repo
string | pull_number
int64 | instance_id
string | issue_numbers
list | base_commit
string | patch
string | test_patch
string | problem_statement
string | hints_text
string | created_at
string | version
string | updated_at
string | environment_setup_commit
string | FAIL_TO_PASS
list | PASS_TO_PASS
list | FAIL_TO_FAIL
list | PASS_TO_FAIL
list |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JohnnyMorganz/StyLua
| 469
|
JohnnyMorganz__StyLua-469
|
[
"448"
] |
56f144f15b2628282fb4a84344e8daad9b8d6666
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- `--output-format=json` now outputs all (error) messages in JSON format ([#453](https://github.com/JohnnyMorganz/StyLua/issues/453))
- Added WASM build support. Stylua is available on npm for consumption in Node.js or a browser (using a bundler) - https://www.npmjs.com/package/@johnnymorganz/stylua
+- Ignore comments will now be respected before fields inside tables ([#448](https://github.com/JohnnyMorganz/StyLua/issues/448))
### Fixed
- [**Luau**] Fixed spacing lost before a comment within a type generic ([#446](https://github.com/JohnnyMorganz/StyLua/issues/446))
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -108,9 +108,10 @@ AST, flagging any syntax errors or possible code semantics changes. This flag ma
where not every file can be examined for spurious formatting.
### Ignoring parts of a file
-If there is a specific statement within your file which you wish to skip formatting on, you can precede it with `-- stylua: ignore`,
-and it will be skipped over during formatting. This may be useful when there is a specific formatting style you wish to preserve for
-a statement. For example:
+
+To skip formatting a particular part of a file, you can add `-- stylua: ignore` before it.
+This may be useful if there is a particular style you want to preseve for readability, e.g.:
+
```lua
-- stylua: ignore
local matrix = {
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -119,7 +120,9 @@ local matrix = {
{ 0, 0, 0 },
}
```
-You can also disable formatting over a block of code by using `-- stylua: ignore start` / `-- stylua: ignore end` respectively.
+
+Formatting can also be skipped over a block of code using `-- stylua: ignore start` and `-- stylua: ignore end`:
+
```lua
local foo = true
-- stylua: ignore start
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -128,8 +131,8 @@ local baz = 0
-- stylua: ignore end
local foobar = false
```
-Note: this comment must be preceding a statement (same as `-- stylua: ignore`), and cannot cross block scope boundaries
-(i.e. if formatting is disabled, and we exit a block, formatting is automatically re-enabled).
+
+Note that ignoring cannot cross scope boundaries - once a block is exited, formatting will be re-enabled.
### Formatting Ranges
If you only want to format a specific range within a file, you can pass the `--range-start <num>` and/or `--range-end <num>` arguments,
diff --git a/src/context.rs b/src/context.rs
--- a/src/context.rs
+++ b/src/context.rs
@@ -106,33 +106,22 @@ impl Context {
}
if let Some(range) = self.range {
- let mut in_range = true;
-
- if let Some(start_bound) = range.start {
- if let Some(node_start) = node.start_position() {
- if node_start.bytes() < start_bound {
- in_range = false;
- }
+ match (range.start, node.start_position()) {
+ (Some(start_bound), Some(node_start)) if node_start.bytes() < start_bound => {
+ return FormatNode::NotInRange
}
- }
+ _ => (),
+ };
- if let Some(end_bound) = range.end {
- if let Some(node_end) = node.end_position() {
- if node_end.bytes() > end_bound {
- in_range = false;
- }
+ match (range.end, node.end_position()) {
+ (Some(end_bound), Some(node_end)) if node_end.bytes() > end_bound => {
+ return FormatNode::NotInRange
}
+ _ => (),
}
-
- if in_range {
- FormatNode::Normal
- } else {
- FormatNode::NotInRange
- }
- } else {
- // No range provided, therefore always in formatting range
- FormatNode::Normal
}
+
+ FormatNode::Normal
}
pub fn should_omit_string_parens(&self) -> bool {
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -1,5 +1,5 @@
use crate::{
- context::{create_indent_trivia, create_newline_trivia, Context},
+ context::{create_indent_trivia, create_newline_trivia, Context, FormatNode},
fmt_symbol,
formatters::{
expression::{format_expression, hang_expression, is_brackets_string},
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -110,6 +110,12 @@ fn format_field(
table_type: TableType,
shape: Shape,
) -> (Field, Vec<Token>) {
+ match dbg!(ctx.should_format_node(field)) {
+ FormatNode::Skip => return (field.to_owned(), Vec::new()),
+ FormatNode::NotInRange => unreachable!("called format_field on a field not in range"),
+ _ => (),
+ }
+
let leading_trivia = match table_type {
TableType::MultiLine => FormatTriviaType::Append(vec![create_indent_trivia(ctx, shape)]),
_ => FormatTriviaType::NoChange,
|
diff --git /dev/null b/tests/inputs-ignore/ignore-table-field.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/ignore-table-field.lua
@@ -0,0 +1,20 @@
+local foo = {
+ -- stylua: ignore
+ x = 2,
+ y = 3,
+ z = " he " ,
+}
+
+local bar = {
+ x = 2,
+ -- stylua: ignore
+ y = 3,
+ z = " he " ,
+}
+
+local baz = {
+ x = 2,
+ y = 3,
+ -- stylua: ignore
+ z = " he " ,
+}
diff --git /dev/null b/tests/inputs-ignore/multiline-block-ignore-1.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/multiline-block-ignore-1.lua
@@ -0,0 +1,5 @@
+local foo = bar
+-- stylua: ignore start
+local bar = baz
+-- stylua: ignore end
+local bar = baz
diff --git /dev/null b/tests/inputs-ignore/multiline-block-ignore-2.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/multiline-block-ignore-2.lua
@@ -0,0 +1,6 @@
+local foo = bar
+-- stylua: ignore start
+local bar = baz
+local bar = baz
+-- stylua: ignore end
+local bar = baz
diff --git /dev/null b/tests/inputs-ignore/multiline-block-ignore-multiple-comments-leading-trivia.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/multiline-block-ignore-multiple-comments-leading-trivia.lua
@@ -0,0 +1,17 @@
+--stylua: ignore start
+local a = 1
+--stylua: ignore end
+
+--stylua: ignore start
+local b = 2
+--stylua: ignore end
+
+--stylua: ignore start
+local c = 3
+--stylua: ignore end
+
+-- Some very large comment
+
+--stylua: ignore start
+local d = 4
+--stylua: ignore end
diff --git /dev/null b/tests/inputs-ignore/multiline-block-ignore-no-ending.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/multiline-block-ignore-no-ending.lua
@@ -0,0 +1,5 @@
+local foo = bar
+-- stylua: ignore start
+local bar = baz
+local bar = baz
+local bar = baz
diff --git /dev/null b/tests/inputs-ignore/multiline-block-ignore-no-starting.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/multiline-block-ignore-no-starting.lua
@@ -0,0 +1,5 @@
+local foo = bar
+local bar = baz
+local bar = baz
+-- stylua: ignore end
+local bar = baz
diff --git /dev/null b/tests/inputs-ignore/multiline-block-ignore-scope-no-ending.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/multiline-block-ignore-scope-no-ending.lua
@@ -0,0 +1,7 @@
+local foo = bar
+do
+ -- stylua: ignore start
+ local bar = baz
+ local bar = baz
+end
+local bar = baz
diff --git /dev/null b/tests/inputs-ignore/multiline-block-ignore-scope.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/multiline-block-ignore-scope.lua
@@ -0,0 +1,8 @@
+local foo = bar
+do
+ -- stylua: ignore start
+ local bar = baz
+ -- stylua: ignore end
+ local bar = baz
+end
+local bar = baz
diff --git /dev/null b/tests/inputs-ignore/singleline-ignore-1.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/singleline-ignore-1.lua
@@ -0,0 +1,3 @@
+local foo = bar
+-- stylua: ignore
+local bar = baz
diff --git /dev/null b/tests/inputs-ignore/singleline-ignore-2.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/singleline-ignore-2.lua
@@ -0,0 +1,4 @@
+local foo = bar
+-- stylua: ignore
+local bar = baz
+local bar = baz
diff --git /dev/null b/tests/inputs-ignore/singleline-ignore-last-stmt.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/singleline-ignore-last-stmt.lua
@@ -0,0 +1,2 @@
+-- stylua: ignore
+return "hi"
diff --git /dev/null b/tests/inputs-ignore/singleline-ignore-stmt-block.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-ignore/singleline-ignore-stmt-block.lua
@@ -0,0 +1,5 @@
+local x = 1
+-- stylua: ignore
+function foo ()
+ return x + 1
+end
diff --git /dev/null b/tests/snapshots/tests__ignores@ignore-table-field.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@ignore-table-field.lua.snap
@@ -0,0 +1,27 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+local foo = {
+ -- stylua: ignore
+ x = 2,
+ y = 3,
+ z = " he ",
+}
+
+local bar = {
+ x = 2,
+ -- stylua: ignore
+ y = 3,
+ z = " he ",
+}
+
+local baz = {
+ x = 2,
+ y = 3,
+ -- stylua: ignore
+ z = " he " ,
+}
+
diff --git /dev/null b/tests/snapshots/tests__ignores@multiline-block-ignore-1.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@multiline-block-ignore-1.lua.snap
@@ -0,0 +1,12 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+local foo = bar
+-- stylua: ignore start
+local bar = baz
+-- stylua: ignore end
+local bar = baz
+
diff --git /dev/null b/tests/snapshots/tests__ignores@multiline-block-ignore-2.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@multiline-block-ignore-2.lua.snap
@@ -0,0 +1,13 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+local foo = bar
+-- stylua: ignore start
+local bar = baz
+local bar = baz
+-- stylua: ignore end
+local bar = baz
+
diff --git /dev/null b/tests/snapshots/tests__ignores@multiline-block-ignore-multiple-comments-leading-trivia.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@multiline-block-ignore-multiple-comments-leading-trivia.lua.snap
@@ -0,0 +1,24 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+--stylua: ignore start
+local a = 1
+--stylua: ignore end
+
+--stylua: ignore start
+local b = 2
+--stylua: ignore end
+
+--stylua: ignore start
+local c = 3
+--stylua: ignore end
+
+-- Some very large comment
+
+--stylua: ignore start
+local d = 4
+--stylua: ignore end
+
diff --git /dev/null b/tests/snapshots/tests__ignores@multiline-block-ignore-no-ending.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@multiline-block-ignore-no-ending.lua.snap
@@ -0,0 +1,12 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+local foo = bar
+-- stylua: ignore start
+local bar = baz
+local bar = baz
+local bar = baz
+
diff --git /dev/null b/tests/snapshots/tests__ignores@multiline-block-ignore-no-starting.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@multiline-block-ignore-no-starting.lua.snap
@@ -0,0 +1,12 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+local foo = bar
+local bar = baz
+local bar = baz
+-- stylua: ignore end
+local bar = baz
+
diff --git /dev/null b/tests/snapshots/tests__ignores@multiline-block-ignore-scope-no-ending.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@multiline-block-ignore-scope-no-ending.lua.snap
@@ -0,0 +1,14 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+local foo = bar
+do
+ -- stylua: ignore start
+ local bar = baz
+ local bar = baz
+end
+local bar = baz
+
diff --git /dev/null b/tests/snapshots/tests__ignores@multiline-block-ignore-scope.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@multiline-block-ignore-scope.lua.snap
@@ -0,0 +1,15 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+local foo = bar
+do
+ -- stylua: ignore start
+ local bar = baz
+ -- stylua: ignore end
+ local bar = baz
+end
+local bar = baz
+
diff --git /dev/null b/tests/snapshots/tests__ignores@singleline-ignore-1.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@singleline-ignore-1.lua.snap
@@ -0,0 +1,10 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+local foo = bar
+-- stylua: ignore
+local bar = baz
+
diff --git /dev/null b/tests/snapshots/tests__ignores@singleline-ignore-2.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@singleline-ignore-2.lua.snap
@@ -0,0 +1,11 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+local foo = bar
+-- stylua: ignore
+local bar = baz
+local bar = baz
+
diff --git /dev/null b/tests/snapshots/tests__ignores@singleline-ignore-last-stmt.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@singleline-ignore-last-stmt.lua.snap
@@ -0,0 +1,9 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+-- stylua: ignore
+return "hi"
+
diff --git /dev/null b/tests/snapshots/tests__ignores@singleline-ignore-stmt-block.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__ignores@singleline-ignore-stmt-block.lua.snap
@@ -0,0 +1,12 @@
+---
+source: tests/tests.rs
+assertion_line: 56
+expression: format(&contents)
+
+---
+local x = 1
+-- stylua: ignore
+function foo ()
+ return x + 1
+end
+
diff --git a/tests/test_ignore.rs /dev/null
--- a/tests/test_ignore.rs
+++ /dev/null
@@ -1,258 +0,0 @@
-use stylua_lib::{format_code, Config, OutputVerification};
-
-fn format(input: &str) -> String {
- format_code(input, Config::default(), None, OutputVerification::None).unwrap()
-}
-
-#[test]
-fn test_singleline_ignore() {
- insta::assert_snapshot!(
- format(
- r###"
-local foo = bar
--- stylua: ignore
-local bar = baz
- "###
- ),
- @r###"
- local foo = bar
- -- stylua: ignore
- local bar = baz
- "###
- );
-}
-
-#[test]
-fn test_singleline_ignore_2() {
- insta::assert_snapshot!(
- format(
- r###"
-local foo = bar
--- stylua: ignore
-local bar = baz
-local bar = baz
- "###
- ),
- @r###"
- local foo = bar
- -- stylua: ignore
- local bar = baz
- local bar = baz
- "###
- );
-}
-
-#[test]
-fn test_singleline_ignore_last_stmt() {
- insta::assert_snapshot!(
- format(
- r###"-- stylua: ignore
-return "hi"
- "###
- ),
- @r###"
- -- stylua: ignore
- return "hi"
- "###
- );
-}
-
-#[test]
-fn test_singleline_ignore_stmt_block() {
- insta::assert_snapshot!(
- r###"local x = 1
--- stylua: ignore
-function foo ()
- return x + 1
-end"###, @r###"
- local x = 1
- -- stylua: ignore
- function foo ()
- return x + 1
- end
- "###
- )
-}
-
-#[test]
-fn test_multiline_block_ignore() {
- insta::assert_snapshot!(
- format(
- r###"
-local foo = bar
--- stylua: ignore start
-local bar = baz
--- stylua: ignore end
-local bar = baz
-"###
- ),
- @r###"
- local foo = bar
- -- stylua: ignore start
- local bar = baz
- -- stylua: ignore end
- local bar = baz
- "###);
-}
-
-#[test]
-fn test_multiline_block_ignore_2() {
- insta::assert_snapshot!(
- format(
- r###"
-local foo = bar
--- stylua: ignore start
-local bar = baz
-local bar = baz
--- stylua: ignore end
-local bar = baz
-"###
- ),
- @r###"
- local foo = bar
- -- stylua: ignore start
- local bar = baz
- local bar = baz
- -- stylua: ignore end
- local bar = baz
- "###);
-}
-
-#[test]
-fn test_multiline_block_ignore_no_ending() {
- insta::assert_snapshot!(
- format(
- r###"
-local foo = bar
--- stylua: ignore start
-local bar = baz
-local bar = baz
-local bar = baz
-"###
- ),
- @r###"
- local foo = bar
- -- stylua: ignore start
- local bar = baz
- local bar = baz
- local bar = baz
- "###);
-}
-
-#[test]
-fn test_multiline_block_ignore_no_starting() {
- insta::assert_snapshot!(
- format(
- r###"
-local foo = bar
-local bar = baz
-local bar = baz
--- stylua: ignore end
-local bar = baz
-"###
- ),
- @r###"
- local foo = bar
- local bar = baz
- local bar = baz
- -- stylua: ignore end
- local bar = baz
- "###);
-}
-
-#[test]
-fn test_multiline_block_ignore_block_scope() {
- insta::assert_snapshot!(
- format(
- r###"
-local foo = bar
-do
- -- stylua: ignore start
- local bar = baz
- -- stylua: ignore end
- local bar = baz
-end
-local bar = baz
-"###
- ),
- @r###"
- local foo = bar
- do
- -- stylua: ignore start
- local bar = baz
- -- stylua: ignore end
- local bar = baz
- end
- local bar = baz
- "###);
-}
-
-#[test]
-fn test_multiline_block_ignore_block_scope_no_ending() {
- insta::assert_snapshot!(
- format(
- r###"
-local foo = bar
-do
- -- stylua: ignore start
- local bar = baz
- local bar = baz
-end
-local bar = baz
-"###
- ),
- @r###"
- local foo = bar
- do
- -- stylua: ignore start
- local bar = baz
- local bar = baz
- end
- local bar = baz
- "###);
-}
-
-#[test]
-fn test_multiline_block_ignore_multiple_comments_in_leading_trivia() {
- insta::assert_snapshot!(
- format(
- r###"--stylua: ignore start
-local a = 1
---stylua: ignore end
-
---stylua: ignore start
-local b = 2
---stylua: ignore end
-
---stylua: ignore start
-local c = 3
---stylua: ignore end
-
--- Some very large comment
-
---stylua: ignore start
-local d = 4
---stylua: ignore end
-"###
- ),
- @r###"
- --stylua: ignore start
- local a = 1
- --stylua: ignore end
-
- --stylua: ignore start
- local b = 2
- --stylua: ignore end
-
- --stylua: ignore start
- local c = 3
- --stylua: ignore end
-
- -- Some very large comment
-
- --stylua: ignore start
- local d = 4
- --stylua: ignore end
- "###
- )
-}
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -1,6 +1,6 @@
use stylua_lib::{format_code, Config, OutputVerification, Range};
-fn format(input: &str, range: Range) -> String {
+fn format_range(input: &str, range: Range) -> String {
format_code(
input,
Config::default(),
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -10,15 +10,26 @@ fn format(input: &str, range: Range) -> String {
.unwrap()
}
+fn format(input: &str) -> String {
+ let start_point = input.find("||");
+ let end_point = input.rfind("||");
+
+ format_code(
+ &input.replace("||", ""),
+ Config::default(),
+ Some(Range::from_values(start_point, end_point)),
+ OutputVerification::None,
+ )
+ .unwrap()
+}
+
#[test]
fn test_default() {
insta::assert_snapshot!(
format(
- r###"
-local foo = bar
+ r###"||local foo = bar||
local bar = baz
"###,
- Range::from_values(Some(0), Some(30))
),
@r###"
local foo = bar
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -32,10 +43,9 @@ local bar = baz
fn test_ignore_last_stmt() {
insta::assert_snapshot!(
format(
- r###"function foo()
+ r###"||f||unction foo()
return bar
-end"###,
- Range::from_values(Some(0), Some(1))
+end"###
),
@r###"
function foo()
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -48,17 +58,16 @@ end"###,
fn test_dont_modify_eof() {
insta::assert_snapshot!(
format(
- r###"
-local foo = bar
+ r###"||local foo = bar||
local bar = baz
- "###,
- Range::from_values(Some(0), Some(30))
+ "###
),
@r###"
+
local foo = bar
local bar = baz
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -73,8 +82,7 @@ local bar = baz
fn test_incomplete_range() {
insta::assert_snapshot!(
format(
- r###"local fooo = bar"###,
- Range::from_values(Some(0), Some(5))
+ r###"||local|| fooo = bar"###
),
@r###"
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -87,8 +95,7 @@ fn test_incomplete_range() {
fn test_large_example() {
insta::assert_snapshot!(
format(
- r###"
-if string.sub(msg, 1, 8) == "setgrav/" then
+ r###"||if string.sub(msg, 1, 8) == "setgrav/" then
danumber = nil for i = 9, 100 do if string.sub(msg, i, i) == "/" then danumber = i break end end if danumber == nil then
return end local player = findplayer(string.sub(msg, 9, danumber - 1), speaker)
if player == 0 then return end for i = 1, #player do if player[i].Character ~= nil then
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -101,7 +108,7 @@ bf.Parent = torso end local c2 = player[i].Character:GetChildren()
for i = 1, #c2 do if c2[i].className == "Part" then
torso.BF.force = torso.BF.force
+ Vector3.new(0, c2[i]:getMass() * -string.sub(msg, danumber + 1), 0)
-end end end end end end
+end end end end end end||
if string.sub(msg, 1, 5) == "trip/" then local player = findplayer(string.sub(msg, 6), speaker)
if player ~= 0 then for i = 1, #player do
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -109,10 +116,10 @@ if player[i].Character ~= nil then
local torso = player[i].Character:FindFirstChild("Torso")
if torso ~= nil then torso.CFrame = CFrame.new(torso.Position.x, torso.Position.y, torso.Position.z, 0, 0, 1, 0, -1, 0, 1, 0, 0) --math.random(),math.random(),math.random(),math.random(),math.random(),math.random(),math.random(),math.random(),math.random()) -- i like the people being upside down better.
end end end end end
- "###,
- Range::from_values(Some(0), Some(847))
+ "###
),
@r###"
+
if string.sub(msg, 1, 8) == "setgrav/" then
danumber = nil
for i = 9, 100 do
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -168,10 +175,9 @@ fn test_nested_range() {
insta::assert_snapshot!(
format(
r###"local my_function = function()
- local nested_statement = "foobar"
+ ||local nested_statement = "foobar"||
end
-"###,
- Range::from_values(Some(33), Some(76))
+"###
),
@r###"
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -187,11 +193,10 @@ fn test_nested_range_local_function() {
format(
r###"local function test()
call "hello"
- call { x = y}
- local z = 1 + 3 - (2 / 3)
+ ||call { x = y}
+ local z = 1 + 3 - (2 / 3)||
end
-"###,
- Range::from_values(Some(33), Some(116))
+"###
),
@r###"
local function test()
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -207,10 +212,9 @@ fn test_nested_range_while() {
insta::assert_snapshot!(
format(
r###"while true do
- local z = 2
+ ||local z = 2||
end
-"###,
- Range::from_values(Some(21), Some(47))
+"###
),
@r###"
while true do
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -223,11 +227,10 @@ fn test_nested_range_while() {
fn test_nested_range_repeat() {
insta::assert_snapshot!(
format(
- r###"repeat
- local z = 2
+ r###"repeat||
+ local z = 2||
until true
-"###,
- Range::from_values(Some(6), Some(32))
+"###
),
@r###"
repeat
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -241,10 +244,9 @@ fn test_nested_range_do() {
insta::assert_snapshot!(
format(
r###"do
- local z = 2
+ ||local z = 2||
end
-"###,
- Range::from_values(Some(2), Some(32))
+"###
),
@r###"
do
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -258,10 +260,9 @@ fn test_nested_range_generic_for() {
insta::assert_snapshot!(
format(
r###"for i, v in pairs(x) do
- local z = 2
+ ||local z = 2||
end
-"###,
- Range::from_values(Some(30), Some(56))
+"###
),
@r###"
for i, v in pairs(x) do
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -277,10 +278,9 @@ fn test_nested_range_else_if() {
r###"if x and y then
local p = q
elseif c - d > 2 then
- local z = 2
+ ||local z = 2||
end
-"###,
- Range::from_values(Some(69), Some(95))
+"###
),
@r###"
if x and y then
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -296,10 +296,9 @@ fn test_nested_range_function_call() {
insta::assert_snapshot!(
format(
r###"call (function ()
- local z = 5
+ ||local z = 5||
end)
-"###,
- Range::from_values(Some(22), Some(58))
+"###
),
@r###"
call (function ()
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -313,10 +312,9 @@ fn test_nested_range_function_call_table() {
insta::assert_snapshot!(
format(
r###"call { x = function()
- local z = 2
+ ||local z = 2||
end}
-"###,
- Range::from_values(Some(28), Some(61))
+"###
),
@r###"
call { x = function()
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -331,11 +329,10 @@ fn test_nested_range_table_1() {
format(
r###"local z = {
function()
- local z = 5
+ ||local z = 5||
end
}
-"###,
- Range::from_values(Some(50), Some(121))
+"###
),
@r###"
local z = {
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -352,12 +349,11 @@ fn test_nested_range_table_2() {
format(
r###"local z = {
[(function()
- return random_func ()
+ ||return random_func ()||
end)()] = true
}
-"###,
- Range::from_values(Some(41), Some(121))
+"###
),
@r###"
local z = {
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -374,10 +370,9 @@ fn test_nested_range_binop() {
insta::assert_snapshot!(
format(
r###"local z =( 1 + (function()
- local p = q
+ ||local p = q||
end)())
-"###,
- Range::from_values(Some(40), Some(75))
+"###
),
@r###"
local z =( 1 + (function()
diff --git a/tests/test_ranges.rs b/tests/test_ranges.rs
--- a/tests/test_ranges.rs
+++ b/tests/test_ranges.rs
@@ -385,3 +380,34 @@ fn test_nested_range_binop() {
end)())
"###);
}
+
+#[test]
+fn test_no_range_start() {
+ insta::assert_snapshot!(
+ format_range(
+ r###"local z = 2
+local e = 5
+"###,
+ Range::from_values(None, Some(20))
+ ),
+ @r###"
+ local z = 2
+ local e = 5
+ "###);
+}
+
+#[test]
+fn test_no_range_end() {
+ insta::assert_snapshot!(
+ format_range(
+ r###"local z = 2
+local e = 5
+"###,
+ Range::from_values(Some(20), None)
+ ),
+ @r###"
+
+ local z = 2
+ local e = 5
+ "###);
+}
diff --git a/tests/tests.rs b/tests/tests.rs
--- a/tests/tests.rs
+++ b/tests/tests.rs
@@ -48,3 +48,11 @@ fn test_lua52() {
insta::assert_snapshot!(format(&contents));
})
}
+
+#[test]
+fn test_ignores() {
+ insta::glob!("inputs-ignore/*.lua", |path| {
+ let contents = std::fs::read_to_string(path).unwrap();
+ insta::assert_snapshot!(format(&contents));
+ })
+}
|
Allow ignore comments to be used in places other than before statements
Currently, the only place ignore comments will be registered if they are leading trivia before statements.
This can be confusing, especially when you place a comment somewhere but it does not do anything.
We should be able to handle ignore comments in most locations. A key location to start with is before a field within a table (we may want to specifically ignore a single field). The only thing to consider is the impact that ignoring has on the remaining formatted code.
|
2022-06-25T19:22:24Z
|
0.13
|
2022-06-25T12:18:38Z
|
69c9278e551be7681578e01e6ab16cf6b05c82c5
|
[
"test_ignores"
] |
[
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments",
"tests::test_config_call_parentheses",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments_2",
"formatters::trivia_util::tests::test_token_contains_singleline_comments",
"tests::test_config_indent_type",
"tests::test_config_column_width",
"tests::test_config_indent_width",
"tests::test_config_quote_style",
"tests::test_config_line_endings",
"tests::test_invalid_input",
"verify_ast::tests::test_equivalent_asts",
"verify_ast::tests::test_different_asts",
"verify_ast::tests::test_different_binary_numbers",
"verify_ast::tests::test_equivalent_binary_numbers",
"verify_ast::tests::test_different_hex_numbers",
"tests::test_entry_point",
"verify_ast::tests::test_equivalent_conditions",
"verify_ast::tests::test_equivalent_hex_numbers",
"tests::test_with_ast_verification",
"verify_ast::tests::test_equivalent_string_escapes",
"verify_ast::tests::test_equivalent_string_quote_types",
"verify_ast::tests::test_equivalent_function_calls",
"verify_ast::tests::test_equivalent_numbers",
"verify_ast::tests::test_equivalent_stmt_semicolons",
"verify_ast::tests::test_equivalent_numbers_2",
"verify_ast::tests::test_equivalent_function_calls_2",
"verify_ast::tests::test_equivalent_table_separators",
"output_diff::tests::test_addition_diff",
"output_diff::tests::test_no_diff",
"output_diff::tests::test_deletion_diff",
"output_diff::tests::test_change_diff",
"opt::tests::verify_opt",
"config::tests::test_override_indent_width",
"config::tests::test_override_column_width",
"config::tests::test_override_line_endings",
"config::tests::test_override_quote_style",
"config::tests::test_override_call_parentheses",
"config::tests::test_override_indent_type",
"tests::test_no_files_provided",
"tests::test_format_stdin",
"test_call_parens_comments",
"test_call_parens_semicolons",
"test_call_parens_none_handles_string_correctly",
"test_call_parens_no_single_string_handles_string_correctly",
"test_call_parens_none_handles_table_correctly",
"test_call_parens_always_handles_string_correctly",
"test_call_parens_no_single_table_handles_table_correctly",
"test_call_parens_no_single_string_handles_table_correctly",
"test_call_parens_always_handles_table_correctly",
"test_call_parens_no_single_table_handles_string_correctly",
"test_call_parens_has_no_affect_on_multi_arg_fn_calls_",
"test_omit_parens_brackets_string",
"test_no_parens_brackets_string",
"test_no_parens_singleline_table",
"test_no_parens_multiline_table",
"test_no_parens_string",
"test_omit_parens_string",
"test_no_parens_method_chain_2",
"test_keep_parens_binop_string",
"test_no_parens_method_chain_1",
"test_no_parens_large_example",
"test_force_single_quotes",
"test_force_double_quotes",
"test_auto_prefer_single_quotes",
"test_auto_prefer_double_quotes",
"test_nested_range_function_call",
"test_incomplete_range",
"test_nested_range_do",
"test_ignore_last_stmt",
"test_nested_range_else_if",
"test_dont_modify_eof",
"test_nested_range_function_call_table",
"test_nested_range_generic_for",
"test_nested_range",
"test_default",
"test_nested_range_binop",
"test_nested_range_repeat",
"test_no_range_end",
"test_no_range_start",
"test_nested_range_while",
"test_nested_range_table_1",
"test_nested_range_table_2",
"test_nested_range_local_function",
"test_large_example",
"test_lua52",
"test_luau_full_moon",
"test_luau"
] |
[] |
[] |
|
JohnnyMorganz/StyLua
| 422
|
JohnnyMorganz__StyLua-422
|
[
"421"
] |
30c713bc68d31b45fcfba1227bc6fbd4df97cba2
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Fixed issue through static linking where Windows binary would not execute due to missing `VCRUNTIME140.dll`. ([#413](https://github.com/JohnnyMorganz/StyLua/issues/413))
- Fixed assignment with comment sometimes not hanging leading to malformed syntax. ([#416](https://github.com/JohnnyMorganz/StyLua/issues/416))
+- Fixed block ignores not applied when multiple leading block ignore comments are present at once. ([#421](https://github.com/JohnnyMorganz/StyLua/issues/421))
## [0.12.5] - 2022-03-08
### Fixed
diff --git a/src/context.rs b/src/context.rs
--- a/src/context.rs
+++ b/src/context.rs
@@ -44,33 +44,36 @@ impl Context {
// To preserve immutability of Context, we return a new Context with the `formatting_disabled` field toggled or left the same
// where necessary. Context is cheap so this is reasonable to do.
pub fn check_toggle_formatting(&self, node: &impl Node) -> Self {
- // Check comments
+ // Load all the leading comments from the token
let leading_trivia = node.surrounding_trivia().0;
- for trivia in leading_trivia {
- let comment_lines = match trivia.token_type() {
- TokenType::SingleLineComment { comment } => comment,
- TokenType::MultiLineComment { comment, .. } => comment,
- _ => continue,
- }
- .lines()
- .map(|line| line.trim());
-
- for line in comment_lines {
- if line == "stylua: ignore start" && !self.formatting_disabled {
- return Self {
- formatting_disabled: true,
- ..*self
- };
- } else if line == "stylua: ignore end" && self.formatting_disabled {
- return Self {
- formatting_disabled: false,
- ..*self
- };
+ let comment_lines = leading_trivia
+ .iter()
+ .filter_map(|trivia| {
+ match trivia.token_type() {
+ TokenType::SingleLineComment { comment } => Some(comment),
+ TokenType::MultiLineComment { comment, .. } => Some(comment),
+ _ => None,
}
+ .map(|comment| comment.lines().map(|line| line.trim()))
+ })
+ .flatten();
+
+ // Load the current formatting disabled state
+ let mut formatting_disabled = self.formatting_disabled;
+
+ // Work through all the lines and update the state as necessary
+ for line in comment_lines {
+ if line == "stylua: ignore start" {
+ formatting_disabled = true;
+ } else if line == "stylua: ignore end" {
+ formatting_disabled = false;
}
}
- *self
+ Self {
+ formatting_disabled,
+ ..*self
+ }
}
/// Checks whether we should format the given node.
|
diff --git a/tests/test_ignore.rs b/tests/test_ignore.rs
--- a/tests/test_ignore.rs
+++ b/tests/test_ignore.rs
@@ -211,3 +211,48 @@ local bar = baz
local bar = baz
"###);
}
+
+#[test]
+fn test_multiline_block_ignore_multiple_comments_in_leading_trivia() {
+ insta::assert_snapshot!(
+ format(
+ r###"--stylua: ignore start
+local a = 1
+--stylua: ignore end
+
+--stylua: ignore start
+local b = 2
+--stylua: ignore end
+
+--stylua: ignore start
+local c = 3
+--stylua: ignore end
+
+-- Some very large comment
+
+--stylua: ignore start
+local d = 4
+--stylua: ignore end
+"###
+ ),
+ @r###"
+ --stylua: ignore start
+ local a = 1
+ --stylua: ignore end
+
+ --stylua: ignore start
+ local b = 2
+ --stylua: ignore end
+
+ --stylua: ignore start
+ local c = 3
+ --stylua: ignore end
+
+ -- Some very large comment
+
+ --stylua: ignore start
+ local d = 4
+ --stylua: ignore end
+ "###
+ )
+}
|
Block ignore is not applied to all back-to-back blocks
When `--stylua: ignore start/end` comments are applied back-to-back, they take effect on every second ignored block. This might be considered as a non-issue because they can be merged into one single ignored block, but it might be inconvenient when they are separated with large comment block.
My understanding is that "this comment must be preceding a statement (same as `-- stylua: ignore`), and cannot cross block scope boundaries" holds here, although I am not sure about it.
Steps to reproduce:
- Create file `tmp.lua` with the following contents:
```lua
--stylua: ignore start
local a = 1
--stylua: ignore end
--stylua: ignore start
local b = 2
--stylua: ignore end
--stylua: ignore start
local c = 3
--stylua: ignore end
-- Some very large comment
--stylua: ignore start
local d = 4
--stylua: ignore end
```
- Run `stylua tmp.lua`.
Currently observed output:
```lua
--stylua: ignore start
local a = 1
--stylua: ignore end
--stylua: ignore start
local b = 2
--stylua: ignore end
--stylua: ignore start
local c = 3
--stylua: ignore end
-- Some very large comment
--stylua: ignore start
local d = 4
--stylua: ignore end
```
Details:
- Version of StyLua: 0.12.5
- OS: Xubuntu 20.04.
|
Yeah, this is a bug - it seems as though we are not correctly re-opening an ignore section when we see the `--stylua: ignore start` comment.
This code is actually parsed as these separate statements:
```lua
--stylua: ignore start
local a = 1
---------------------------
--stylua: ignore end
--stylua: ignore start
local b = 2
```
where `--stylua: ignore end` and `--stylua: ignore start` are both leading trivia of the `local b` statement.
We are probably exiting early when we see the `--stylua: ignore end` comment in the leading trivia, but we should continue scanning in case we find another ignore comment afterwards
|
2022-03-27T21:08:32Z
|
0.12
|
2022-03-27T13:12:43Z
|
a369d02342f3b1432ff89c619c97129a57678141
|
[
"test_multiline_block_ignore_multiple_comments_in_leading_trivia"
] |
[
"formatters::trivia_util::tests::test_token_contains_singleline_comments",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments_2",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments",
"tests::test_config_call_parentheses",
"tests::test_config_column_width",
"tests::test_config_indent_type",
"tests::test_config_indent_width",
"tests::test_config_quote_style",
"tests::test_config_line_endings",
"tests::test_invalid_input",
"verify_ast::tests::test_different_binary_numbers",
"verify_ast::tests::test_equivalent_binary_numbers",
"verify_ast::tests::test_different_asts",
"verify_ast::tests::test_different_hex_numbers",
"verify_ast::tests::test_equivalent_asts",
"tests::test_with_ast_verification",
"verify_ast::tests::test_equivalent_hex_numbers",
"tests::test_entry_point",
"verify_ast::tests::test_equivalent_function_calls",
"verify_ast::tests::test_equivalent_conditions",
"verify_ast::tests::test_equivalent_numbers",
"verify_ast::tests::test_equivalent_stmt_semicolons",
"verify_ast::tests::test_equivalent_numbers_2",
"verify_ast::tests::test_equivalent_string_escapes",
"verify_ast::tests::test_equivalent_function_calls_2",
"verify_ast::tests::test_equivalent_string_quote_types",
"verify_ast::tests::test_equivalent_table_separators",
"output_diff::tests::test_no_diff",
"output_diff::tests::test_addition_diff",
"output_diff::tests::test_deletion_diff",
"output_diff::tests::test_change_diff",
"opt::tests::verify_opt",
"config::tests::test_override_column_width",
"config::tests::test_override_line_endings",
"config::tests::test_override_indent_type",
"config::tests::test_override_quote_style",
"config::tests::test_override_indent_width",
"config::tests::test_override_call_parentheses",
"tests::test_no_files_provided",
"tests::test_format_stdin",
"test_call_parens_comments",
"test_call_parens_semicolons",
"test_call_parens_no_single_string_handles_string_correctly",
"test_call_parens_none_handles_string_correctly",
"test_call_parens_no_single_table_handles_string_correctly",
"test_call_parens_always_handles_string_correctly",
"test_call_parens_none_handles_table_correctly",
"test_call_parens_no_single_table_handles_table_correctly",
"test_call_parens_always_handles_table_correctly",
"test_call_parens_no_single_string_handles_table_correctly",
"test_call_parens_has_no_affect_on_multi_arg_fn_calls_",
"test_singleline_ignore_stmt_block",
"test_singleline_ignore",
"test_singleline_ignore_last_stmt",
"test_multiline_block_ignore_block_scope_no_ending",
"test_multiline_block_ignore",
"test_multiline_block_ignore_2",
"test_singleline_ignore_2",
"test_multiline_block_ignore_block_scope",
"test_multiline_block_ignore_no_ending",
"test_multiline_block_ignore_no_starting",
"test_no_parens_brackets_string",
"test_omit_parens_brackets_string",
"test_no_parens_singleline_table",
"test_no_parens_string",
"test_no_parens_multiline_table",
"test_omit_parens_string",
"test_keep_parens_binop_string",
"test_no_parens_method_chain_1",
"test_no_parens_method_chain_2",
"test_no_parens_large_example",
"test_force_single_quotes",
"test_auto_prefer_double_quotes",
"test_auto_prefer_single_quotes",
"test_force_double_quotes",
"test_ignore_last_stmt",
"test_nested_range_do",
"test_dont_modify_eof",
"test_default",
"test_nested_range_else_if",
"test_nested_range_generic_for",
"test_nested_range_function_call",
"test_nested_range_binop",
"test_incomplete_range",
"test_nested_range",
"test_nested_range_function_call_table",
"test_nested_range_repeat",
"test_nested_range_while",
"test_nested_range_local_function",
"test_nested_range_table_1",
"test_nested_range_table_2",
"test_large_example",
"test_lua52",
"test_luau_full_moon",
"test_luau"
] |
[] |
[] |
JohnnyMorganz/StyLua
| 131
|
JohnnyMorganz__StyLua-131
|
[
"78"
] |
aa9d9319d0314a853c4f56d3c120525668dc1a8a
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,10 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
- Parentheses around conditions are now removed, as they are not required in Lua. `if (foo and (not bar or baz)) then ... end` turns to `if foo and (not bar or baz) then ... end`
+- Long multi-variable assignments which surpass the column width, even when hanging on the equals token, will now hang on multiple lines.
### Changed
- Changed the heursitics for when parentheses are removed around expressions. Parentheses will now never be removed around a function call prefix (e.g. `("hello"):len()`)
- Changed formatting for comma-separated lists. Previously, we would buffer the comments to the end of the list, but now we keep the comments next to where they original were.
+- Improved contextual formatting informattion when formatting deep in the AST. We can now better determine how much space is left on the current line, before we need to change formatting
+- Improved formatting of function declarations. It will now properly take into account the amount of space left on the column width.
+- Improve formatting for assignments with expressions such as function calls. The whole assignment is now taken into account, so we can better determine whether to split the expression.
## [0.7.1] - 2021-04-19
### Fixed
diff --git a/src/context.rs b/src/context.rs
--- a/src/context.rs
+++ b/src/context.rs
@@ -41,17 +41,6 @@ impl Context {
self.indent_level
}
- /// Returns the size of the current indent level in characters
- pub fn indent_width(&self) -> usize {
- (self.indent_level() - 1) * self.config().indent_width
- }
-
- /// Returns the size of the current indent level in characters, including any additional indent level
- pub fn indent_width_additional(&self, additional_indent_level: Option<usize>) -> usize {
- (self.indent_level() - 1 + additional_indent_level.unwrap_or(0))
- * self.config().indent_width
- }
-
/// Increase the level of indention at the current position of the formatter
pub fn increment_indent_level(&mut self) {
self.indent_level += 1;
diff --git a/src/formatters/assignment.rs b/src/formatters/assignment.rs
--- a/src/formatters/assignment.rs
+++ b/src/formatters/assignment.rs
@@ -5,7 +5,7 @@ use full_moon::ast::{
Assignment, Expression, LocalAssignment,
};
use full_moon::node::Node;
-use full_moon::tokenizer::{TokenKind, TokenReference};
+use full_moon::tokenizer::{Token, TokenKind, TokenReference};
#[cfg(feature = "luau")]
use crate::formatters::luau::format_type_specifier;
diff --git a/src/formatters/assignment.rs b/src/formatters/assignment.rs
--- a/src/formatters/assignment.rs
+++ b/src/formatters/assignment.rs
@@ -13,55 +13,25 @@ use crate::{
context::{create_indent_trivia, create_newline_trivia, Context},
fmt_symbol,
formatters::{
- expression::{format_expression, format_var, hang_expression_no_trailing_newline},
- general::{format_punctuated, format_token_reference_mut, try_format_punctuated},
- trivia::{FormatTriviaType, UpdateLeadingTrivia, UpdateTrailingTrivia},
+ expression::{format_expression, format_var, hang_expression},
+ general::{
+ format_punctuated, format_punctuated_multiline, format_token_reference_mut,
+ try_format_punctuated,
+ },
+ trivia::{
+ strip_leading_trivia, strip_trailing_trivia, strip_trivia, FormatTriviaType,
+ UpdateLeadingTrivia, UpdateTrailingTrivia,
+ },
trivia_util,
util::token_range,
},
+ shape::Shape,
};
-/// Returns an Assignment with leading and trailing trivia removed
-fn strip_assignment_trivia<'ast>(assignment: &Assignment<'ast>) -> Assignment<'ast> {
- let var_list = assignment
- .variables()
- .update_leading_trivia(FormatTriviaType::Replace(vec![]));
- let expr_list = assignment
- .expressions()
- .update_trailing_trivia(FormatTriviaType::Replace(vec![]));
-
- Assignment::new(var_list, expr_list).with_equal_token(assignment.equal_token().to_owned())
-}
-
-/// Returns a LocalAssignment with leading and trailing trivia removed
-fn strip_local_assignment_trivia<'ast>(
- local_assignment: &LocalAssignment<'ast>,
-) -> LocalAssignment<'ast> {
- let local_token = local_assignment
- .local_token()
- .update_leading_trivia(FormatTriviaType::Replace(vec![]));
-
- if local_assignment.expressions().is_empty() {
- let name_list = local_assignment
- .names()
- .update_trailing_trivia(FormatTriviaType::Replace(vec![]));
-
- LocalAssignment::new(name_list).with_local_token(local_token)
- } else {
- let expr_list = local_assignment
- .expressions()
- .update_trailing_trivia(FormatTriviaType::Replace(vec![]));
-
- LocalAssignment::new(local_assignment.names().to_owned())
- .with_local_token(local_token)
- .with_equal_token(local_assignment.equal_token().map(|x| x.to_owned()))
- .with_expressions(expr_list)
- }
-}
-
-fn hang_punctuated_list<'ast>(
+pub fn hang_punctuated_list<'ast>(
ctx: &mut Context,
punctuated: &Punctuated<'ast, Expression<'ast>>,
+ shape: Shape,
additional_indent_level: Option<usize>,
) -> Punctuated<'ast, Expression<'ast>> {
// Add the expression list into the indent range, as it will be indented by one
diff --git a/src/formatters/assignment.rs b/src/formatters/assignment.rs
--- a/src/formatters/assignment.rs
+++ b/src/formatters/assignment.rs
@@ -69,138 +39,181 @@ fn hang_punctuated_list<'ast>(
.range()
.expect("no range for assignment punctuated list");
ctx.add_indent_range((expr_range.0.bytes(), expr_range.1.bytes()));
+
let mut output = Punctuated::new();
+ let mut shape = shape;
// Format each expression and hang them
// We need to format again because we will now take into account the indent increase
for pair in punctuated.pairs() {
- let expr = format_expression(ctx, pair.value());
- let value = hang_expression_no_trailing_newline(ctx, expr, additional_indent_level, None);
+ let value = hang_expression(ctx, pair.value(), shape, additional_indent_level, None);
+ shape = shape.take_last_line(&strip_trivia(&value));
+
output.push(Pair::new(
value,
pair.punctuation().map(|x| fmt_symbol!(ctx, x, ", ")),
- ))
+ ));
+ shape = shape + 2; // 2 = ", "
}
output
}
-/// Checks the list of assigned expressions to see if any were hangable.
-/// If not, then we still have a long list of assigned expressions - we split it onto a newline at the equal token.
+/// Hangs at the equal token, and indents the first item.
/// Returns the new equal token [`TokenReference`]
-fn check_long_expression<'ast>(
+fn hang_equal_token<'ast>(
ctx: &mut Context,
- expressions: &Punctuated<'ast, Expression<'ast>>,
equal_token: TokenReference<'ast>,
additional_indent_level: Option<usize>,
) -> TokenReference<'ast> {
- // See if any of our expressions were hangable.
- // If not, then its still a big long line - we should newline at the end of the equals token,
- // then indent the first item
- if !expressions
- .iter()
- .any(|x| trivia_util::can_hang_expression(x))
- {
- let equal_token_trailing_trivia = vec![
- create_newline_trivia(ctx),
- create_indent_trivia(ctx, additional_indent_level.or(Some(0)).map(|x| x + 1)),
- ]
- .iter()
- .chain(
- // Remove the space that was present after the equal token
- equal_token
- .trailing_trivia()
- .skip_while(|x| x.token_kind() == TokenKind::Whitespace),
- )
- .map(|x| x.to_owned())
- .collect();
-
- equal_token.update_trailing_trivia(FormatTriviaType::Replace(equal_token_trailing_trivia))
- } else {
+ let equal_token_trailing_trivia = vec![
+ create_newline_trivia(ctx),
+ create_indent_trivia(ctx, additional_indent_level.or(Some(0)).map(|x| x + 1)),
+ ]
+ .iter()
+ .chain(
+ // Remove the space that was present after the equal token
equal_token
- }
+ .trailing_trivia()
+ .skip_while(|x| x.token_kind() == TokenKind::Whitespace),
+ )
+ .map(|x| x.to_owned())
+ .collect();
+
+ equal_token.update_trailing_trivia(FormatTriviaType::Replace(equal_token_trailing_trivia))
}
pub fn format_assignment<'ast>(
ctx: &mut Context,
assignment: &Assignment<'ast>,
+ shape: Shape,
) -> Assignment<'ast> {
// Calculate trivia - pick an arbitrary range within the whole assignment expression to see if
// indentation is required
// Leading trivia added to before the var_list, trailing trivia added to the end of the expr_list
let additional_indent_level =
ctx.get_range_indent_increase(token_range(assignment.equal_token().token()));
+ let shape = shape.with_additional_indent(additional_indent_level);
let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
let trailing_trivia = vec![create_newline_trivia(ctx)];
- let var_list = try_format_punctuated(ctx, assignment.variables(), format_var);
- // Don't need to worry about comments in expr_list, as it will automatically force multiline
- let mut expr_list = format_punctuated(ctx, assignment.expressions(), format_expression);
-
+ // Check if the assignment expressions contain comments. If they do, we bail out of determining any tactics
+ // and format multiline
+ let contains_comments = assignment.expressions().pairs().any(|pair| {
+ pair.punctuation()
+ .map_or(false, |x| trivia_util::token_contains_comments(x))
+ || trivia_util::expression_contains_inline_comments(pair.value())
+ });
+
+ // Firstly attempt to format the assignment onto a single line, using an infinite column width shape
+ let mut var_list = try_format_punctuated(
+ ctx,
+ assignment.variables(),
+ shape.with_infinite_width(),
+ format_var,
+ );
let mut equal_token = fmt_symbol!(ctx, assignment.equal_token(), " = ");
-
- // Create preliminary assignment
- let formatted_assignment = Assignment::new(var_list.to_owned(), expr_list.to_owned())
- .with_equal_token(equal_token.to_owned());
-
- // Test whether we need to hang the expression, using the updated assignment
- // We have to format normally before this, since we may be expanding the expression onto multiple lines
- // (e.g. if it was a table). We only want to use the first line to determine if we need to hang the expression
- let indent_spacing = ctx.indent_width_additional(additional_indent_level);
- let require_multiline_expression = indent_spacing
- + strip_assignment_trivia(&formatted_assignment)
- .to_string()
- .lines()
- .next()
- .expect("no lines")
- .len()
- > ctx.config().column_width
- || assignment.expressions().pairs().any(|pair| {
- pair.punctuation()
- .map_or(false, |punc| trivia_util::token_contains_comments(punc))
- || trivia_util::expression_contains_inline_comments(pair.value())
- });
-
- if require_multiline_expression {
- expr_list = hang_punctuated_list(ctx, assignment.expressions(), additional_indent_level);
-
- equal_token = check_long_expression(
- ctx,
- assignment.expressions(),
- equal_token,
- additional_indent_level,
- );
+ let mut expr_list = format_punctuated(
+ ctx,
+ assignment.expressions(),
+ shape.with_infinite_width(),
+ format_expression,
+ );
+
+ // Test the assignment to see if its over width
+ let singleline_shape = shape
+ + (strip_leading_trivia(&var_list).to_string().len()
+ + 3
+ + strip_trailing_trivia(&expr_list).to_string().len());
+ if contains_comments || singleline_shape.over_budget() {
+ // We won't attempt anything else with the var_list. Format it normally
+ var_list = try_format_punctuated(ctx, assignment.variables(), shape, format_var);
+ let shape = shape + (strip_leading_trivia(&var_list).to_string().len() + 3);
+ // The next tactic will be to see if we can hang the expression
+ // We can either hang the expression list, or hang at the equals token
+ if assignment
+ .expressions()
+ .iter()
+ .any(|x| trivia_util::can_hang_expression(x))
+ {
+ expr_list = hang_punctuated_list(
+ ctx,
+ assignment.expressions(),
+ shape,
+ additional_indent_level,
+ );
+ } else {
+ // The next tactic is to see whether there is more than one item in the punctuated list
+ // If there is, we should put it on multiple lines
+ if expr_list.len() > 1 {
+ // First try hanging at the equal token, using an infinite width, to see if its enough
+ let hanging_equal_token =
+ hang_equal_token(ctx, equal_token.to_owned(), additional_indent_level);
+ let hanging_shape = shape
+ .reset()
+ .with_additional_indent(Some(additional_indent_level.unwrap_or(0) + 1));
+ expr_list = format_punctuated(
+ ctx,
+ assignment.expressions(),
+ hanging_shape.with_infinite_width(),
+ format_expression,
+ );
+
+ if hanging_shape
+ .take_first_line(&strip_trivia(&expr_list))
+ .over_budget()
+ {
+ // Hang the expressions on multiple lines
+ expr_list = format_punctuated_multiline(
+ ctx,
+ assignment.expressions(),
+ shape,
+ format_expression,
+ Some(1),
+ );
+ } else {
+ equal_token = hanging_equal_token;
+ }
+ } else {
+ // Format the expressions normally. If still over budget, hang at the equals token
+ expr_list =
+ format_punctuated(ctx, assignment.expressions(), shape, format_expression);
+ let formatting_shape = shape.take_first_line(&strip_trailing_trivia(&expr_list));
+
+ if formatting_shape.over_budget() {
+ equal_token = hang_equal_token(ctx, equal_token, additional_indent_level);
+ // Add the expression list into the indent range, as it will be indented by one
+ let expr_range = assignment
+ .expressions()
+ .range()
+ .expect("no range for assignment punctuated list");
+ ctx.add_indent_range((expr_range.0.bytes(), expr_range.1.bytes()));
+ expr_list =
+ format_punctuated(ctx, assignment.expressions(), shape, format_expression);
+ }
+ }
+ }
}
- // Add any trailing trivia to the end of the expression list
+ // Add necessary trivia
+ let var_list = var_list.update_leading_trivia(FormatTriviaType::Append(leading_trivia));
let expr_list = expr_list.update_trailing_trivia(FormatTriviaType::Append(trailing_trivia));
- // Add on leading trivia
- let formatted_var_list =
- var_list.update_leading_trivia(FormatTriviaType::Append(leading_trivia));
-
- formatted_assignment
- .with_variables(formatted_var_list)
- .with_equal_token(equal_token)
- .with_expressions(expr_list)
+ Assignment::new(var_list, expr_list).with_equal_token(equal_token)
}
-pub fn format_local_assignment<'ast>(
+fn format_local_no_assignment<'ast>(
ctx: &mut Context,
assignment: &LocalAssignment<'ast>,
+ shape: Shape,
+ leading_trivia: Vec<Token<'ast>>,
+ trailing_trivia: Vec<Token<'ast>>,
) -> LocalAssignment<'ast> {
- // Calculate trivia - pick an arbitrary range within the whole local assignment expression to see if
- // indentation is required
- // Leading trivia added to before the local token, and trailing trivia added to the end of the expr_list, or name_list if no expr_list provided
- let additional_indent_level =
- ctx.get_range_indent_increase(token_range(assignment.local_token().token()));
- let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
- let trailing_trivia = vec![create_newline_trivia(ctx)];
-
let local_token = fmt_symbol!(ctx, assignment.local_token(), "local ")
.update_leading_trivia(FormatTriviaType::Append(leading_trivia));
-
- let mut name_list = try_format_punctuated(ctx, assignment.names(), format_token_reference_mut);
+ let shape = shape + 6; // 6 = "local "
+ let mut name_list =
+ try_format_punctuated(ctx, assignment.names(), shape, format_token_reference_mut);
#[cfg(feature = "luau")]
let mut type_specifiers: Vec<Option<TypeSpecifier<'ast>>> = assignment
diff --git a/src/formatters/assignment.rs b/src/formatters/assignment.rs
--- a/src/formatters/assignment.rs
+++ b/src/formatters/assignment.rs
@@ -211,81 +224,190 @@ pub fn format_local_assignment<'ast>(
})
.collect();
- if assignment.expressions().is_empty() {
- // See if the last variable assigned has a type specifier, and add a new line to that
- #[allow(unused_mut)]
- let mut new_line_added = false;
+ // See if the last variable assigned has a type specifier, and add a new line to that
+ #[allow(unused_mut)]
+ let mut new_line_added = false;
- #[cfg(feature = "luau")]
- if let Some(Some(specifier)) = type_specifiers.pop() {
- type_specifiers.push(Some(specifier.update_trailing_trivia(
- FormatTriviaType::Append(trailing_trivia.to_owned()),
- )));
- new_line_added = true;
- }
+ #[cfg(feature = "luau")]
+ if let Some(Some(specifier)) = type_specifiers.pop() {
+ type_specifiers.push(Some(specifier.update_trailing_trivia(
+ FormatTriviaType::Append(trailing_trivia.to_owned()),
+ )));
+ new_line_added = true;
+ }
- // Add any trailing trivia to the end of the expression list, if we haven't already added a newline
- if !new_line_added {
- name_list = name_list.update_trailing_trivia(FormatTriviaType::Append(trailing_trivia))
- }
+ // Add any trailing trivia to the end of the expression list, if we haven't already added a newline
+ if !new_line_added {
+ name_list = name_list.update_trailing_trivia(FormatTriviaType::Append(trailing_trivia))
+ }
- let local_assignment = LocalAssignment::new(name_list)
- .with_local_token(local_token)
- .with_equal_token(None)
- .with_expressions(Punctuated::new());
+ let local_assignment = LocalAssignment::new(name_list)
+ .with_local_token(local_token)
+ .with_equal_token(None)
+ .with_expressions(Punctuated::new());
- #[cfg(feature = "luau")]
- let local_assignment = local_assignment.with_type_specifiers(type_specifiers);
- local_assignment
+ #[cfg(feature = "luau")]
+ let local_assignment = local_assignment.with_type_specifiers(type_specifiers);
+ local_assignment
+}
+
+pub fn format_local_assignment<'ast>(
+ ctx: &mut Context,
+ assignment: &LocalAssignment<'ast>,
+ shape: Shape,
+) -> LocalAssignment<'ast> {
+ // Calculate trivia - pick an arbitrary range within the whole local assignment expression to see if
+ // indentation is required
+ // Leading trivia added to before the local token, and trailing trivia added to the end of the expr_list, or name_list if no expr_list provided
+ let additional_indent_level =
+ ctx.get_range_indent_increase(token_range(assignment.local_token().token()));
+ let shape = shape.with_additional_indent(additional_indent_level);
+ let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
+ let trailing_trivia = vec![create_newline_trivia(ctx)];
+
+ if assignment.expressions().is_empty() {
+ format_local_no_assignment(ctx, assignment, shape, leading_trivia, trailing_trivia)
} else {
+ // Check if the assignment expressions contain comments. If they do, we bail out of determining any tactics
+ // and format multiline
+ let contains_comments = assignment.expressions().pairs().any(|pair| {
+ pair.punctuation()
+ .map_or(false, |x| trivia_util::token_contains_comments(x))
+ || trivia_util::expression_contains_inline_comments(pair.value())
+ });
+
+ // Firstly attempt to format the assignment onto a single line, using an infinite column width shape
+ let local_token = fmt_symbol!(ctx, assignment.local_token(), "local ")
+ .update_leading_trivia(FormatTriviaType::Append(leading_trivia));
+
+ let mut name_list = try_format_punctuated(
+ ctx,
+ assignment.names(),
+ shape.with_infinite_width(),
+ format_token_reference_mut,
+ );
let mut equal_token = fmt_symbol!(ctx, assignment.equal_token().unwrap(), " = ");
- // Format the expression normally - if there are any comments, it will automatically force multiline
- let mut expr_list = format_punctuated(ctx, assignment.expressions(), format_expression);
- // Create our preliminary new assignment
- let local_assignment = LocalAssignment::new(name_list)
- .with_local_token(local_token)
- .with_equal_token(Some(equal_token.to_owned()))
- .with_expressions(expr_list.to_owned());
- #[cfg(feature = "luau")]
- let local_assignment = local_assignment.with_type_specifiers(type_specifiers);
+ let mut expr_list = format_punctuated(
+ ctx,
+ assignment.expressions(),
+ shape.with_infinite_width(),
+ format_expression,
+ );
- // Test whether we need to hang the expression, using the updated assignment
- // We have to format normally before this, since we may be expanding the expression onto multiple lines
- // (e.g. if it was a table). We only want to use the first line to determine if we need to hang the expression
- let indent_spacing = ctx.indent_width_additional(additional_indent_level);
- let require_multiline_expression = indent_spacing
- + strip_local_assignment_trivia(&local_assignment)
- .to_string()
- .lines()
- .next()
- .expect("no lines")
- .len()
- > ctx.config().column_width
- || assignment.expressions().pairs().any(|pair| {
- pair.punctuation()
- .map_or(false, |punc| trivia_util::token_contains_comments(punc))
- || trivia_util::expression_contains_inline_comments(pair.value())
+ #[cfg(feature = "luau")]
+ let type_specifiers: Vec<Option<TypeSpecifier<'ast>>> = assignment
+ .type_specifiers()
+ .map(|x| match x {
+ Some(type_specifier) => Some(format_type_specifier(ctx, type_specifier)),
+ None => None,
+ })
+ .collect();
+ let type_specifier_len;
+ #[cfg(feature = "luau")]
+ {
+ type_specifier_len = type_specifiers.iter().fold(0, |acc, x| {
+ acc + x.as_ref().map_or(0, |y| y.to_string().len())
});
+ }
+ #[cfg(not(feature = "luau"))]
+ {
+ type_specifier_len = 0;
+ }
- // Format the expression depending on whether we are multline or not
- if require_multiline_expression {
- expr_list =
- hang_punctuated_list(ctx, assignment.expressions(), additional_indent_level);
-
- equal_token = check_long_expression(
- ctx,
- assignment.expressions(),
- equal_token,
- additional_indent_level,
- );
+ // Test the assignment to see if its over width
+ let singleline_shape = shape
+ + (strip_leading_trivia(&name_list).to_string().len()
+ + 6 // 6 = "local "
+ + 3 // 3 = " = "
+ + type_specifier_len
+ + strip_trailing_trivia(&expr_list).to_string().len());
+
+ if contains_comments || singleline_shape.over_budget() {
+ // We won't attempt anything else with the name_list. Format it normally
+ name_list =
+ try_format_punctuated(ctx, assignment.names(), shape, format_token_reference_mut);
+ let shape = shape
+ + (strip_leading_trivia(&name_list).to_string().len() + 6 + 3 + type_specifier_len);
+ // The next tactic will be to see if we can hang the expression
+ // We can either hang the expression list, or hang at the equals token
+ if assignment
+ .expressions()
+ .iter()
+ .any(|x| trivia_util::can_hang_expression(x))
+ {
+ expr_list = hang_punctuated_list(
+ ctx,
+ assignment.expressions(),
+ shape,
+ additional_indent_level,
+ );
+ } else {
+ // The next tactic is to see whether there is more than one item in the punctuated list
+ // If there is, we should put it on multiple lines
+ if expr_list.len() > 1 {
+ // First try hanging at the equal token, using an infinite width, to see if its enough
+ let hanging_equal_token =
+ hang_equal_token(ctx, equal_token.to_owned(), additional_indent_level);
+ let hanging_shape = shape
+ .reset()
+ .with_additional_indent(Some(additional_indent_level.unwrap_or(0) + 1));
+ expr_list = format_punctuated(
+ ctx,
+ assignment.expressions(),
+ hanging_shape.with_infinite_width(),
+ format_expression,
+ );
+
+ if hanging_shape
+ .take_first_line(&strip_trivia(&expr_list))
+ .over_budget()
+ {
+ // Hang the expressions on multiple lines
+ expr_list = format_punctuated_multiline(
+ ctx,
+ assignment.expressions(),
+ shape,
+ format_expression,
+ Some(1),
+ );
+ } else {
+ equal_token = hanging_equal_token;
+ }
+ } else {
+ // Format the expressions normally. If still over budget, hang at the equals token
+ expr_list =
+ format_punctuated(ctx, assignment.expressions(), shape, format_expression);
+ let formatting_shape =
+ shape.take_first_line(&strip_trailing_trivia(&expr_list));
+
+ if formatting_shape.over_budget() {
+ equal_token = hang_equal_token(ctx, equal_token, additional_indent_level);
+ // Add the expression list into the indent range, as it will be indented by one
+ let expr_range = assignment
+ .expressions()
+ .range()
+ .expect("no range for assignment punctuated list");
+ ctx.add_indent_range((expr_range.0.bytes(), expr_range.1.bytes()));
+ expr_list = format_punctuated(
+ ctx,
+ assignment.expressions(),
+ shape,
+ format_expression,
+ );
+ }
+ }
+ }
}
- // Add any trailing trivia to the end of the expression list
+ // Add necessary trivia
let expr_list = expr_list.update_trailing_trivia(FormatTriviaType::Append(trailing_trivia));
- // Update our local assignment
- local_assignment
+ let local_assignment = LocalAssignment::new(name_list)
+ .with_local_token(local_token)
.with_equal_token(Some(equal_token))
- .with_expressions(expr_list)
+ .with_expressions(expr_list);
+ #[cfg(feature = "luau")]
+ let local_assignment = local_assignment.with_type_specifiers(type_specifiers);
+ local_assignment
}
}
diff --git a/src/formatters/block.rs b/src/formatters/block.rs
--- a/src/formatters/block.rs
+++ b/src/formatters/block.rs
@@ -3,7 +3,8 @@ use crate::{
context::{create_indent_trivia, create_newline_trivia, Context},
fmt_symbol,
formatters::{
- expression::{format_expression, hang_expression_no_trailing_newline},
+ assignment::hang_punctuated_list,
+ expression::format_expression,
general::{format_symbol, try_format_punctuated},
stmt::format_stmt,
trivia::{
diff --git a/src/formatters/block.rs b/src/formatters/block.rs
--- a/src/formatters/block.rs
+++ b/src/formatters/block.rs
@@ -12,12 +13,11 @@ use crate::{
trivia_util,
util::token_range,
},
+ shape::Shape,
};
use full_moon::ast::{
- punctuated::{Pair, Punctuated},
- Block, Expression, LastStmt, Prefix, Return, Stmt, Var,
+ punctuated::Punctuated, Block, Expression, LastStmt, Prefix, Return, Stmt, Var,
};
-use full_moon::node::Node;
use full_moon::tokenizer::TokenType;
use full_moon::tokenizer::{Token, TokenReference};
#[cfg(feature = "luau")]
diff --git a/src/formatters/block.rs b/src/formatters/block.rs
--- a/src/formatters/block.rs
+++ b/src/formatters/block.rs
@@ -31,9 +31,14 @@ macro_rules! update_first_token {
}};
}
-pub fn format_return<'ast>(ctx: &mut Context, return_node: &Return<'ast>) -> Return<'ast> {
+pub fn format_return<'ast>(
+ ctx: &mut Context,
+ return_node: &Return<'ast>,
+ shape: Shape,
+) -> Return<'ast> {
// Calculate trivia
let additional_indent_level = ctx.get_range_indent_increase(token_range(return_node.token()));
+ let shape = shape.with_additional_indent(additional_indent_level);
let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
let trailing_trivia = vec![create_newline_trivia(ctx)];
diff --git a/src/formatters/block.rs b/src/formatters/block.rs
--- a/src/formatters/block.rs
+++ b/src/formatters/block.rs
@@ -48,41 +53,18 @@ pub fn format_return<'ast>(ctx: &mut Context, return_node: &Return<'ast>) -> Ret
let token = fmt_symbol!(ctx, return_node.token(), "return ")
.update_leading_trivia(FormatTriviaType::Append(leading_trivia));
+ let shape = shape + (strip_trivia(return_node.token()).to_string().len() + 1); // 1 = " "
let mut formatted_returns =
- try_format_punctuated(ctx, return_node.returns(), format_expression);
+ try_format_punctuated(ctx, return_node.returns(), shape, format_expression);
// Determine if we need to hang the condition
- let first_line_str = strip_trivia(return_node.token()).to_string()
- + " "
- + &strip_trivia(&formatted_returns).to_string();
-
- let indent_spacing = ctx.indent_width_additional(additional_indent_level);
- let require_multiline_expression = (indent_spacing
- + first_line_str
- .trim()
- .lines()
- .next()
- .expect("no lines")
- .len())
- > ctx.config().column_width;
+ let require_multiline_expression = shape
+ .take_first_line(&strip_trivia(&formatted_returns))
+ .over_budget();
if require_multiline_expression {
- // Add the expression list into the indent range, as it will be indented by one
- let expr_range = return_node.returns().range().expect("no range for returns");
- ctx.add_indent_range((expr_range.0.bytes(), expr_range.1.bytes()));
-
- // Hang each expression
- let mut new_list = Punctuated::new();
- for pair in return_node.returns().pairs() {
- let expr = format_expression(ctx, pair.value());
- let value =
- hang_expression_no_trailing_newline(ctx, expr, additional_indent_level, None);
- new_list.push(Pair::new(
- value,
- pair.punctuation().map(|x| fmt_symbol!(ctx, x, ", ")),
- ));
- }
- formatted_returns = new_list
+ formatted_returns =
+ hang_punctuated_list(ctx, return_node.returns(), shape, additional_indent_level);
}
if let Some(pair) = formatted_returns.pop() {
diff --git a/src/formatters/block.rs b/src/formatters/block.rs
--- a/src/formatters/block.rs
+++ b/src/formatters/block.rs
@@ -97,7 +79,11 @@ pub fn format_return<'ast>(ctx: &mut Context, return_node: &Return<'ast>) -> Ret
}
}
-pub fn format_last_stmt<'ast>(ctx: &mut Context, last_stmt: &LastStmt<'ast>) -> LastStmt<'ast> {
+pub fn format_last_stmt<'ast>(
+ ctx: &mut Context,
+ last_stmt: &LastStmt<'ast>,
+ shape: Shape,
+) -> LastStmt<'ast> {
check_should_format!(ctx, last_stmt);
match last_stmt {
diff --git a/src/formatters/block.rs b/src/formatters/block.rs
--- a/src/formatters/block.rs
+++ b/src/formatters/block.rs
@@ -109,7 +95,7 @@ pub fn format_last_stmt<'ast>(ctx: &mut Context, last_stmt: &LastStmt<'ast>) ->
FormatTriviaType::Append(vec![create_newline_trivia(ctx)]),
)),
- LastStmt::Return(return_node) => LastStmt::Return(format_return(ctx, return_node)),
+ LastStmt::Return(return_node) => LastStmt::Return(format_return(ctx, return_node, shape)),
#[cfg(feature = "luau")]
LastStmt::Continue(token) => LastStmt::Continue(
format_symbol(
diff --git a/src/formatters/block.rs b/src/formatters/block.rs
--- a/src/formatters/block.rs
+++ b/src/formatters/block.rs
@@ -328,7 +314,8 @@ pub fn format_block<'ast>(ctx: &mut Context, block: Block<'ast>) -> Block<'ast>
let mut found_first_stmt = false;
let mut stmt_iterator = block.stmts_with_semicolon().peekable();
while let Some((stmt, semi)) = stmt_iterator.next() {
- let mut stmt = format_stmt(ctx, stmt);
+ let shape = Shape::from_context(ctx);
+ let mut stmt = format_stmt(ctx, stmt, shape);
// If this is the first stmt, then remove any leading newlines
if !found_first_stmt {
diff --git a/src/formatters/block.rs b/src/formatters/block.rs
--- a/src/formatters/block.rs
+++ b/src/formatters/block.rs
@@ -400,7 +387,8 @@ pub fn format_block<'ast>(ctx: &mut Context, block: Block<'ast>) -> Block<'ast>
let formatted_last_stmt = match block.last_stmt_with_semicolon() {
Some((last_stmt, semi)) => {
- let mut last_stmt = format_last_stmt(ctx, last_stmt);
+ let shape = Shape::from_context(ctx);
+ let mut last_stmt = format_last_stmt(ctx, last_stmt, shape);
// If this is the first stmt, then remove any leading newlines
if !found_first_stmt && ctx.should_format_node(&last_stmt) {
last_stmt = last_stmt_remove_leading_newlines(last_stmt);
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -13,9 +13,13 @@ use crate::{
functions::{format_anonymous_function, format_call, format_function_call},
general::{format_contained_span, format_token_reference},
table::format_table_constructor,
- trivia::{FormatTriviaType, UpdateLeadingTrivia, UpdateTrailingTrivia, UpdateTrivia},
+ trivia::{
+ strip_leading_trivia, strip_trivia, FormatTriviaType, UpdateLeadingTrivia,
+ UpdateTrailingTrivia, UpdateTrivia,
+ },
trivia_util,
},
+ shape::Shape,
};
#[macro_export]
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -92,8 +96,9 @@ fn check_excess_parentheses(internal_expression: &Expression) -> bool {
pub fn format_expression<'ast>(
ctx: &mut Context,
expression: &Expression<'ast>,
+ shape: Shape,
) -> Expression<'ast> {
- format_expression_internal(ctx, expression, ExpressionContext::Standard)
+ format_expression_internal(ctx, expression, ExpressionContext::Standard, shape)
}
/// Internal expression formatter, with access to expression context
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -101,6 +106,7 @@ fn format_expression_internal<'ast>(
ctx: &mut Context,
expression: &Expression<'ast>,
context: ExpressionContext,
+ shape: Shape,
) -> Expression<'ast> {
match expression {
Expression::Value {
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -108,7 +114,7 @@ fn format_expression_internal<'ast>(
#[cfg(feature = "luau")]
type_assertion,
} => Expression::Value {
- value: Box::new(format_value(ctx, value)),
+ value: Box::new(format_value(ctx, value, shape)),
#[cfg(feature = "luau")]
type_assertion: match type_assertion {
Some(assertion) => Some(format_type_assertion(ctx, assertion)),
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -125,36 +131,45 @@ fn format_expression_internal<'ast>(
// If the context is for a prefix, we should always keep the parentheses, as they are always required
if use_internal_expression && !matches!(context, ExpressionContext::Prefix) {
- format_expression(ctx, expression)
+ format_expression(ctx, expression, shape)
} else {
Expression::Parentheses {
contained: format_contained_span(ctx, &contained),
- expression: Box::new(format_expression(ctx, expression)),
+ expression: Box::new(format_expression(ctx, expression, shape + 1)), // 1 = opening parentheses
}
}
}
- Expression::UnaryOperator { unop, expression } => Expression::UnaryOperator {
- unop: format_unop(ctx, unop),
- expression: Box::new(format_expression(ctx, expression)),
- },
- Expression::BinaryOperator { lhs, binop, rhs } => Expression::BinaryOperator {
- lhs: Box::new(format_expression(ctx, lhs)),
- binop: format_binop(ctx, binop),
- rhs: Box::new(format_expression(ctx, rhs)),
- },
+ Expression::UnaryOperator { unop, expression } => {
+ let unop = format_unop(ctx, unop);
+ let shape = shape + strip_leading_trivia(&unop).to_string().len();
+ Expression::UnaryOperator {
+ unop,
+ expression: Box::new(format_expression(ctx, expression, shape)),
+ }
+ }
+ Expression::BinaryOperator { lhs, binop, rhs } => {
+ let lhs = format_expression(ctx, lhs, shape);
+ let binop = format_binop(ctx, binop);
+ let shape = shape.take_last_line(&lhs) + binop.to_string().len();
+ Expression::BinaryOperator {
+ lhs: Box::new(lhs),
+ binop,
+ rhs: Box::new(format_expression(ctx, rhs, shape)),
+ }
+ }
other => panic!("unknown node {:?}", other),
}
}
/// Formats an Index Node
-pub fn format_index<'ast>(ctx: &mut Context, index: &Index<'ast>) -> Index<'ast> {
+pub fn format_index<'ast>(ctx: &mut Context, index: &Index<'ast>, shape: Shape) -> Index<'ast> {
match index {
Index::Brackets {
brackets,
expression,
} => Index::Brackets {
brackets: format_contained_span(ctx, &brackets),
- expression: format_expression(ctx, expression),
+ expression: format_expression(ctx, expression, shape + 1), // 1 = opening bracket
},
Index::Dot { dot, name } => Index::Dot {
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -166,12 +181,13 @@ pub fn format_index<'ast>(ctx: &mut Context, index: &Index<'ast>) -> Index<'ast>
}
/// Formats a Prefix Node
-pub fn format_prefix<'ast>(ctx: &mut Context, prefix: &Prefix<'ast>) -> Prefix<'ast> {
+pub fn format_prefix<'ast>(ctx: &mut Context, prefix: &Prefix<'ast>, shape: Shape) -> Prefix<'ast> {
match prefix {
Prefix::Expression(expression) => Prefix::Expression(format_expression_internal(
ctx,
expression,
ExpressionContext::Prefix,
+ shape,
)),
Prefix::Name(token_reference) => Prefix::Name(format_token_reference(ctx, token_reference)),
other => panic!("unknown node {:?}", other),
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -179,28 +195,28 @@ pub fn format_prefix<'ast>(ctx: &mut Context, prefix: &Prefix<'ast>) -> Prefix<'
}
/// Formats a Suffix Node
-pub fn format_suffix<'ast>(ctx: &mut Context, suffix: &Suffix<'ast>) -> Suffix<'ast> {
+pub fn format_suffix<'ast>(ctx: &mut Context, suffix: &Suffix<'ast>, shape: Shape) -> Suffix<'ast> {
match suffix {
- Suffix::Call(call) => Suffix::Call(format_call(ctx, call)),
- Suffix::Index(index) => Suffix::Index(format_index(ctx, index)),
+ Suffix::Call(call) => Suffix::Call(format_call(ctx, call, shape)),
+ Suffix::Index(index) => Suffix::Index(format_index(ctx, index, shape)),
other => panic!("unknown node {:?}", other),
}
}
/// Formats a Value Node
-pub fn format_value<'ast>(ctx: &mut Context, value: &Value<'ast>) -> Value<'ast> {
+pub fn format_value<'ast>(ctx: &mut Context, value: &Value<'ast>, shape: Shape) -> Value<'ast> {
match value {
Value::Function((token_reference, function_body)) => Value::Function(
format_anonymous_function(ctx, token_reference, function_body),
),
Value::FunctionCall(function_call) => {
- Value::FunctionCall(format_function_call(ctx, function_call))
+ Value::FunctionCall(format_function_call(ctx, function_call, shape))
}
Value::Number(token_reference) => {
Value::Number(format_token_reference(ctx, token_reference))
}
Value::ParenthesesExpression(expression) => {
- Value::ParenthesesExpression(format_expression(ctx, expression))
+ Value::ParenthesesExpression(format_expression(ctx, expression, shape))
}
Value::String(token_reference) => {
Value::String(format_token_reference(ctx, token_reference))
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -209,19 +225,19 @@ pub fn format_value<'ast>(ctx: &mut Context, value: &Value<'ast>) -> Value<'ast>
Value::Symbol(format_token_reference(ctx, token_reference))
}
Value::TableConstructor(table_constructor) => {
- Value::TableConstructor(format_table_constructor(ctx, table_constructor))
+ Value::TableConstructor(format_table_constructor(ctx, table_constructor, shape))
}
- Value::Var(var) => Value::Var(format_var(ctx, var)),
+ Value::Var(var) => Value::Var(format_var(ctx, var, shape)),
other => panic!("unknown node {:?}", other),
}
}
/// Formats a Var Node
-pub fn format_var<'ast>(ctx: &mut Context, var: &Var<'ast>) -> Var<'ast> {
+pub fn format_var<'ast>(ctx: &mut Context, var: &Var<'ast>, shape: Shape) -> Var<'ast> {
match var {
Var::Name(token_reference) => Var::Name(format_token_reference(ctx, token_reference)),
Var::Expression(var_expression) => {
- Var::Expression(format_var_expression(ctx, var_expression))
+ Var::Expression(format_var_expression(ctx, var_expression, shape))
}
other => panic!("unknown node {:?}", other),
}
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -230,11 +246,18 @@ pub fn format_var<'ast>(ctx: &mut Context, var: &Var<'ast>) -> Var<'ast> {
pub fn format_var_expression<'ast>(
ctx: &mut Context,
var_expression: &VarExpression<'ast>,
+ shape: Shape,
) -> VarExpression<'ast> {
- let formatted_prefix = format_prefix(ctx, var_expression.prefix());
+ let formatted_prefix = format_prefix(ctx, var_expression.prefix(), shape);
+ let mut shape = shape + strip_leading_trivia(&formatted_prefix).to_string().len();
+
let formatted_suffixes = var_expression
.suffixes()
- .map(|x| format_suffix(ctx, x))
+ .map(|x| {
+ let suffix = format_suffix(ctx, x, shape);
+ shape = shape + suffix.to_string().len();
+ suffix
+ })
.collect();
VarExpression::new(formatted_prefix).with_suffixes(formatted_suffixes)
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -303,9 +326,10 @@ fn binop_expression_length<'ast>(expression: &Expression<'ast>, top_binop: &BinO
}
fn hang_binop_expression<'ast>(
- ctx: &Context,
+ ctx: &mut Context,
expression: Expression<'ast>,
top_binop: BinOp<'ast>,
+ shape: Shape,
indent_level: usize,
) -> Expression<'ast> {
let full_expression = expression.to_owned();
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -330,28 +354,34 @@ fn hang_binop_expression<'ast>(
lhs.to_owned()
};
- let over_column_width = ctx.indent_width()
- + binop_expression_length(&full_expression, &binop)
- > ctx.config().column_width;
+ let over_column_width = shape
+ .add_width(binop_expression_length(&full_expression, &binop))
+ .over_budget();
+ let binop = format_binop(ctx, &binop);
let (binop, updated_side) = if same_op_level || over_column_width {
+ let shape = Shape::with_indent_level(ctx, indent_level)
+ + strip_trivia(&binop).to_string().len()
+ + 1;
+
let op = hang_binop(ctx, binop.to_owned(), indent_level);
let side = hang_binop_expression(
ctx,
*side_to_use,
if same_op_level { top_binop } else { binop },
+ shape,
indent_level,
);
(op, side)
} else {
- (binop, *side_to_use)
+ (binop, format_expression(ctx, &*side_to_use, shape))
};
if is_right_associative {
Expression::BinaryOperator {
- lhs,
+ lhs: Box::new(format_expression(ctx, &*lhs, shape)),
binop,
rhs: Box::new(updated_side),
}
diff --git a/src/formatters/expression.rs b/src/formatters/expression.rs
--- a/src/formatters/expression.rs
+++ b/src/formatters/expression.rs
@@ -359,124 +389,148 @@ fn hang_binop_expression<'ast>(
Expression::BinaryOperator {
lhs: Box::new(updated_side),
binop,
- rhs,
+ rhs: Box::new(format_expression(ctx, &*rhs, shape)),
}
}
}
// Base case: no more binary operators - just return to normal splitting
- _ => expression_split_binop(ctx, expression, indent_level),
+ _ => format_hanging_expression_(ctx, &expression, shape, indent_level),
}
}
-fn expression_split_binop<'ast>(
- ctx: &Context,
- expression: Expression<'ast>,
- indent_increase: usize,
+/// Internal expression formatter, where the binop is also hung
+fn format_hanging_expression_<'ast>(
+ ctx: &mut Context,
+ expression: &Expression<'ast>,
+ shape: Shape,
+ indent_level: usize,
) -> Expression<'ast> {
match expression {
+ Expression::Value {
+ value,
+ #[cfg(feature = "luau")]
+ type_assertion,
+ } => {
+ let value = Box::new(match &**value {
+ Value::ParenthesesExpression(expression) => Value::ParenthesesExpression(
+ format_hanging_expression_(ctx, expression, shape, indent_level),
+ ),
+ _ => format_value(ctx, value, shape),
+ });
+ Expression::Value {
+ value,
+ #[cfg(feature = "luau")]
+ type_assertion: match type_assertion {
+ Some(assertion) => Some(format_type_assertion(ctx, assertion)),
+ None => None,
+ },
+ }
+ }
Expression::Parentheses {
contained,
expression,
} => {
- // Examine the expression itself to see if needs to be split onto multiple lines
- let expression_str = expression.to_string();
- if expression_str.len()
- + 2 // Account for the two parentheses
- + ctx.indent_width() // Account for the current indent level
- + (indent_increase * ctx.config().indent_width) // Account for any further indent increase
- < ctx.config().column_width
- {
- // The expression inside the parentheses is small, we do not need to break it down further
- return Expression::Parentheses {
+ // Examine whether the internal expression requires parentheses
+ // If not, just format and return the internal expression. Otherwise, format the parentheses
+ let use_internal_expression = check_excess_parentheses(expression);
+
+ // If the context is for a prefix, we should always keep the parentheses, as they are always required
+ if use_internal_expression {
+ format_hanging_expression_(ctx, expression, shape, indent_level)
+ } else {
+ let contained = format_contained_span(ctx, &contained);
+ let expression = format_expression(ctx, expression, shape + 1); // 1 = opening parentheses
+
+ // Examine the expression itself to see if needs to be split onto multiple lines
+ let expression_str = expression.to_string();
+ if !shape.add_width(2 + expression_str.len()).over_budget() {
+ // The expression inside the parentheses is small, we do not need to break it down further
+ return Expression::Parentheses {
+ contained,
+ expression: Box::new(expression),
+ };
+ }
+
+ // Modify the parentheses to hang the expression
+ let (start_token, end_token) = contained.tokens();
+ // Create a newline after the start brace and before the end brace
+ // Also, indent enough for the first expression in the start brace
+ let contained = ContainedSpan::new(
+ start_token.update_trailing_trivia(FormatTriviaType::Append(vec![
+ create_newline_trivia(ctx),
+ create_plain_indent_trivia(ctx, indent_level + 1),
+ ])),
+ end_token.update_leading_trivia(FormatTriviaType::Append(vec![
+ create_newline_trivia(ctx),
+ create_plain_indent_trivia(ctx, indent_level),
+ ])),
+ );
+
+ Expression::Parentheses {
contained,
- expression,
- };
+ expression: Box::new(format_hanging_expression_(
+ ctx,
+ &expression,
+ Shape::with_indent_level(ctx, indent_level + 1),
+ indent_level + 1, // Apply indent increase
+ )),
+ }
}
-
- // Modify the parentheses to hang the expression
- let (start_token, end_token) = contained.tokens();
- // Create a newline after the start brace and before the end brace
- // Also, indent enough for the first expression in the start brace
- let contained = ContainedSpan::new(
- start_token.update_trailing_trivia(FormatTriviaType::Append(vec![
- create_newline_trivia(ctx),
- create_plain_indent_trivia(ctx, indent_increase + 1),
- ])),
- end_token.update_leading_trivia(FormatTriviaType::Append(vec![
- create_newline_trivia(ctx),
- create_plain_indent_trivia(ctx, indent_increase),
- ])),
- );
-
- Expression::Parentheses {
- contained,
- expression: Box::new(expression_split_binop(
- ctx,
- *expression,
- indent_increase + 1, // Apply indent increase
- )),
+ }
+ Expression::UnaryOperator { unop, expression } => {
+ let unop = format_unop(ctx, unop);
+ let shape = shape + strip_leading_trivia(&unop).to_string().len();
+ let expression = format_expression(ctx, expression, shape);
+ let expression = format_hanging_expression_(ctx, &expression, shape, indent_level);
+
+ Expression::UnaryOperator {
+ unop,
+ expression: Box::new(expression),
}
}
- Expression::UnaryOperator { unop, expression } => Expression::UnaryOperator {
- unop,
- expression: Box::new(expression_split_binop(ctx, *expression, indent_increase)),
- },
Expression::BinaryOperator { lhs, binop, rhs } => {
- let lhs = Box::new(hang_binop_expression(
- ctx,
- *lhs,
- binop.to_owned(),
- indent_increase,
- ));
- let rhs = Box::new(hang_binop_expression(
- ctx,
- *rhs,
- binop.to_owned(),
- indent_increase,
- ));
- let binop = hang_binop(ctx, binop, indent_increase);
-
- Expression::BinaryOperator { lhs, binop, rhs }
+ // Don't format the lhs and rhs here, because it will be handled later when hang_binop_expression calls back for a Value
+ let lhs =
+ hang_binop_expression(ctx, *lhs.to_owned(), binop.to_owned(), shape, indent_level);
+ let binop = format_binop(ctx, binop);
+ let shape = Shape::with_indent_level(ctx, indent_level)
+ + strip_trivia(&binop).to_string().len()
+ + 1;
+
+ let binop = hang_binop(ctx, binop, indent_level);
+ let rhs =
+ hang_binop_expression(ctx, *rhs.to_owned(), binop.to_owned(), shape, indent_level);
+
+ Expression::BinaryOperator {
+ lhs: Box::new(lhs),
+ binop,
+ rhs: Box::new(rhs),
+ }
}
-
- Expression::Value {
- value,
- #[cfg(feature = "luau")]
- type_assertion,
- } => Expression::Value {
- value: match *value {
- Value::ParenthesesExpression(expression) => Box::new(Value::ParenthesesExpression(
- expression_split_binop(ctx, expression, indent_increase),
- )),
- _ => value,
- },
- #[cfg(feature = "luau")]
- type_assertion,
- },
-
- // Can't hang anything else, so just return the original expression
- _ => expression,
+ other => panic!("unknown node {:?}", other),
}
}
-pub fn hang_expression_no_trailing_newline<'ast>(
- ctx: &Context,
- expression: Expression<'ast>,
+pub fn hang_expression<'ast>(
+ ctx: &mut Context,
+ expression: &Expression<'ast>,
+ shape: Shape,
additional_indent_level: Option<usize>,
hang_level: Option<usize>,
) -> Expression<'ast> {
let additional_indent_level = additional_indent_level.unwrap_or(0) + hang_level.unwrap_or(0);
let hang_level = ctx.indent_level() + additional_indent_level;
- expression_split_binop(ctx, expression, hang_level)
+ format_hanging_expression_(ctx, expression, shape, hang_level)
}
-pub fn hang_expression<'ast>(
- ctx: &Context,
- expression: Expression<'ast>,
+pub fn hang_expression_trailing_newline<'ast>(
+ ctx: &mut Context,
+ expression: &Expression<'ast>,
+ shape: Shape,
additional_indent_level: Option<usize>,
hang_level: Option<usize>,
) -> Expression<'ast> {
- hang_expression_no_trailing_newline(ctx, expression, additional_indent_level, hang_level)
+ hang_expression(ctx, expression, shape, additional_indent_level, hang_level)
.update_trailing_trivia(FormatTriviaType::Append(vec![create_newline_trivia(ctx)]))
}
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -14,19 +14,19 @@ use crate::{
context::{create_indent_trivia, create_newline_trivia, Context},
fmt_symbol,
formatters::{
- expression::{
- format_expression, format_prefix, format_suffix, hang_expression_no_trailing_newline,
- },
+ expression::{format_expression, format_prefix, format_suffix, hang_expression},
general::{
format_contained_span, format_end_token, format_punctuated, format_symbol,
format_token_reference, EndTokenType,
},
trivia::{
- strip_trivia, FormatTriviaType, UpdateLeadingTrivia, UpdateTrailingTrivia, UpdateTrivia,
+ strip_leading_trivia, strip_trivia, FormatTriviaType, UpdateLeadingTrivia,
+ UpdateTrailingTrivia, UpdateTrivia,
},
trivia_util,
util::{expression_range, token_range},
},
+ shape::Shape,
};
/// Formats an Anonymous Function
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -40,7 +40,8 @@ pub fn format_anonymous_function<'ast>(
let additional_indent_level = ctx.get_range_indent_increase(function_token_range);
let function_token = fmt_symbol!(ctx, function_token, "function");
- let mut function_body = format_function_body(ctx, function_body, false);
+ let mut function_body =
+ format_function_body(ctx, function_body, false, Shape::from_context(ctx)); // TODO: shape
// Need to insert any additional trivia, as it isn't being inserted elsewhere
#[cfg(feature = "luau")]
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -89,12 +90,14 @@ pub fn format_anonymous_function<'ast>(
}
/// Formats a Call node
-pub fn format_call<'ast>(ctx: &mut Context, call: &Call<'ast>) -> Call<'ast> {
+pub fn format_call<'ast>(ctx: &mut Context, call: &Call<'ast>, shape: Shape) -> Call<'ast> {
match call {
Call::AnonymousCall(function_args) => {
- Call::AnonymousCall(format_function_args(ctx, function_args))
+ Call::AnonymousCall(format_function_args(ctx, function_args, shape))
+ }
+ Call::MethodCall(method_call) => {
+ Call::MethodCall(format_method_call(ctx, method_call, shape))
}
- Call::MethodCall(method_call) => Call::MethodCall(format_method_call(ctx, method_call)),
other => panic!("unknown node {:?}", other),
}
}
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -103,6 +106,7 @@ pub fn format_call<'ast>(ctx: &mut Context, call: &Call<'ast>) -> Call<'ast> {
pub fn format_function_args<'ast>(
ctx: &mut Context,
function_args: &FunctionArgs<'ast>,
+ shape: Shape,
) -> FunctionArgs<'ast> {
match function_args {
FunctionArgs::Parentheses {
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -115,14 +119,15 @@ pub fn format_function_args<'ast>(
Token::end_position(&start_parens).bytes(),
Token::start_position(&end_parens).bytes(),
);
- let current_indent_width = ctx
- .indent_width_additional(ctx.get_range_indent_increase(token_range(start_parens)));
// Format all the arguments, so that we can prepare them and check to see whether they need expanding
// We will ignore punctuation for now
let mut first_iter_formatted_arguments = Vec::new();
+ let mut first_iter_shape = shape;
for argument in arguments.iter() {
- first_iter_formatted_arguments.push(format_expression(ctx, argument))
+ let argument = format_expression(ctx, argument, first_iter_shape);
+ first_iter_shape = shape.take_last_line(&argument);
+ first_iter_formatted_arguments.push(argument);
}
// Apply some heuristics to determine whether we should expand the function call
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -168,6 +173,7 @@ pub fn format_function_args<'ast>(
};
let mut is_multiline = force_mutliline;
+ let mut singleline_shape = shape + 1; // 1 = opening parentheses
if !force_mutliline {
// If we only have one argument then we will not make it multi line (expanding it would have little value)
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -187,9 +193,6 @@ pub fn format_function_args<'ast>(
// call(foo, { ... }) or call(foo, { ... }, foo) can stay on one line, provided the
// single line arguments dont surpass the column width setting
- // TODO: We need to add more to this - there may be quite a lot before this function call
- let mut width_passed = current_indent_width;
-
// Use state values to determine the type of arguments we have seen so far
let mut seen_multiline_arg = false; // Whether we have seen a multiline table/function already
let mut seen_other_arg_after_multiline = false; // Whether we have seen a non multiline table/function after a multiline one. In this case, we should expand
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -209,8 +212,16 @@ pub fn format_function_args<'ast>(
seen_multiline_arg = true;
- // Reset the width count back
- width_passed = current_indent_width;
+ // First check the top line of the anonymous function (i.e. the function token and any parameters)
+ // If this is over budget, then we should expand
+ singleline_shape = singleline_shape.take_first_line(value);
+ if singleline_shape.over_budget() {
+ is_multiline = true;
+ break;
+ }
+
+ // Reset the shape onto a new line // 3 = "end" for the function line
+ singleline_shape = singleline_shape.reset() + 3;
}
Value::TableConstructor(table) => {
// Check to see whether it has been expanded
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -228,13 +239,16 @@ pub fn format_function_args<'ast>(
}
seen_multiline_arg = true;
- // Reset the width count back
- width_passed = current_indent_width;
+
+ // Reset the shape onto a new line
+ singleline_shape = singleline_shape.reset() + 1;
+ // 1 = "}"
} else {
// We have a collapsed table constructor - add the width, and if it fails,
// we need to expand
- width_passed += argument.to_string().len();
- if width_passed > ctx.config().column_width - 20 {
+ singleline_shape =
+ singleline_shape + argument.to_string().len();
+ if singleline_shape.over_budget() {
is_multiline = true;
break;
}
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -246,8 +260,9 @@ pub fn format_function_args<'ast>(
if seen_multiline_arg {
seen_other_arg_after_multiline = true;
}
- width_passed += argument.to_string().len();
- if width_passed > ctx.config().column_width - 20 {
+ singleline_shape =
+ singleline_shape + argument.to_string().len();
+ if singleline_shape.over_budget() {
// We have passed 80 characters without a table or anonymous function
// There is nothing else stopping us from expanding - so we will
is_multiline = true;
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -265,8 +280,8 @@ pub fn format_function_args<'ast>(
seen_other_arg_after_multiline = true;
}
- width_passed += argument.to_string().len();
- if width_passed > ctx.config().column_width - 20 {
+ singleline_shape = singleline_shape + argument.to_string().len();
+ if singleline_shape.over_budget() {
// We have passed 80 characters without a table or anonymous function
// There is nothing else stopping us from expanding - so we will
is_multiline = true;
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -276,7 +291,7 @@ pub fn format_function_args<'ast>(
}
// Add width which would be taken up by comment and space
- width_passed += 2;
+ singleline_shape = singleline_shape + 2;
}
}
}
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -313,41 +328,29 @@ pub fn format_function_args<'ast>(
);
let mut formatted_arguments = Punctuated::new();
- // Iterate through the original formatted_arguments, so we can see how the formatted version would look like
- let mut formatted_versions = first_iter_formatted_arguments.iter();
-
ctx.add_indent_range(function_call_range);
for argument in arguments.pairs() {
- // See what the formatted version of the argument would look like
- let formatted_version = formatted_versions
- .next()
- .expect("less arguments than expected");
-
let argument_range = expression_range(argument.value());
let additional_indent_level = ctx.get_range_indent_increase(argument_range);
+ let shape = shape
+ .reset()
+ .with_additional_indent(additional_indent_level); // Argument is on a new line, so reset the shape
+
+ let mut formatted_argument = format_expression(ctx, argument.value(), shape);
- let indent_spacing = ctx.indent_width_additional(additional_indent_level);
let require_multiline_expression =
trivia_util::can_hang_expression(argument.value())
- && indent_spacing
- + formatted_version
- .to_string()
- .lines()
- .next()
- .expect("no lines")
- .len()
- > ctx.config().column_width;
-
- // Unfortunately, we need to format again, taking into account in indent increase
- // TODO: Can we fix this? We don't want to have to format twice
- let mut formatted_argument = format_expression(ctx, argument.value());
+ && shape
+ .take_first_line(&strip_trivia(&formatted_argument))
+ .over_budget();
// Hang the expression if necessary
if require_multiline_expression {
- formatted_argument = hang_expression_no_trailing_newline(
+ formatted_argument = hang_expression(
ctx,
- formatted_argument,
+ argument.value(),
+ shape,
additional_indent_level,
None,
);
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -387,7 +390,7 @@ pub fn format_function_args<'ast>(
// multiline function args
let parentheses = format_contained_span(ctx, &parentheses);
- let arguments = format_punctuated(ctx, arguments, format_expression);
+ let arguments = format_punctuated(ctx, arguments, shape + 1, format_expression); // 1 = opening parentheses
FunctionArgs::Parentheses {
parentheses,
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -405,6 +408,7 @@ pub fn format_function_args<'ast>(
#[cfg(feature = "luau")]
type_assertion: None,
},
+ shape + 1, // 1 = opening parentheses
);
// Remove any trailing comments from the expression, and move them into a buffer
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -435,6 +439,7 @@ pub fn format_function_args<'ast>(
#[cfg(feature = "luau")]
type_assertion: None,
},
+ shape + 1, // 1 = opening parentheses
);
// Remove any trailing comments from the expression, and move them into a buffer
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -464,6 +469,7 @@ pub fn format_function_body<'ast>(
ctx: &mut Context,
function_body: &FunctionBody<'ast>,
add_trivia: bool,
+ shape: Shape,
) -> FunctionBody<'ast> {
// Calculate trivia
let additional_indent_level =
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -494,36 +500,35 @@ pub fn format_function_body<'ast>(
contains_comments || type_specifier_comments
});
- contains_comments
- || {
- // Check the length of the parameters. We need to format them first onto a single line to check if required
- let types_length: usize;
- #[cfg(feature = "luau")]
- {
- types_length = function_body
- .type_specifiers()
- .chain(std::iter::once(function_body.return_type())) // Include optional return type
- .map(|x| {
- x.map_or(0, |specifier| {
- format_type_specifier(ctx, specifier).to_string().len()
- })
+ contains_comments || {
+ // Check the length of the parameters. We need to format them first onto a single line to check if required
+ let types_length: usize;
+ #[cfg(feature = "luau")]
+ {
+ types_length = function_body
+ .type_specifiers()
+ .chain(std::iter::once(function_body.return_type())) // Include optional return type
+ .map(|x| {
+ x.map_or(0, |specifier| {
+ format_type_specifier(ctx, specifier).to_string().len()
})
- .sum::<usize>()
- }
- #[cfg(not(feature = "luau"))]
- {
- types_length = 0
- }
+ })
+ .sum::<usize>()
+ }
+ #[cfg(not(feature = "luau"))]
+ {
+ types_length = 0
+ }
- let line_length = format_singleline_parameters(ctx, function_body)
+ let line_length = format_singleline_parameters(ctx, function_body)
.to_string()
.len()
+ 2 // Account for the parentheses around the parameters
- + types_length // Account for type specifiers and return type
- + ctx.indent_width_additional(ctx.get_range_indent_increase(token_range(function_body.parameters_parentheses().tokens().0)));
+ + types_length; // Account for type specifiers and return type
- line_length > ctx.config().column_width
- }
+ let singleline_shape = shape + line_length;
+ singleline_shape.over_budget()
+ }
};
let (formatted_parameters, mut parameters_parentheses) = match multiline_params {
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -628,8 +633,9 @@ pub fn format_function_body<'ast>(
pub fn format_function_call<'ast>(
ctx: &mut Context,
function_call: &FunctionCall<'ast>,
+ shape: Shape,
) -> FunctionCall<'ast> {
- let formatted_prefix = format_prefix(ctx, function_call.prefix());
+ let formatted_prefix = format_prefix(ctx, function_call.prefix(), shape);
let num_suffixes = function_call.suffixes().count();
let should_hang = {
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -646,18 +652,14 @@ pub fn format_function_call<'ast>(
// Create a temporary formatted version of suffixes to use for this check
let formatted_suffixes = function_call
.suffixes()
- .map(|x| format_suffix(ctx, x))
+ .map(|x| format_suffix(ctx, x, shape)) // TODO: is this the right shape to use?
.collect();
let preliminary_function_call =
FunctionCall::new(formatted_prefix.to_owned()).with_suffixes(formatted_suffixes);
- let outcome = if strip_trivia(&preliminary_function_call)
- .to_string()
- .lines()
- .next()
- .expect("no lines")
- .len()
- > ctx.config().column_width
+ let outcome = if shape
+ .take_first_line(&strip_trivia(&preliminary_function_call))
+ .over_budget()
{
true
} else {
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -685,6 +687,7 @@ pub fn format_function_call<'ast>(
}
};
+ let mut shape = shape + strip_leading_trivia(&formatted_prefix).to_string().len(); // TODO: can the prefix be multiline?
let mut formatted_suffixes = Vec::with_capacity(num_suffixes);
for suffix in function_call.suffixes() {
// Calculate the range before formatting, otherwise it will reset to (0,0)
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -701,8 +704,14 @@ pub fn format_function_call<'ast>(
} else {
None
};
+ shape = shape.with_additional_indent(indent_level);
+
+ if indent_level.is_some() {
+ // The suffix will be added onto a new line
+ shape = shape.reset();
+ }
- let mut suffix = format_suffix(ctx, suffix);
+ let mut suffix = format_suffix(ctx, suffix, shape);
if indent_level.is_some() {
suffix = suffix.update_leading_trivia(FormatTriviaType::Append(vec![
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -711,6 +720,7 @@ pub fn format_function_call<'ast>(
]));
}
+ shape = shape.take_last_line(&suffix);
formatted_suffixes.push(suffix);
}
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -757,6 +767,7 @@ pub fn format_function_name<'ast>(
pub fn format_function_declaration<'ast>(
ctx: &mut Context,
function_declaration: &FunctionDeclaration<'ast>,
+ shape: Shape,
) -> FunctionDeclaration<'ast> {
// Calculate trivia
let additional_indent_level =
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -766,7 +777,11 @@ pub fn format_function_declaration<'ast>(
let function_token = fmt_symbol!(ctx, function_declaration.function_token(), "function ")
.update_leading_trivia(FormatTriviaType::Append(leading_trivia));
let formatted_function_name = format_function_name(ctx, function_declaration.name());
- let formatted_function_body = format_function_body(ctx, function_declaration.body(), true);
+
+ let shape = shape.with_additional_indent(additional_indent_level)
+ + (9 + strip_trivia(&formatted_function_name).to_string().len()); // 9 = "function "
+ let formatted_function_body =
+ format_function_body(ctx, function_declaration.body(), true, shape);
FunctionDeclaration::new(formatted_function_name)
.with_function_token(function_token)
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -777,6 +792,7 @@ pub fn format_function_declaration<'ast>(
pub fn format_local_function<'ast>(
ctx: &mut Context,
local_function: &LocalFunction<'ast>,
+ shape: Shape,
) -> LocalFunction<'ast> {
// Calculate trivia
let additional_indent_level =
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -785,10 +801,12 @@ pub fn format_local_function<'ast>(
let local_token = fmt_symbol!(ctx, local_function.local_token(), "local ")
.update_leading_trivia(FormatTriviaType::Append(leading_trivia));
-
let function_token = fmt_symbol!(ctx, local_function.function_token(), "function ");
let formatted_name = format_token_reference(ctx, local_function.name());
- let formatted_function_body = format_function_body(ctx, local_function.body(), true);
+
+ let shape = shape.with_additional_indent(additional_indent_level)
+ + (6 + 9 + strip_trivia(&formatted_name).to_string().len()); // 6 = "local ", 9 = "function "
+ let formatted_function_body = format_function_body(ctx, local_function.body(), true, shape);
LocalFunction::new(formatted_name)
.with_local_token(local_token)
diff --git a/src/formatters/functions.rs b/src/formatters/functions.rs
--- a/src/formatters/functions.rs
+++ b/src/formatters/functions.rs
@@ -800,10 +818,13 @@ pub fn format_local_function<'ast>(
pub fn format_method_call<'ast>(
ctx: &mut Context,
method_call: &MethodCall<'ast>,
+ shape: Shape,
) -> MethodCall<'ast> {
let formatted_colon_token = format_token_reference(ctx, method_call.colon_token());
let formatted_name = format_token_reference(ctx, method_call.name());
- let formatted_function_args = format_function_args(ctx, method_call.args());
+ let shape =
+ shape + (formatted_colon_token.to_string().len() + formatted_name.to_string().len());
+ let formatted_function_args = format_function_args(ctx, method_call.args(), shape);
MethodCall::new(formatted_name, formatted_function_args).with_colon_token(formatted_colon_token)
}
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -6,6 +6,7 @@ use crate::{
trivia_util,
util::token_range,
},
+ shape::Shape,
QuoteStyle,
};
use full_moon::ast::{
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -338,6 +339,7 @@ pub fn format_token_reference<'a>(
pub fn format_token_reference_mut<'ast>(
ctx: &mut Context,
token_reference: &TokenReference<'ast>,
+ _: Shape,
) -> TokenReference<'ast> {
format_token_reference(ctx, token_reference)
}
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -375,13 +377,16 @@ pub fn format_punctuation<'ast>(
pub fn format_punctuated_buffer<'a, T, F>(
ctx: &mut Context,
old: &Punctuated<'a, T>,
+ shape: Shape,
value_formatter: F,
) -> (Punctuated<'a, T>, Vec<Token<'a>>)
where
- F: Fn(&mut Context, &T) -> T,
+ T: std::fmt::Display,
+ F: Fn(&mut Context, &T, Shape) -> T,
{
let mut formatted: Punctuated<T> = Punctuated::new();
let mut comments_buffer = Vec::new();
+ let mut shape = shape;
for pair in old.pairs() {
match pair {
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -390,12 +395,13 @@ where
let (formatted_punctuation, mut comments) = format_punctuation(punctuation);
comments_buffer.append(&mut comments);
- let formatted_value = value_formatter(ctx, value);
+ let formatted_value = value_formatter(ctx, value, shape);
+ shape = shape + (formatted_value.to_string().len() + 2); // 2 = ", "
formatted.push(Pair::new(formatted_value, Some(formatted_punctuation)));
}
Pair::End(value) => {
- let formatted_value = value_formatter(ctx, value);
+ let formatted_value = value_formatter(ctx, value, shape);
formatted.push(Pair::new(formatted_value, None));
}
}
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -410,23 +416,27 @@ where
pub fn format_punctuated<'a, T, F>(
ctx: &mut Context,
old: &Punctuated<'a, T>,
+ shape: Shape,
value_formatter: F,
) -> Punctuated<'a, T>
where
- F: Fn(&mut Context, &T) -> T,
+ T: std::fmt::Display,
+ F: Fn(&mut Context, &T, Shape) -> T,
{
let mut list: Punctuated<T> = Punctuated::new();
+ let mut shape = shape;
for pair in old.pairs() {
match pair {
Pair::Punctuated(value, punctuation) => {
- let value = value_formatter(ctx, value);
+ let value = value_formatter(ctx, value, shape);
let punctuation = fmt_symbol!(ctx, punctuation, ", ");
+ shape = shape + (value.to_string().len() + 2); // 2 = ", "
list.push(Pair::new(value, Some(punctuation)));
}
Pair::End(value) => {
- let value = value_formatter(ctx, value);
+ let value = value_formatter(ctx, value, shape);
list.push(Pair::new(value, None));
}
}
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -439,32 +449,39 @@ where
pub fn format_punctuated_multiline<'a, T, F>(
ctx: &mut Context,
old: &Punctuated<'a, T>,
+ shape: Shape,
value_formatter: F,
hang_level: Option<usize>,
) -> Punctuated<'a, T>
where
T: Node<'a>,
- F: Fn(&mut Context, &T) -> T,
+ F: Fn(&mut Context, &T, Shape) -> T,
{
let mut formatted: Punctuated<T> = Punctuated::new();
let mut is_first = true; // Don't want to add an indent range for the first item, as it will be inline
+ let mut shape = shape;
for pair in old.pairs() {
// Indent the pair (unless its the first item)
if is_first {
is_first = false;
} else {
- ctx.add_indent_range((
+ let range = (
pair.start_position()
.expect("no pair start position")
.bytes(),
pair.end_position().expect("no pair end position").bytes(),
- ))
+ );
+ let additional_indent_level = ctx.get_range_indent_increase(range);
+ ctx.add_indent_range(range); // TODO: should this be before we get the range indent increaese?
+ shape = shape
+ .reset()
+ .with_additional_indent(additional_indent_level);
}
match pair {
Pair::Punctuated(value, punctuation) => {
- let value = value_formatter(ctx, value);
+ let value = value_formatter(ctx, value, shape);
let punctuation = fmt_symbol!(ctx, punctuation, ",").update_trailing_trivia(
FormatTriviaType::Append(vec![
create_newline_trivia(ctx),
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -474,7 +491,7 @@ where
formatted.push(Pair::new(value, Some(punctuation)));
}
Pair::End(value) => {
- let formatted_value = value_formatter(ctx, value);
+ let formatted_value = value_formatter(ctx, value, shape);
formatted.push(Pair::new(formatted_value, None));
}
}
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -488,11 +505,12 @@ where
pub fn try_format_punctuated<'a, T, F>(
ctx: &mut Context,
old: &Punctuated<'a, T>,
+ shape: Shape,
value_formatter: F,
) -> Punctuated<'a, T>
where
- T: Node<'a>,
- F: Fn(&mut Context, &T) -> T,
+ T: Node<'a> + std::fmt::Display,
+ F: Fn(&mut Context, &T, Shape) -> T,
{
let mut format_multiline = false;
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -506,9 +524,9 @@ where
}
if format_multiline {
- format_punctuated_multiline(ctx, old, value_formatter, Some(1))
+ format_punctuated_multiline(ctx, old, shape, value_formatter, Some(1))
} else {
- format_punctuated(ctx, old, value_formatter)
+ format_punctuated(ctx, old, shape, value_formatter)
}
}
diff --git a/src/formatters/lua52.rs b/src/formatters/lua52.rs
--- a/src/formatters/lua52.rs
+++ b/src/formatters/lua52.rs
@@ -6,11 +6,12 @@ use crate::{
trivia::{FormatTriviaType, UpdateLeadingTrivia, UpdateTrailingTrivia},
util::token_range,
},
+ shape::Shape,
};
use full_moon::ast::lua52::{Goto, Label};
use full_moon::tokenizer::TokenReference;
-pub fn format_goto<'ast>(ctx: &Context, goto: &Goto<'ast>) -> Goto<'ast> {
+pub fn format_goto<'ast>(ctx: &Context, goto: &Goto<'ast>, _shape: Shape) -> Goto<'ast> {
// Calculate trivia
let additional_indent_level = ctx.get_range_indent_increase(token_range(goto.goto_token()));
let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
diff --git a/src/formatters/lua52.rs b/src/formatters/lua52.rs
--- a/src/formatters/lua52.rs
+++ b/src/formatters/lua52.rs
@@ -25,7 +26,7 @@ pub fn format_goto<'ast>(ctx: &Context, goto: &Goto<'ast>) -> Goto<'ast> {
Goto::new(label_name).with_goto_token(goto_token)
}
-pub fn format_label<'ast>(ctx: &Context, label: &Label<'ast>) -> Label<'ast> {
+pub fn format_label<'ast>(ctx: &Context, label: &Label<'ast>, _shape: Shape) -> Label<'ast> {
// Calculate trivia
let additional_indent_level = ctx.get_range_indent_increase(token_range(label.left_colons()));
let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
diff --git a/src/formatters/luau.rs b/src/formatters/luau.rs
--- a/src/formatters/luau.rs
+++ b/src/formatters/luau.rs
@@ -8,9 +8,12 @@ use crate::{
format_token_reference_mut, try_format_punctuated,
},
table::{create_table_braces, TableType},
- trivia::{FormatTriviaType, UpdateLeadingTrivia, UpdateTrailingTrivia},
+ trivia::{
+ strip_leading_trivia, FormatTriviaType, UpdateLeadingTrivia, UpdateTrailingTrivia,
+ },
util::{expression_range, token_range},
},
+ shape::Shape,
};
use full_moon::ast::types::{
CompoundAssignment, CompoundOp, ExportedTypeDeclaration, GenericDeclaration, IndexedTypeInfo,
diff --git a/src/formatters/luau.rs b/src/formatters/luau.rs
--- a/src/formatters/luau.rs
+++ b/src/formatters/luau.rs
@@ -39,22 +42,35 @@ pub fn format_compound_op<'ast>(ctx: &Context, compound_op: &CompoundOp<'ast>) -
pub fn format_compound_assignment<'ast>(
ctx: &mut Context,
compound_assignment: &CompoundAssignment<'ast>,
+ shape: Shape,
) -> CompoundAssignment<'ast> {
// Calculate trivia
let additional_indent_level =
ctx.get_range_indent_increase(expression_range(compound_assignment.rhs()));
+ let shape = shape.with_additional_indent(additional_indent_level);
let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
let trailing_trivia = vec![create_newline_trivia(ctx)];
- let lhs = format_var(ctx, compound_assignment.lhs())
+ let lhs = format_var(ctx, compound_assignment.lhs(), shape)
.update_leading_trivia(FormatTriviaType::Append(leading_trivia));
let compound_operator = format_compound_op(ctx, compound_assignment.compound_operator());
- let rhs = format_expression(ctx, compound_assignment.rhs())
+ let shape = shape
+ + (strip_leading_trivia(&lhs).to_string().len() + compound_operator.to_string().len());
+
+ let rhs = format_expression(ctx, compound_assignment.rhs(), shape)
.update_trailing_trivia(FormatTriviaType::Append(trailing_trivia));
CompoundAssignment::new(lhs, compound_operator, rhs)
}
+fn format_type_info_shape<'ast>(
+ ctx: &mut Context,
+ type_info: &TypeInfo<'ast>,
+ _shape: Shape,
+) -> TypeInfo<'ast> {
+ format_type_info(ctx, type_info)
+}
+
pub fn format_type_info<'ast>(ctx: &mut Context, type_info: &TypeInfo<'ast>) -> TypeInfo<'ast> {
match type_info {
TypeInfo::Array { braces, type_info } => {
diff --git a/src/formatters/luau.rs b/src/formatters/luau.rs
--- a/src/formatters/luau.rs
+++ b/src/formatters/luau.rs
@@ -80,7 +96,12 @@ pub fn format_type_info<'ast>(ctx: &mut Context, type_info: &TypeInfo<'ast>) ->
return_type,
} => {
let parentheses = format_contained_span(ctx, parentheses);
- let arguments = try_format_punctuated(ctx, arguments, format_type_info);
+ let arguments = try_format_punctuated(
+ ctx,
+ arguments,
+ Shape::from_context(ctx),
+ format_type_info_shape,
+ );
let arrow = fmt_symbol!(ctx, arrow, " -> ");
let return_type = Box::new(format_type_info(ctx, return_type));
TypeInfo::Callback {
diff --git a/src/formatters/luau.rs b/src/formatters/luau.rs
--- a/src/formatters/luau.rs
+++ b/src/formatters/luau.rs
@@ -98,7 +119,12 @@ pub fn format_type_info<'ast>(ctx: &mut Context, type_info: &TypeInfo<'ast>) ->
} => {
let base = format_token_reference(ctx, base);
let arrows = format_contained_span(ctx, arrows);
- let generics = try_format_punctuated(ctx, generics, format_type_info);
+ let generics = try_format_punctuated(
+ ctx,
+ generics,
+ Shape::from_context(ctx),
+ format_type_info_shape,
+ );
TypeInfo::Generic {
base,
arrows,
diff --git a/src/formatters/luau.rs b/src/formatters/luau.rs
--- a/src/formatters/luau.rs
+++ b/src/formatters/luau.rs
@@ -247,7 +273,7 @@ pub fn format_type_info<'ast>(ctx: &mut Context, type_info: &TypeInfo<'ast>) ->
),
);
let parentheses = format_contained_span(ctx, parentheses);
- let inner = Box::new(format_expression(ctx, inner));
+ let inner = Box::new(format_expression(ctx, inner, Shape::from_context(ctx)));
TypeInfo::Typeof {
typeof_token,
parentheses,
diff --git a/src/formatters/luau.rs b/src/formatters/luau.rs
--- a/src/formatters/luau.rs
+++ b/src/formatters/luau.rs
@@ -257,7 +283,8 @@ pub fn format_type_info<'ast>(ctx: &mut Context, type_info: &TypeInfo<'ast>) ->
TypeInfo::Tuple { parentheses, types } => {
let parentheses = format_contained_span(ctx, parentheses);
- let types = try_format_punctuated(ctx, types, format_type_info);
+ let types =
+ try_format_punctuated(ctx, types, Shape::from_context(ctx), format_type_info_shape);
TypeInfo::Tuple { parentheses, types }
}
diff --git a/src/formatters/luau.rs b/src/formatters/luau.rs
--- a/src/formatters/luau.rs
+++ b/src/formatters/luau.rs
@@ -290,7 +317,12 @@ pub fn format_indexed_type_info<'ast>(
} => {
let base = format_token_reference(ctx, base);
let arrows = format_contained_span(ctx, arrows);
- let generics = try_format_punctuated(ctx, generics, format_type_info);
+ let generics = try_format_punctuated(
+ ctx,
+ generics,
+ Shape::from_context(ctx),
+ format_type_info_shape,
+ );
IndexedTypeInfo::Generic {
base,
arrows,
diff --git a/src/formatters/luau.rs b/src/formatters/luau.rs
--- a/src/formatters/luau.rs
+++ b/src/formatters/luau.rs
@@ -395,6 +427,7 @@ fn format_type_declaration<'ast>(
pub fn format_type_declaration_stmt<'ast>(
ctx: &mut Context,
type_declaration: &TypeDeclaration<'ast>,
+ _shape: Shape,
) -> TypeDeclaration<'ast> {
format_type_declaration(ctx, type_declaration, true)
}
diff --git a/src/formatters/luau.rs b/src/formatters/luau.rs
--- a/src/formatters/luau.rs
+++ b/src/formatters/luau.rs
@@ -407,6 +440,7 @@ pub fn format_generic_declaration<'ast>(
let generics = try_format_punctuated(
ctx,
generic_declaration.generics(),
+ Shape::from_context(ctx),
format_token_reference_mut,
);
diff --git a/src/formatters/luau.rs b/src/formatters/luau.rs
--- a/src/formatters/luau.rs
+++ b/src/formatters/luau.rs
@@ -432,6 +466,7 @@ pub fn format_type_specifier<'ast>(
pub fn format_exported_type_declaration<'ast>(
ctx: &mut Context,
exported_type_declaration: &ExportedTypeDeclaration<'ast>,
+ _shape: Shape,
) -> ExportedTypeDeclaration<'ast> {
// Calculate trivia
let additional_indent_level =
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -11,7 +11,7 @@ use crate::{
fmt_symbol,
formatters::{
assignment::{format_assignment, format_local_assignment},
- expression::{format_expression, hang_expression},
+ expression::{format_expression, hang_expression_trailing_newline},
functions::{format_function_call, format_function_declaration, format_local_function},
general::{
format_end_token, format_punctuated_buffer, format_token_reference,
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -23,6 +23,7 @@ use crate::{
trivia_util,
util::{prefix_range, token_range},
},
+ shape::Shape,
};
use full_moon::ast::{
Do, ElseIf, Expression, FunctionCall, GenericFor, If, NumericFor, Repeat, Stmt, Value, While,
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -31,11 +32,11 @@ use full_moon::node::Node;
use full_moon::tokenizer::{Token, TokenReference, TokenType};
macro_rules! fmt_stmt {
- ($ctx:expr, $value:ident, { $($(#[$inner:meta])* $operator:ident = $output:ident,)+ }) => {
+ ($ctx:expr, $value:ident, $shape:ident, { $($(#[$inner:meta])* $operator:ident = $output:ident,)+ }) => {
match $value {
$(
$(#[$inner])*
- Stmt::$operator(stmt) => Stmt::$operator($output($ctx, stmt)),
+ Stmt::$operator(stmt) => Stmt::$operator($output($ctx, stmt, $shape)),
)+
other => panic!("unknown node {:?}", other),
}
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -56,7 +57,7 @@ fn remove_condition_parentheses(expression: Expression) -> Expression {
}
/// Format a Do node
-pub fn format_do_block<'ast>(ctx: &Context, do_block: &Do<'ast>) -> Do<'ast> {
+pub fn format_do_block<'ast>(ctx: &Context, do_block: &Do<'ast>, _shape: Shape) -> Do<'ast> {
// Create trivia
let additional_indent_level = ctx.get_range_indent_increase(token_range(do_block.do_token()));
let leading_trivia =
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -78,6 +79,7 @@ pub fn format_do_block<'ast>(ctx: &Context, do_block: &Do<'ast>) -> Do<'ast> {
pub fn format_generic_for<'ast>(
ctx: &mut Context,
generic_for: &GenericFor<'ast>,
+ shape: Shape,
) -> GenericFor<'ast> {
// Create trivia
let additional_indent_level =
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -85,10 +87,11 @@ pub fn format_generic_for<'ast>(
let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
let mut trailing_trivia = vec![create_newline_trivia(ctx)];
+ // TODO: Should we actually update the shape here?
let for_token = fmt_symbol!(ctx, generic_for.for_token(), "for ")
.update_leading_trivia(FormatTriviaType::Append(leading_trivia.to_owned()));
let (formatted_names, mut names_comments_buf) =
- format_punctuated_buffer(ctx, generic_for.names(), format_token_reference_mut);
+ format_punctuated_buffer(ctx, generic_for.names(), shape, format_token_reference_mut);
#[cfg(feature = "luau")]
let type_specifiers = generic_for
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -101,7 +104,7 @@ pub fn format_generic_for<'ast>(
let in_token = fmt_symbol!(ctx, generic_for.in_token(), " in ");
let (formatted_expr_list, mut expr_comments_buf) =
- format_punctuated_buffer(ctx, generic_for.expressions(), format_expression);
+ format_punctuated_buffer(ctx, generic_for.expressions(), shape, format_expression);
// Create comments buffer and append to end of do token
names_comments_buf.append(&mut expr_comments_buf);
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -131,10 +134,17 @@ pub fn format_generic_for<'ast>(
}
/// Formats an ElseIf node - This must always reside within format_if
-fn format_else_if<'ast>(ctx: &mut Context, else_if_node: &ElseIf<'ast>) -> ElseIf<'ast> {
+fn format_else_if<'ast>(
+ ctx: &mut Context,
+ else_if_node: &ElseIf<'ast>,
+ shape: Shape,
+) -> ElseIf<'ast> {
// Calculate trivia
let additional_indent_level =
ctx.get_range_indent_increase(token_range(else_if_node.else_if_token()));
+ let shape = shape
+ .reset()
+ .with_additional_indent(additional_indent_level);
let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
let trailing_trivia = vec![create_newline_trivia(ctx)];
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -142,14 +152,8 @@ fn format_else_if<'ast>(ctx: &mut Context, else_if_node: &ElseIf<'ast>) -> ElseI
let condition = remove_condition_parentheses(else_if_node.condition().to_owned());
// Determine if we need to hang the condition
- let last_line_str_len = (strip_trivia(else_if_node.else_if_token()).to_string()
- + &strip_trivia(&condition).to_string()
- + &strip_trivia(else_if_node.then_token()).to_string())
- .len()
- + 2; // Include space before and after condition
- let indent_spacing = ctx.indent_width_additional(additional_indent_level);
- let require_multiline_expression = (indent_spacing + last_line_str_len)
- > ctx.config().column_width
+ let singleline_shape = shape + (7 + 5 + strip_trivia(&condition).to_string().len()); // 7 = "elseif ", 5 = " then"
+ let require_multiline_expression = singleline_shape.over_budget()
|| trivia_util::expression_contains_inline_comments(&condition);
let (else_if_trailing_trivia, then_text) = if require_multiline_expression {
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -171,15 +175,15 @@ fn format_else_if<'ast>(ctx: &mut Context, else_if_node: &ElseIf<'ast>) -> ElseI
.expect("no range for else if condition");
ctx.add_indent_range((expr_range.0.bytes(), expr_range.1.bytes()));
- let condition = format_expression(ctx, &condition);
- hang_expression(ctx, condition, additional_indent_level, None).update_leading_trivia(
- FormatTriviaType::Append(vec![create_indent_trivia(
+ let indent_level = Some(additional_indent_level.unwrap_or(0) + 1);
+ let shape = shape.reset().with_additional_indent(indent_level);
+ hang_expression_trailing_newline(ctx, &condition, shape, additional_indent_level, None)
+ .update_leading_trivia(FormatTriviaType::Append(vec![create_indent_trivia(
ctx,
- Some(additional_indent_level.unwrap_or(0) + 1),
- )]),
- )
+ indent_level,
+ )]))
} else {
- format_expression(ctx, &condition)
+ format_expression(ctx, &condition, shape + 7) // 7 = "elseif "
};
let formatted_then_token = fmt_symbol!(ctx, else_if_node.then_token(), then_text)
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -200,9 +204,10 @@ fn format_else_if<'ast>(ctx: &mut Context, else_if_node: &ElseIf<'ast>) -> ElseI
}
/// Format an If node
-pub fn format_if<'ast>(ctx: &mut Context, if_node: &If<'ast>) -> If<'ast> {
+pub fn format_if<'ast>(ctx: &mut Context, if_node: &If<'ast>, shape: Shape) -> If<'ast> {
// Calculate trivia
let additional_indent_level = ctx.get_range_indent_increase(token_range(if_node.if_token()));
+ let shape = shape.with_additional_indent(additional_indent_level);
let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
let trailing_trivia = vec![create_newline_trivia(ctx)];
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -210,14 +215,8 @@ pub fn format_if<'ast>(ctx: &mut Context, if_node: &If<'ast>) -> If<'ast> {
let condition = remove_condition_parentheses(if_node.condition().to_owned());
// Determine if we need to hang the condition
- let last_line_str_len = (strip_trivia(if_node.if_token()).to_string()
- + &strip_trivia(&condition).to_string()
- + &strip_trivia(if_node.then_token()).to_string())
- .len()
- + 2; // Include space before and after condition
- let indent_spacing = ctx.indent_width_additional(additional_indent_level);
- let require_multiline_expression = (indent_spacing + last_line_str_len)
- > ctx.config().column_width
+ let singleline_shape = shape + (3 + 5 + strip_trivia(&condition).to_string().len()); // 3 = "if ", 5 = " then"
+ let require_multiline_expression = singleline_shape.over_budget()
|| trivia_util::expression_contains_inline_comments(&condition);
let (if_text, then_text) = if require_multiline_expression {
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -237,15 +236,15 @@ pub fn format_if<'ast>(ctx: &mut Context, if_node: &If<'ast>) -> If<'ast> {
.expect("no range for if condition");
ctx.add_indent_range((expr_range.0.bytes(), expr_range.1.bytes()));
- let condition = format_expression(ctx, &condition);
- hang_expression(ctx, condition, additional_indent_level, None).update_leading_trivia(
- FormatTriviaType::Append(vec![create_indent_trivia(
+ let indent_level = Some(additional_indent_level.unwrap_or(0) + 1);
+ let shape = shape.reset().with_additional_indent(indent_level);
+ hang_expression_trailing_newline(ctx, &condition, shape, additional_indent_level, None)
+ .update_leading_trivia(FormatTriviaType::Append(vec![create_indent_trivia(
ctx,
- Some(additional_indent_level.unwrap_or(0) + 1),
- )]),
- )
+ indent_level,
+ )]))
} else {
- format_expression(ctx, &condition)
+ format_expression(ctx, &condition, shape + 3) // 3 = "if "
};
let formatted_then_token = fmt_symbol!(ctx, if_node.then_token(), then_text).update_trivia(
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -266,7 +265,7 @@ pub fn format_if<'ast>(ctx: &mut Context, if_node: &If<'ast>) -> If<'ast> {
Some(else_if) => Some(
else_if
.iter()
- .map(|else_if| format_else_if(ctx, else_if))
+ .map(|else_if| format_else_if(ctx, else_if, shape))
.collect(),
),
None => None,
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -297,6 +296,7 @@ pub fn format_if<'ast>(ctx: &mut Context, if_node: &If<'ast>) -> If<'ast> {
pub fn format_numeric_for<'ast>(
ctx: &mut Context,
numeric_for: &NumericFor<'ast>,
+ shape: Shape,
) -> NumericFor<'ast> {
// Create trivia
let additional_indent_level =
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -314,10 +314,11 @@ pub fn format_numeric_for<'ast>(
None => None,
};
+ // TODO: Should we actually update the shape here?
let equal_token = fmt_symbol!(ctx, numeric_for.equal_token(), " = ");
- let formatted_start_expression = format_expression(ctx, numeric_for.start());
+ let formatted_start_expression = format_expression(ctx, numeric_for.start(), shape);
let start_end_comma = fmt_symbol!(ctx, numeric_for.start_end_comma(), ", ");
- let formatted_end_expression = format_expression(ctx, numeric_for.end());
+ let formatted_end_expression = format_expression(ctx, numeric_for.end(), shape);
let (end_step_comma, formatted_step_expression) = match numeric_for.step() {
Some(step) => (
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -326,7 +327,7 @@ pub fn format_numeric_for<'ast>(
numeric_for.end_step_comma().unwrap(),
", "
)),
- Some(format_expression(ctx, step)),
+ Some(format_expression(ctx, step, shape)),
),
None => (None, None),
};
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -358,10 +359,15 @@ pub fn format_numeric_for<'ast>(
}
/// Format a Repeat node
-pub fn format_repeat_block<'ast>(ctx: &mut Context, repeat_block: &Repeat<'ast>) -> Repeat<'ast> {
+pub fn format_repeat_block<'ast>(
+ ctx: &mut Context,
+ repeat_block: &Repeat<'ast>,
+ shape: Shape,
+) -> Repeat<'ast> {
// Calculate trivia
let additional_indent_level =
ctx.get_range_indent_increase(token_range(repeat_block.repeat_token()));
+ let shape = shape.with_additional_indent(additional_indent_level);
let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
let trailing_trivia = vec![create_newline_trivia(ctx)];
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -376,18 +382,12 @@ pub fn format_repeat_block<'ast>(ctx: &mut Context, repeat_block: &Repeat<'ast>)
let condition = remove_condition_parentheses(repeat_block.until().to_owned());
// Determine if we need to hang the condition
- let last_line_str_len = (strip_trivia(repeat_block.until_token()).to_string()
- + &strip_trivia(&condition).to_string())
- .len()
- + 1; // Include space before until and condition
-
- let indent_spacing = ctx.indent_width_additional(additional_indent_level);
- let require_multiline_expression = (indent_spacing + last_line_str_len)
- > ctx.config().column_width
+ let singleline_shape = shape + (6 + strip_trivia(&condition).to_string().len()); // 6 = "until "
+ let require_multiline_expression = singleline_shape.over_budget()
|| trivia_util::expression_contains_inline_comments(&condition);
- let formatted_until = format_expression(ctx, &condition);
- let formatted_until_trivia = match require_multiline_expression {
+ let shape = shape + 6; // 6 = "until "
+ let formatted_until = match require_multiline_expression {
true => {
// Add the expression list into the indent range, as it will be indented by one
let expr_range = repeat_block
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -395,23 +395,29 @@ pub fn format_repeat_block<'ast>(ctx: &mut Context, repeat_block: &Repeat<'ast>)
.range()
.expect("no range for repeat until");
ctx.add_indent_range((expr_range.0.bytes(), expr_range.1.bytes()));
- hang_expression(ctx, formatted_until, additional_indent_level, None)
+ hang_expression_trailing_newline(ctx, &condition, shape, additional_indent_level, None)
}
- false => formatted_until.update_trailing_trivia(FormatTriviaType::Append(trailing_trivia)),
+ false => format_expression(ctx, &condition, shape)
+ .update_trailing_trivia(FormatTriviaType::Append(trailing_trivia)),
};
repeat_block
.to_owned()
.with_repeat_token(repeat_token)
.with_until_token(until_token)
- .with_until(formatted_until_trivia)
+ .with_until(formatted_until)
}
/// Format a While node
-pub fn format_while_block<'ast>(ctx: &mut Context, while_block: &While<'ast>) -> While<'ast> {
+pub fn format_while_block<'ast>(
+ ctx: &mut Context,
+ while_block: &While<'ast>,
+ shape: Shape,
+) -> While<'ast> {
// Calculate trivia
let additional_indent_level =
ctx.get_range_indent_increase(token_range(while_block.while_token()));
+ let shape = shape.with_additional_indent(additional_indent_level);
let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
let trailing_trivia = vec![create_newline_trivia(ctx)];
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -419,14 +425,8 @@ pub fn format_while_block<'ast>(ctx: &mut Context, while_block: &While<'ast>) ->
let condition = remove_condition_parentheses(while_block.condition().to_owned());
// Determine if we need to hang the condition
- let last_line_str = strip_trivia(while_block.while_token()).to_string()
- + &strip_trivia(&condition).to_string()
- + &strip_trivia(while_block.do_token()).to_string();
- let last_line_str_len = last_line_str.len() + 2; // Include space before and after condition
-
- let indent_spacing = ctx.indent_width_additional(additional_indent_level);
- let require_multiline_expression = (indent_spacing + last_line_str_len)
- > ctx.config().column_width
+ let singleline_shape = shape + (6 + 3 + strip_trivia(&condition).to_string().len()); // 6 = "while ", 3 = " do"
+ let require_multiline_expression = singleline_shape.over_budget()
|| trivia_util::expression_contains_inline_comments(&condition);
let (while_text, do_text) = if require_multiline_expression {
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -446,15 +446,15 @@ pub fn format_while_block<'ast>(ctx: &mut Context, while_block: &While<'ast>) ->
.expect("no range for while condition");
ctx.add_indent_range((expr_range.0.bytes(), expr_range.1.bytes()));
- let condition = format_expression(ctx, &condition);
- hang_expression(ctx, condition, additional_indent_level, None).update_leading_trivia(
- FormatTriviaType::Append(vec![create_indent_trivia(
+ let indent_level = Some(additional_indent_level.unwrap_or(0) + 1);
+ let shape = shape.reset().with_additional_indent(indent_level);
+ hang_expression_trailing_newline(ctx, &condition, shape, additional_indent_level, None)
+ .update_leading_trivia(FormatTriviaType::Append(vec![create_indent_trivia(
ctx,
- Some(additional_indent_level.unwrap_or(0) + 1),
- )]),
- )
+ indent_level,
+ )]))
} else {
- format_expression(ctx, &condition)
+ format_expression(ctx, &condition, shape + 6) // 6 = "while "
};
let do_token = fmt_symbol!(ctx, while_block.do_token(), do_text).update_trivia(
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -486,23 +486,25 @@ pub fn format_while_block<'ast>(ctx: &mut Context, while_block: &While<'ast>) ->
pub fn format_function_call_stmt<'ast>(
ctx: &mut Context,
function_call: &FunctionCall<'ast>,
+ shape: Shape,
) -> FunctionCall<'ast> {
// Calculate trivia
let additional_indent_level =
ctx.get_range_indent_increase(prefix_range(function_call.prefix()));
+ let shape = shape.with_additional_indent(additional_indent_level);
let leading_trivia = vec![create_indent_trivia(ctx, additional_indent_level)];
let trailing_trivia = vec![create_newline_trivia(ctx)];
- format_function_call(ctx, function_call).update_trivia(
+ format_function_call(ctx, function_call, shape).update_trivia(
FormatTriviaType::Append(leading_trivia),
FormatTriviaType::Append(trailing_trivia),
)
}
-pub fn format_stmt<'ast>(ctx: &mut Context, stmt: &Stmt<'ast>) -> Stmt<'ast> {
+pub fn format_stmt<'ast>(ctx: &mut Context, stmt: &Stmt<'ast>, shape: Shape) -> Stmt<'ast> {
check_should_format!(ctx, stmt);
- fmt_stmt!(ctx, stmt, {
+ fmt_stmt!(ctx, stmt, shape, {
Assignment = format_assignment,
Do = format_do_block,
FunctionCall = format_function_call_stmt,
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -7,10 +7,11 @@ use crate::{
format_contained_span, format_end_token, format_symbol, format_token_reference,
EndTokenType,
},
- trivia::{FormatTriviaType, UpdateLeadingTrivia, UpdateTrailingTrivia},
+ trivia::{strip_trivia, FormatTriviaType, UpdateLeadingTrivia, UpdateTrailingTrivia},
trivia_util,
util::{expression_range, token_range},
},
+ shape::Shape,
};
use full_moon::ast::{
punctuated::{Pair, Punctuated},
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -34,6 +35,7 @@ pub fn format_field<'ast>(
ctx: &mut Context,
field: &Field<'ast>,
leading_trivia: FormatTriviaType<'ast>,
+ shape: Shape,
) -> (Field<'ast>, Vec<Token<'ast>>) {
let trailing_trivia;
let field = match field {
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -44,28 +46,33 @@ pub fn format_field<'ast>(
value,
} => {
trailing_trivia = trivia_util::get_expression_trailing_trivia(value);
+ let brackets =
+ format_contained_span(ctx, brackets).update_leading_trivia(leading_trivia);
+ let key = format_expression(ctx, key, shape + 1); // 1 = opening bracket
+ let equal = fmt_symbol!(ctx, equal, " = ");
+ let shape = shape.take_last_line(&key) + (2 + 3); // 2 = brackets, 3 = " = "
+ let value = format_expression(ctx, value, shape)
+ .update_trailing_trivia(FormatTriviaType::Replace(vec![])); // We will remove all the trivia from this value, and place it after the comma
Field::ExpressionKey {
- brackets: format_contained_span(ctx, brackets)
- .update_leading_trivia(leading_trivia),
- key: format_expression(ctx, key),
- equal: fmt_symbol!(ctx, equal, " = "),
- // We will remove all the trivia from this value, and place it after the comma
- value: format_expression(ctx, value)
- .update_trailing_trivia(FormatTriviaType::Replace(vec![])),
+ brackets,
+ key,
+ equal,
+ value,
}
}
Field::NameKey { key, equal, value } => {
trailing_trivia = trivia_util::get_expression_trailing_trivia(value);
- Field::NameKey {
- key: format_token_reference(ctx, key).update_leading_trivia(leading_trivia),
- equal: fmt_symbol!(ctx, equal, " = "),
- value: format_expression(ctx, value)
- .update_trailing_trivia(FormatTriviaType::Replace(vec![])),
- }
+ let key = format_token_reference(ctx, key).update_leading_trivia(leading_trivia);
+ let equal = fmt_symbol!(ctx, equal, " = ");
+ let shape = shape + (strip_trivia(&key).to_string().len() + 3); // 3 = " = "
+ let value = format_expression(ctx, value, shape)
+ .update_trailing_trivia(FormatTriviaType::Replace(vec![]));
+
+ Field::NameKey { key, equal, value }
}
Field::NoKey(expression) => {
trailing_trivia = trivia_util::get_expression_trailing_trivia(expression);
- let formatted_expression = format_expression(ctx, expression);
+ let formatted_expression = format_expression(ctx, expression, shape);
if let FormatTriviaType::NoChange = leading_trivia {
Field::NoKey(formatted_expression)
} else {
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -139,6 +146,7 @@ pub fn create_table_braces<'ast>(
pub fn format_table_constructor<'ast>(
ctx: &mut Context,
table_constructor: &TableConstructor<'ast>,
+ shape: Shape,
) -> TableConstructor<'ast> {
let mut fields = Punctuated::new();
let mut current_fields = table_constructor
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -153,13 +161,8 @@ pub fn format_table_constructor<'ast>(
end_brace.token().start_position().bytes(),
);
- // We subtract 20 as we don't have full information about what preceded this table constructor (e.g. the assignment).
- // This is used as a general estimate. TODO: see if we can improve this calculation
- let mut is_multiline =
- (braces_range.1 - braces_range.0) + ctx.indent_width() > ctx.config().column_width - 20;
-
- // Determine if there are any comments within the table. If so, we should go multiline
- if !is_multiline {
+ // Determine if there are any comments within the table. If so, we should force, multiline
+ let contains_comments = {
let braces_contain_comments = start_brace.trailing_trivia().any(|trivia| {
trivia.token_kind() == TokenKind::SingleLineComment
|| trivia.token_kind() == TokenKind::MultiLineComment
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -168,14 +171,20 @@ pub fn format_table_constructor<'ast>(
|| trivia.token_kind() == TokenKind::MultiLineComment
});
- is_multiline = braces_contain_comments
- || trivia_util::table_fields_contains_comments(table_constructor)
+ braces_contain_comments || trivia_util::table_fields_contains_comments(table_constructor)
};
- let table_type = match is_multiline {
- true => TableType::MultiLine,
- false => match current_fields.peek() {
- Some(_) => {
+ // Use input shape to determine if we are over budget
+ // TODO: should we format the table onto a single line first?
+ let singleline_shape = shape + (braces_range.1 - braces_range.0);
+
+ let table_type = match (contains_comments, current_fields.peek()) {
+ // We have comments, so force multiline
+ (true, _) => TableType::MultiLine,
+
+ (false, Some(_)) => match singleline_shape.over_budget() {
+ true => TableType::MultiLine,
+ false => {
// Determine if there was a new line at the end of the start brace
// If so, then we should always be multiline
if start_brace
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -187,8 +196,8 @@ pub fn format_table_constructor<'ast>(
TableType::SingleLine
}
}
- None => TableType::Empty,
},
+ (false, None) => TableType::Empty,
};
if let TableType::MultiLine = table_type {
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -205,6 +214,12 @@ pub fn format_table_constructor<'ast>(
additional_indent_level,
);
+ let mut shape = match table_type {
+ TableType::SingleLine => shape + 2, // 1 = opening brace, 1 = space
+ TableType::MultiLine => shape.reset(), // Will take new line
+ TableType::Empty => shape,
+ };
+
while let Some(pair) = current_fields.next() {
let (field, punctuation) = pair.into_tuple();
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -219,12 +234,16 @@ pub fn format_table_constructor<'ast>(
other => panic!("unknown node {:?}", other),
};
let additional_indent_level = ctx.get_range_indent_increase(range);
+ shape = shape
+ .reset()
+ .with_additional_indent(additional_indent_level);
FormatTriviaType::Append(vec![create_indent_trivia(ctx, additional_indent_level)])
}
_ => FormatTriviaType::NoChange,
};
- let (formatted_field, mut trailing_trivia) = format_field(ctx, &field, leading_trivia);
+ let (formatted_field, mut trailing_trivia) =
+ format_field(ctx, &field, leading_trivia, shape);
// Filter trailing_trivia for any newlines
trailing_trivia = trailing_trivia
.iter()
diff --git a/src/formatters/table.rs b/src/formatters/table.rs
--- a/src/formatters/table.rs
+++ b/src/formatters/table.rs
@@ -249,6 +268,7 @@ pub fn format_table_constructor<'ast>(
_ => {
if current_fields.peek().is_some() {
// Have more elements still to go
+ shape = shape + (formatted_field.to_string().len() + 2); // 2 = ", "
formatted_punctuation = match punctuation {
Some(punctuation) => Some(format_symbol(
ctx,
diff --git a/src/formatters/trivia.rs b/src/formatters/trivia.rs
--- a/src/formatters/trivia.rs
+++ b/src/formatters/trivia.rs
@@ -2,8 +2,8 @@
use full_moon::ast::types::{IndexedTypeInfo, TypeAssertion, TypeInfo, TypeSpecifier};
use full_moon::ast::{
punctuated::Punctuated, span::ContainedSpan, BinOp, Call, Expression, FunctionArgs,
- FunctionBody, FunctionCall, Index, MethodCall, Parameter, Prefix, Suffix, TableConstructor,
- UnOp, Value, Var, VarExpression,
+ FunctionBody, FunctionCall, FunctionName, Index, MethodCall, Parameter, Prefix, Suffix,
+ TableConstructor, UnOp, Value, Var, VarExpression,
};
use full_moon::tokenizer::{Token, TokenReference};
diff --git a/src/formatters/trivia.rs b/src/formatters/trivia.rs
--- a/src/formatters/trivia.rs
+++ b/src/formatters/trivia.rs
@@ -28,6 +28,20 @@ where
.update_trailing_trivia(FormatTriviaType::Replace(vec![]))
}
+pub fn strip_leading_trivia<'ast, T>(item: &T) -> T
+where
+ T: UpdateLeadingTrivia<'ast>,
+{
+ item.update_leading_trivia(FormatTriviaType::Replace(vec![]))
+}
+
+pub fn strip_trailing_trivia<'ast, T>(item: &T) -> T
+where
+ T: UpdateTrailingTrivia<'ast>,
+{
+ item.update_trailing_trivia(FormatTriviaType::Replace(vec![]))
+}
+
pub trait UpdateLeadingTrivia<'ast> {
fn update_leading_trivia(&self, leading_trivia: FormatTriviaType<'ast>) -> Self;
}
diff --git a/src/formatters/trivia.rs b/src/formatters/trivia.rs
--- a/src/formatters/trivia.rs
+++ b/src/formatters/trivia.rs
@@ -311,6 +325,22 @@ define_update_trivia!(FunctionCall, |this, leading, trailing| {
this.to_owned().with_prefix(prefix).with_suffixes(suffixes)
});
+define_update_trivia!(FunctionName, |this, leading, trailing| {
+ if let Some(method_name) = this.method_name() {
+ let names = this.names().update_leading_trivia(leading);
+ let method_name = method_name.update_trailing_trivia(trailing);
+ this.to_owned()
+ .with_names(names)
+ .with_method(Some((this.method_colon().unwrap().to_owned(), method_name)))
+ } else {
+ let names = this
+ .names()
+ .update_leading_trivia(leading)
+ .update_trailing_trivia(trailing);
+ this.to_owned().with_names(names)
+ }
+});
+
define_update_trivia!(Index, |this, leading, trailing| {
match this {
Index::Brackets {
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -5,6 +5,7 @@ use serde::Deserialize;
#[macro_use]
mod context;
mod formatters;
+mod shape;
/// The type of indents to use when indenting
#[derive(Debug, Copy, Clone, Deserialize)]
|
diff --git /dev/null b/src/shape.rs
new file mode 100644
--- /dev/null
+++ b/src/shape.rs
@@ -0,0 +1,125 @@
+use crate::context::Context;
+use std::fmt::Display;
+use std::ops::Add;
+
+#[derive(Clone, Copy, Debug)]
+pub struct Shape {
+ /// The current block indentation level. The base indentation level is 0. Note: this is not the indentation width
+ indent_level: usize,
+ /// How many characters a single indent level represents. This is inferred from the configuration
+ indent_width: usize,
+ /// Any additional indent level that we are currently in.
+ additional_indent_level: usize,
+ /// The current width we have taken on the line, excluding any indentation.
+ offset: usize,
+ /// The maximum number of characters we want to fit on a line. This is inferred from the configuration
+ column_width: usize,
+}
+
+impl Shape {
+ pub fn from_context(ctx: &Context) -> Self {
+ Self {
+ indent_level: ctx.indent_level().saturating_sub(1),
+ indent_width: ctx.config().indent_width,
+ additional_indent_level: 0,
+ offset: 0,
+ column_width: ctx.config().column_width,
+ }
+ }
+
+ /// Create a shape with a given block indent level
+ pub fn with_indent_level(ctx: &Context, indent_level: usize) -> Self {
+ Self {
+ indent_level,
+ indent_width: ctx.config().indent_width,
+ additional_indent_level: 0,
+ offset: 0,
+ column_width: ctx.config().column_width,
+ }
+ }
+
+ /// Create a new shape containing any additional indent level
+ pub fn with_additional_indent(&self, additional_indent_level: Option<usize>) -> Shape {
+ match additional_indent_level {
+ Some(t) => Self {
+ additional_indent_level: t,
+ ..*self
+ },
+ None => *self,
+ }
+ }
+
+ /// Sets the column width to the provided width. Normally only used to set an infinite width when testing layouts
+ pub fn with_column_width(&self, column_width: usize) -> Self {
+ Self {
+ column_width,
+ ..*self
+ }
+ }
+
+ /// Recreates the shape with an infinite width. Useful when testing layouts and want to force code onto a single line
+ pub fn with_infinite_width(&self) -> Self {
+ self.with_column_width(usize::MAX)
+ }
+
+ pub fn indent_width(&self) -> usize {
+ (self.indent_level + self.additional_indent_level) * self.indent_width
+ }
+
+ /// The width currently taken up for this line
+ pub fn used_width(&self) -> usize {
+ self.indent_width() + self.offset
+ }
+
+ /// Check to see whether our current width is above the budget available
+ pub fn over_budget(&self) -> bool {
+ self.used_width() > self.column_width
+ }
+
+ /// Adds a width offset to the current width total
+ pub fn add_width(&self, width: usize) -> Shape {
+ Self {
+ offset: self.offset + width,
+ ..*self
+ }
+ }
+
+ /// Resets the offset for the shape
+ pub fn reset(&self) -> Shape {
+ Self { offset: 0, ..*self }
+ }
+
+ /// Takes the first line from an item which can be converted into a string, and sets that to the the shape
+ pub fn take_first_line<T: Display>(&self, item: &T) -> Shape {
+ let string = format!("{}", item);
+ let mut lines = string.lines();
+ let width = lines.next().expect("no lines").len();
+ self.add_width(width)
+ }
+
+ /// Takes an item which could possibly span multiple lines. If it spans multiple lines, the shape is reset
+ /// and the last line is added to the width. If it only takes a single line, we just continue adding to the current
+ /// width
+ pub fn take_last_line<T: Display>(&self, item: &T) -> Shape {
+ let string = format!("{}", item);
+ let mut lines = string.lines();
+ let last_item = lines.next_back().expect("no lines");
+
+ // Check if we have any more lines remaining
+ if lines.count() > 0 {
+ // Reset the shape and add the last line
+ self.reset().add_width(last_item.len())
+ } else {
+ // Continue adding to the current shape
+ self.add_width(last_item.len())
+ }
+ }
+}
+
+impl Add<usize> for Shape {
+ type Output = Shape;
+
+ fn add(self, rhs: usize) -> Shape {
+ self.add_width(rhs)
+ }
+}
diff --git /dev/null b/tests/inputs/context-long-lines.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs/context-long-lines.lua
@@ -0,0 +1,17 @@
+do
+ local region = Region3.new(part.Position - (0.5 * part.Size), part.Position + (0.5 * part.Size))
+
+ do
+ do
+ return function(...)
+ callback(LOG_FORMAT:format(os.date("%H:%M:%S"), key, level, fmt.fmt(...)))
+ end
+ end
+ end
+
+ self.digits = math.ceil(math.log10(math.max(math.abs(self.props.maxValue), math.abs(self.props.minValue))))
+end
+
+local gamemodes, keysById, idsByKey = createDataIndex(script.AllGamemodes, validateGamemodeSchema)
+
+HealthRegen.ValidateInstance = t.intersection(ComponentUtil.HasComponentValidator("Health"), ComponentUtil.HasComponentValidator("Target"))
\ No newline at end of file
diff --git a/tests/inputs/function-def-multiline.lua b/tests/inputs/function-def-multiline.lua
--- a/tests/inputs/function-def-multiline.lua
+++ b/tests/inputs/function-def-multiline.lua
@@ -1,4 +1,7 @@
-function foo(fooooo, barrrrrrrrrr, bazzzzzzzzzzzzzzz, fooooooooooo, bazzzzzzzzzzzzzzzzzzz, barrrrrrrrrrrrrrrrrrrrrrrr, fooooooobarbaz)
+function foo(foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo, barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr)
+end
+
+function foobar(fooooo, barrrrrrrrrr, bazzzzzzzzzzzzzzz, fooooooooooo, bazzzzzzzzzzzzzzzzzzz, barrrrrrrrrrrrrrrrrrrrrrrr)
print("test")
end
diff --git a/tests/inputs/function-def-multiline.lua b/tests/inputs/function-def-multiline.lua
--- a/tests/inputs/function-def-multiline.lua
+++ b/tests/inputs/function-def-multiline.lua
@@ -9,6 +12,11 @@ do
end
end
+do
+ function bar(foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo, barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr)
+ end
+end
+
local x = {
func = function (fooooo, bar --test
)
diff --git a/tests/inputs/long-assignment.lua b/tests/inputs/long-assignment.lua
--- a/tests/inputs/long-assignment.lua
+++ b/tests/inputs/long-assignment.lua
@@ -4,4 +4,8 @@ LoadAddOn, UnitName, GetRealmName, UnitRace, UnitFactionGroup, IsInRaid = LoadAd
do
local LoadAddOn, UnitName, GetRealmName, UnitRace, UnitFactionGroup, IsInRaid = LoadAddOn, UnitName, GetRealmName, UnitRace, UnitFactionGroup, IsInRaid
+end
+
+do
+ local XOffset, YOffset, ZOffset = CFrame.new(GlobalConfiguration.TPS_CAMERA_OFFSET.X, 0, 0), CFrame.new(0, GlobalConfiguration.TPS_CAMERA_OFFSET.Y, 0), CFrame.new(0, 0, GlobalConfiguration.TPS_CAMERA_OFFSET.Z)
end
\ No newline at end of file
diff --git a/tests/snapshots/tests__luau@large_example.lua.snap b/tests/snapshots/tests__luau@large_example.lua.snap
--- a/tests/snapshots/tests__luau@large_example.lua.snap
+++ b/tests/snapshots/tests__luau@large_example.lua.snap
@@ -67,7 +67,11 @@ function API.isReady()
return not not dump
end
-function API.getMembers(class: string, tagFilter: Array<string>?, securityFilter: Array<string>?): Dictionary<ApiTypes.Member>
+function API.getMembers(
+ class: string,
+ tagFilter: Array<string>?,
+ securityFilter: Array<string>?
+): Dictionary<ApiTypes.Member>
if not dump then
error(MODULE_NOT_READY_MESSAGE, 2)
end
diff --git a/tests/snapshots/tests__luau@large_example.lua.snap b/tests/snapshots/tests__luau@large_example.lua.snap
--- a/tests/snapshots/tests__luau@large_example.lua.snap
+++ b/tests/snapshots/tests__luau@large_example.lua.snap
@@ -97,7 +101,11 @@ function API.getMembers(class: string, tagFilter: Array<string>?, securityFilter
return memberList
end
-function API.getProperties(class: string, tagFilter: Array<string>?, securityFilter: Array<string>?): Dictionary<ApiTypes.Property>
+function API.getProperties(
+ class: string,
+ tagFilter: Array<string>?,
+ securityFilter: Array<string>?
+): Dictionary<ApiTypes.Property>
if not dump then
error(MODULE_NOT_READY_MESSAGE, 2)
end
diff --git a/tests/snapshots/tests__luau@large_example.lua.snap b/tests/snapshots/tests__luau@large_example.lua.snap
--- a/tests/snapshots/tests__luau@large_example.lua.snap
+++ b/tests/snapshots/tests__luau@large_example.lua.snap
@@ -130,7 +138,11 @@ function API.getProperties(class: string, tagFilter: Array<string>?, securityFil
return memberList
end
-function API.getFunctions(class: string, tagFilter: Array<string>?, securityFilter: Array<string>?): Dictionary<ApiTypes.Function>
+function API.getFunctions(
+ class: string,
+ tagFilter: Array<string>?,
+ securityFilter: Array<string>?
+): Dictionary<ApiTypes.Function>
if not dump then
error(MODULE_NOT_READY_MESSAGE, 2)
end
diff --git a/tests/snapshots/tests__luau@large_example.lua.snap b/tests/snapshots/tests__luau@large_example.lua.snap
--- a/tests/snapshots/tests__luau@large_example.lua.snap
+++ b/tests/snapshots/tests__luau@large_example.lua.snap
@@ -163,7 +175,11 @@ function API.getFunctions(class: string, tagFilter: Array<string>?, securityFilt
return memberList
end
-function API.getEvents(class: string, tagFilter: Array<string>?, securityFilter: Array<string>?): Dictionary<ApiTypes.Event>
+function API.getEvents(
+ class: string,
+ tagFilter: Array<string>?,
+ securityFilter: Array<string>?
+): Dictionary<ApiTypes.Event>
if not dump then
error(MODULE_NOT_READY_MESSAGE, 2)
end
diff --git a/tests/snapshots/tests__luau@large_example.lua.snap b/tests/snapshots/tests__luau@large_example.lua.snap
--- a/tests/snapshots/tests__luau@large_example.lua.snap
+++ b/tests/snapshots/tests__luau@large_example.lua.snap
@@ -196,7 +212,11 @@ function API.getEvents(class: string, tagFilter: Array<string>?, securityFilter:
return memberList
end
-function API.getCallbacks(class: string, tagFilter: Array<string>?, securityFilter: Array<string>?): Dictionary<ApiTypes.Callback>
+function API.getCallbacks(
+ class: string,
+ tagFilter: Array<string>?,
+ securityFilter: Array<string>?
+): Dictionary<ApiTypes.Callback>
if not dump then
error(MODULE_NOT_READY_MESSAGE, 2)
end
diff --git /dev/null b/tests/snapshots/tests__standard@context-long-lines.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/tests__standard@context-long-lines.lua.snap
@@ -0,0 +1,26 @@
+---
+source: tests/tests.rs
+expression: format(&contents)
+
+---
+do
+ local region = Region3.new(part.Position - (0.5 * part.Size), part.Position + (0.5 * part.Size))
+
+ do
+ do
+ return function(...)
+ callback(LOG_FORMAT:format(os.date("%H:%M:%S"), key, level, fmt.fmt(...)))
+ end
+ end
+ end
+
+ self.digits = math.ceil(math.log10(math.max(math.abs(self.props.maxValue), math.abs(self.props.minValue))))
+end
+
+local gamemodes, keysById, idsByKey = createDataIndex(script.AllGamemodes, validateGamemodeSchema)
+
+HealthRegen.ValidateInstance = t.intersection(
+ ComponentUtil.HasComponentValidator("Health"),
+ ComponentUtil.HasComponentValidator("Target")
+)
+
diff --git a/tests/snapshots/tests__standard@function-def-multiline.lua.snap b/tests/snapshots/tests__standard@function-def-multiline.lua.snap
--- a/tests/snapshots/tests__standard@function-def-multiline.lua.snap
+++ b/tests/snapshots/tests__standard@function-def-multiline.lua.snap
@@ -3,14 +3,16 @@ source: tests/tests.rs
expression: format(&contents)
---
-function foo(
+function foo(foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo, barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr)
+end
+
+function foobar(
fooooo,
barrrrrrrrrr,
bazzzzzzzzzzzzzzz,
fooooooooooo,
bazzzzzzzzzzzzzzzzzzz,
- barrrrrrrrrrrrrrrrrrrrrrrr,
- fooooooobarbaz
+ barrrrrrrrrrrrrrrrrrrrrrrr
)
print("test")
end
diff --git a/tests/snapshots/tests__standard@function-def-multiline.lua.snap b/tests/snapshots/tests__standard@function-def-multiline.lua.snap
--- a/tests/snapshots/tests__standard@function-def-multiline.lua.snap
+++ b/tests/snapshots/tests__standard@function-def-multiline.lua.snap
@@ -24,6 +26,14 @@ do
end
end
+do
+ function bar(
+ foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo,
+ barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
+ )
+ end
+end
+
local x = {
func = function(
fooooo,
diff --git a/tests/snapshots/tests__standard@long-assignment.lua.snap b/tests/snapshots/tests__standard@long-assignment.lua.snap
--- a/tests/snapshots/tests__standard@long-assignment.lua.snap
+++ b/tests/snapshots/tests__standard@long-assignment.lua.snap
@@ -14,3 +14,9 @@ do
LoadAddOn, UnitName, GetRealmName, UnitRace, UnitFactionGroup, IsInRaid
end
+do
+ local XOffset, YOffset, ZOffset = CFrame.new(GlobalConfiguration.TPS_CAMERA_OFFSET.X, 0, 0),
+ CFrame.new(0, GlobalConfiguration.TPS_CAMERA_OFFSET.Y, 0),
+ CFrame.new(0, 0, GlobalConfiguration.TPS_CAMERA_OFFSET.Z)
+end
+
|
Turns readable multi-line function calls into harder to read, single line ones, but are under the column width
I'm not sure if this is something that's able to be fixed, but this is the before and after. I much prefer the before.




vvv This is 140 columns long, without any configuration.

|
I definitely also prefer the former styling here, so this should be looked into.
I think part of the reason for this problem is because of the way I set up formatting for function args - when it happens, StyLua only sees the parentheses and anything inside of them, not the previous information on the line - so it's hard to judge when to wrap. I'm probably going to have to give it access to some more context
Just thought I'd let you know - you may find that the formatting is better for you if you reduce the column with (maybe to something like 80 or 100). It may help in these situations, but there are still cases where it won't do as wanted/expected (such as your local assignment example with three variables - it won't catch that this line is greater than the column width.)
Maybe, but 120 cols is already the rule I follow internally, feels weird to lower that down for the sake of StyLua.
Yeah I ran into this as well, feels a bit weird having this tied to the col width only!
|
2021-04-30T00:06:22Z
|
0.7
|
2021-04-30T12:15:38Z
|
aa9d9319d0314a853c4f56d3c120525668dc1a8a
|
[
"test_luau"
] |
[
"test_lua52"
] |
[] |
[] |
JohnnyMorganz/StyLua
| 931
|
JohnnyMorganz__StyLua-931
|
[
"928"
] |
d67c77b6f73ccab63d544adffe9cf3d859e71fa4
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- Fixed regression where configuration present in current working directory not used when formatting from stdin and no `--stdin-filepath` is provided ([#928](https://github.com/JohnnyMorganz/StyLua/issues/928))
+
## [2.0.1] - 2024-11-18
### Added
diff --git a/src/cli/config.rs b/src/cli/config.rs
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -55,15 +55,22 @@ impl ConfigResolver<'_> {
})
}
+ /// Returns the root used when searching for configuration
+ /// If `--search-parent-directories`, then there is no root, and we keep searching
+ /// Else, the root is the current working directory, and we do not search higher than the cwd
+ fn get_configuration_search_root(&self) -> Option<PathBuf> {
+ match self.opt.search_parent_directories {
+ true => None,
+ false => Some(self.current_directory.to_path_buf()),
+ }
+ }
+
pub fn load_configuration(&mut self, path: &Path) -> Result<Config> {
if let Some(configuration) = self.forced_configuration {
return Ok(configuration);
}
- let root = match self.opt.search_parent_directories {
- true => None,
- false => Some(self.current_directory.to_path_buf()),
- };
+ let root = self.get_configuration_search_root();
let absolute_path = self.current_directory.join(path);
let parent_path = &absolute_path
diff --git a/src/cli/config.rs b/src/cli/config.rs
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -91,19 +98,25 @@ impl ConfigResolver<'_> {
return Ok(configuration);
}
+ let root = self.get_configuration_search_root();
+ let my_current_directory = self.current_directory.to_owned();
+
match &self.opt.stdin_filepath {
Some(filepath) => self.load_configuration(filepath),
- None => {
- #[cfg(feature = "editorconfig")]
- if self.opt.no_editorconfig {
+ None => match self.find_config_file(&my_current_directory, root)? {
+ Some(config) => Ok(config),
+ None => {
+ #[cfg(feature = "editorconfig")]
+ if self.opt.no_editorconfig {
+ Ok(self.default_configuration)
+ } else {
+ editorconfig::parse(self.default_configuration, &PathBuf::from("*.lua"))
+ .context("could not parse editorconfig")
+ }
+ #[cfg(not(feature = "editorconfig"))]
Ok(self.default_configuration)
- } else {
- editorconfig::parse(self.default_configuration, &PathBuf::from("*.lua"))
- .context("could not parse editorconfig")
}
- #[cfg(not(feature = "editorconfig"))]
- Ok(self.default_configuration)
- }
+ },
}
}
|
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -810,6 +810,24 @@ mod tests {
cwd.close().unwrap();
}
+ #[test]
+ fn test_cwd_configuration_respected_when_formatting_from_stdin() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferSingle'",
+ "foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .arg("-")
+ .write_stdin("local x = \"hello\"")
+ .assert()
+ .success()
+ .stdout("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
+
#[test]
fn test_cwd_configuration_respected_for_file_in_cwd() {
let cwd = construct_tree!({
|
after new release stdin does not repsect .stylua.toml by default
unless must set config-path .. before no need

|
Looks like a mistake in https://github.com/JohnnyMorganz/StyLua/blob/1daf4c18fb6baf687cc41082f1cc6905ced226a4/src/cli/config.rs#L96, we forget to check the current directory if stdin file path was not provided. Thanks for reporting!
As a work around, you can use `--stdin-filepath` to specify the file path for the file you're formatting. It can even be a dummy file: `--stdin-filepath ./dummy` should in theory lookup config in the current working directory
sure but hope can fix in next release
|
2024-11-30T20:21:18Z
|
2.0
|
2024-11-30T12:36:13Z
|
f581279895a7040a36abaea4a6c8a6f50f112cd7
|
[
"tests::test_cwd_configuration_respected_when_formatting_from_stdin"
] |
[
"editorconfig::tests::test_collapse_simple_statement_always",
"editorconfig::tests::test_call_parentheses_always",
"editorconfig::tests::test_collapse_simple_statement_conditional_only",
"editorconfig::tests::test_call_parentheses_no_single_string",
"editorconfig::tests::test_collapse_simple_statement_function_only",
"editorconfig::tests::test_call_parentheses_no_single_table",
"editorconfig::tests::test_collapse_simple_statement_never",
"editorconfig::tests::test_call_parentheses_none",
"editorconfig::tests::test_end_of_line_cr",
"editorconfig::tests::test_end_of_line_lf",
"editorconfig::tests::test_end_of_line_crlf",
"editorconfig::tests::test_indent_size",
"editorconfig::tests::test_indent_style_space",
"editorconfig::tests::test_indent_style_tab",
"editorconfig::tests::test_indent_size_use_tab_width",
"editorconfig::tests::test_invalid_properties",
"editorconfig::tests::test_max_line_length",
"editorconfig::tests::test_max_line_length_off",
"editorconfig::tests::test_quote_type_auto",
"editorconfig::tests::test_quote_type_double",
"editorconfig::tests::test_quote_type_single",
"editorconfig::tests::test_sort_requires_disabled",
"editorconfig::tests::test_sort_requires_enabled",
"editorconfig::tests::test_space_after_function_names_always",
"editorconfig::tests::test_space_after_function_names_calls",
"editorconfig::tests::test_space_after_function_names_definitions",
"editorconfig::tests::test_space_after_function_names_never",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments_2",
"sort_requires::tests::fail_extracting_non_identifier_token",
"formatters::trivia_util::tests::test_token_contains_singleline_comments",
"sort_requires::tests::get_expression_kind_other_1",
"sort_requires::tests::get_expression_kind_get_service",
"sort_requires::tests::get_expression_kind_other_2",
"sort_requires::tests::get_expression_kind_other_4",
"sort_requires::tests::get_expression_kind_other_6",
"sort_requires::tests::get_expression_kind_other_3",
"sort_requires::tests::get_expression_kind_other_5",
"sort_requires::tests::get_expression_kind_require_stmt",
"sort_requires::tests::get_expression_kind_require_type_assertion",
"tests::test_invalid_input",
"verify_ast::tests::test_different_asts",
"verify_ast::tests::test_different_hex_numbers",
"verify_ast::tests::test_equivalent_conditions",
"verify_ast::tests::test_different_binary_numbers",
"tests::test_entry_point",
"verify_ast::tests::test_equivalent_asts",
"verify_ast::tests::test_equivalent_hex_numbers",
"verify_ast::tests::test_equivalent_binary_numbers",
"verify_ast::tests::test_equivalent_function_calls",
"verify_ast::tests::test_equivalent_hex_numbers_very_large_number",
"verify_ast::tests::test_equivalent_function_calls_2",
"tests::test_with_ast_verification",
"verify_ast::tests::test_equivalent_hex_numbers_with_separators",
"verify_ast::tests::test_equivalent_numbers",
"verify_ast::tests::test_equivalent_string_quote_types",
"verify_ast::tests::test_equivalent_luajit_numbers",
"verify_ast::tests::test_equivalent_string_escapes",
"verify_ast::tests::test_equivalent_numbers_2",
"verify_ast::tests::test_equivalent_stmt_semicolons",
"verify_ast::tests::test_equivalent_types_removed_parentheses",
"verify_ast::tests::test_equivalent_table_separators",
"output_diff::tests::test_deletion_diff",
"output_diff::tests::test_addition_diff",
"output_diff::tests::test_no_diff",
"output_diff::tests::test_change_diff",
"config::tests::test_override_indent_width",
"config::tests::test_override_quote_style",
"opt::tests::verify_opt",
"config::tests::test_override_indent_type",
"config::tests::test_override_syntax",
"config::tests::test_override_line_endings",
"config::tests::test_override_call_parentheses",
"config::tests::test_override_column_width",
"tests::test_no_files_provided",
"tests::test_format_stdin",
"tests::explicitly_provided_files_dont_check_ignores_stdin",
"tests::explicitly_provided_files_dont_check_ignores",
"tests::test_configuration_is_not_used_outside_of_cwd",
"tests::test_configuration_is_searched_next_to_file",
"tests::test_stdin_filepath_respects_cwd_configuration_for_nested_file",
"tests::test_respect_ignores",
"tests::test_respect_config_path_override_for_stdin_filepath",
"tests::test_respect_ignores_stdin",
"tests::test_respect_ignores_directory_no_glob",
"tests::test_uses_cli_overrides_instead_of_default_configuration_stdin_filepath",
"tests::test_stdin_filepath_respects_cwd_configuration_next_to_file",
"tests::test_uses_cli_overrides_instead_of_found_configuration_stdin_filepath",
"tests::test_format_file",
"tests::test_cwd_configuration_respected_for_nested_file",
"tests::test_configuration_used_outside_of_cwd_when_search_parent_directories_is_enabled",
"tests::test_respect_config_path_override",
"tests::test_configuration_is_used_closest_to_the_file",
"tests::test_cwd_configuration_respected_for_file_in_cwd",
"tests::test_uses_cli_overrides_instead_of_found_configuration",
"tests::test_uses_cli_overrides_instead_of_default_configuration",
"tests::test_stylua_ignore",
"test_call_parens_comments",
"test_call_parens_semicolons",
"test_call_parens_none_handles_string_correctly",
"test_call_parens_no_single_table_handles_table_correctly",
"test_call_parens_always_handles_string_correctly",
"test_call_parens_no_single_table_handles_string_correctly",
"test_call_parens_no_single_string_handles_table_correctly",
"test_call_parens_no_single_string_handles_string_correctly",
"test_call_parens_always_handles_table_correctly",
"test_call_parens_none_handles_table_correctly",
"test_call_parens_input",
"test_call_parens_has_no_affect_on_multi_arg_fn_calls_",
"test_local",
"test_root",
"test_empty_root",
"test_global",
"test_stylua_toml",
"test_omit_parens_brackets_string",
"test_no_parens_brackets_string",
"test_no_parens_multiline_table",
"test_no_parens_singleline_table",
"test_no_parens_string",
"test_omit_parens_string",
"test_no_parens_method_chain_1",
"test_keep_parens_binop_string",
"test_no_parens_method_chain_2",
"test_no_parens_large_example",
"test_force_double_quotes",
"test_force_single_quotes",
"test_auto_prefer_single_quotes",
"test_auto_prefer_double_quotes",
"test_incomplete_range",
"test_dont_modify_eof",
"test_default",
"test_ignore_last_stmt",
"test_nested_range_binop",
"test_nested_range_else_if",
"test_nested_range_do",
"test_nested_range_function_call_table",
"test_nested_range_generic_for",
"test_nested_range_function_call",
"test_nested_range",
"test_large_example",
"test_no_range_end",
"test_nested_range_while",
"test_nested_range_repeat",
"test_no_range_start",
"test_nested_range_table_1",
"test_nested_range_table_2",
"test_nested_range_local_function",
"test_space_after_function_definitions",
"test_never_space_after_function_names",
"test_space_after_function_calls",
"test_always_space_after_function_names",
"test_crlf_in_multiline_strings",
"test_crlf_in_multiline_comments",
"test_collapse_single_statement_lua_52",
"test_lua54",
"test_lua53",
"test_lua52",
"test_ignores",
"test_sort_requires",
"test_full_moon_test_suite",
"test_luau_full_moon",
"test_collapse_single_statement",
"test_luau",
"test_standard"
] |
[] |
[] |
JohnnyMorganz/StyLua
| 926
|
JohnnyMorganz__StyLua-926
|
[
"925"
] |
08e536f3a02d9a07b0991726897e0013ff78dd21
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- Fixed CLI overrides not applying on top of a resolved `stylua.toml` file ([#925](https://github.com/JohnnyMorganz/StyLua/issues/925))
+
## [2.0.0] - 2024-11-17
### Breaking Changes
diff --git a/src/cli/config.rs b/src/cli/config.rs
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -113,7 +113,9 @@ impl ConfigResolver<'_> {
match config_file {
Some(file_path) => {
debug!("config: found config at {}", file_path.display());
- read_config_file(&file_path).map(Some)
+ let config = read_and_apply_overrides(&file_path, self.opt)?;
+ debug!("config: {:#?}", config);
+ Ok(Some(config))
}
None => Ok(None),
}
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -271,9 +271,6 @@ fn format(opt: opt::Opt) -> Result<i32> {
let opt_for_config_resolver = opt.clone();
let mut config_resolver = config::ConfigResolver::new(&opt_for_config_resolver)?;
- // TODO:
- // debug!("config: {:#?}", config);
-
// Create range if provided
let range = if opt.range_start.is_some() || opt.range_end.is_some() {
Some(Range::from_values(opt.range_start, opt.range_end))
|
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -953,4 +950,74 @@ mod tests {
cwd.close().unwrap();
}
+
+ #[test]
+ fn test_uses_cli_overrides_instead_of_default_configuration() {
+ let cwd = construct_tree!({
+ "foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .args(["--quote-style", "AutoPreferSingle", "."])
+ .assert()
+ .success();
+
+ cwd.child("foo.lua").assert("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
+
+ #[test]
+ fn test_uses_cli_overrides_instead_of_default_configuration_stdin_filepath() {
+ let cwd = construct_tree!({
+ "foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .args(["--quote-style", "AutoPreferSingle", "-"])
+ .write_stdin("local x = \"hello\"")
+ .assert()
+ .success()
+ .stdout("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
+
+ #[test]
+ fn test_uses_cli_overrides_instead_of_found_configuration() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferDouble'",
+ "foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .args(["--quote-style", "AutoPreferSingle", "."])
+ .assert()
+ .success();
+
+ cwd.child("foo.lua").assert("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
+
+ #[test]
+ fn test_uses_cli_overrides_instead_of_found_configuration_stdin_filepath() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferDouble'",
+ "foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .args(["--quote-style", "AutoPreferSingle", "-"])
+ .write_stdin("local x = \"hello\"")
+ .assert()
+ .success()
+ .stdout("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
}
|
CLI overrides not applied when formatting files in v2.0.0
I tried to run it both from Windows and from Docker for Windows
`stylua.exe --line-endings Windows --check .`
`stylua.exe --line-endings Unix --check .`
The result is the same, it gives errors in all files. Example of the first two files
```
Diff in ./cloud_test_tasks/runTests.luau:
1 |-require(game.ReplicatedStorage.Shared.LuTestRoblox.LuTestRunner)
1 |+require(game.ReplicatedStorage.Shared.LuTestRoblox.LuTestRunner)
Diff in ./place_battle/replicated_storage/tests/test_workspace.luau:
1 |-local tests = {}
2 |-local Workspace = game:GetService("Workspace")
3 |-
4 |-function tests.test_server_workspace_gravity()
5 |- assert(math.floor(Workspace.Gravity) == 196, "Gravity value is: " .. Workspace.Gravity)
6 |-end
7 |-
8 |-return tests
1 |+local tests = {}
2 |+local Workspace = game:GetService("Workspace")
3 |+
4 |+function tests.test_server_workspace_gravity()
5 |+ assert(math.floor(Workspace.Gravity) == 196, "Gravity value is: " .. Workspace.Gravity)
6 |+end
7 |+
8 |+return tests
Diff in ./place_battle/replicated_storage/tests/test_starterplayer.luau:
```
After reverting to 0.20.0 the results became normal again
|
Hm, this does look like line endings changing for some reason. Which is weird, since I don't think we touched that at all.
Do you by any chance have an example file I can test this with? Either in a public repo, or attaching a code file here (not in a code block since we need to preserve the line endings)
Yes, sure
[runTests.zip](https://github.com/user-attachments/files/17792304/runTests.zip)
|
2024-11-18T05:01:53Z
|
2.0
|
2024-11-17T21:06:05Z
|
f581279895a7040a36abaea4a6c8a6f50f112cd7
|
[
"tests::test_uses_cli_overrides_instead_of_found_configuration"
] |
[
"editorconfig::tests::test_call_parentheses_no_single_string",
"editorconfig::tests::test_call_parentheses_no_single_table",
"editorconfig::tests::test_call_parentheses_always",
"editorconfig::tests::test_call_parentheses_none",
"editorconfig::tests::test_collapse_simple_statement_always",
"editorconfig::tests::test_collapse_simple_statement_conditional_only",
"editorconfig::tests::test_collapse_simple_statement_function_only",
"editorconfig::tests::test_collapse_simple_statement_never",
"editorconfig::tests::test_end_of_line_cr",
"editorconfig::tests::test_end_of_line_crlf",
"editorconfig::tests::test_end_of_line_lf",
"editorconfig::tests::test_indent_size_use_tab_width",
"editorconfig::tests::test_indent_size",
"editorconfig::tests::test_indent_style_space",
"editorconfig::tests::test_indent_style_tab",
"editorconfig::tests::test_invalid_properties",
"editorconfig::tests::test_max_line_length",
"editorconfig::tests::test_max_line_length_off",
"editorconfig::tests::test_quote_type_auto",
"editorconfig::tests::test_quote_type_double",
"editorconfig::tests::test_quote_type_single",
"editorconfig::tests::test_sort_requires_disabled",
"editorconfig::tests::test_sort_requires_enabled",
"editorconfig::tests::test_space_after_function_names_always",
"editorconfig::tests::test_space_after_function_names_calls",
"editorconfig::tests::test_space_after_function_names_definitions",
"editorconfig::tests::test_space_after_function_names_never",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments_2",
"formatters::trivia_util::tests::test_token_contains_singleline_comments",
"sort_requires::tests::fail_extracting_non_identifier_token",
"sort_requires::tests::get_expression_kind_other_1",
"sort_requires::tests::get_expression_kind_other_2",
"sort_requires::tests::get_expression_kind_get_service",
"sort_requires::tests::get_expression_kind_other_4",
"sort_requires::tests::get_expression_kind_other_5",
"sort_requires::tests::get_expression_kind_require_stmt",
"sort_requires::tests::get_expression_kind_other_3",
"sort_requires::tests::get_expression_kind_require_type_assertion",
"tests::test_invalid_input",
"sort_requires::tests::get_expression_kind_other_6",
"verify_ast::tests::test_different_binary_numbers",
"verify_ast::tests::test_different_asts",
"verify_ast::tests::test_different_hex_numbers",
"verify_ast::tests::test_equivalent_conditions",
"verify_ast::tests::test_equivalent_binary_numbers",
"tests::test_entry_point",
"verify_ast::tests::test_equivalent_asts",
"tests::test_with_ast_verification",
"verify_ast::tests::test_equivalent_hex_numbers",
"verify_ast::tests::test_equivalent_hex_numbers_very_large_number",
"verify_ast::tests::test_equivalent_function_calls",
"verify_ast::tests::test_equivalent_function_calls_2",
"verify_ast::tests::test_equivalent_hex_numbers_with_separators",
"verify_ast::tests::test_equivalent_numbers_2",
"verify_ast::tests::test_equivalent_types_removed_parentheses",
"verify_ast::tests::test_equivalent_stmt_semicolons",
"verify_ast::tests::test_equivalent_string_escapes",
"verify_ast::tests::test_equivalent_string_quote_types",
"verify_ast::tests::test_equivalent_numbers",
"verify_ast::tests::test_equivalent_luajit_numbers",
"verify_ast::tests::test_equivalent_table_separators",
"output_diff::tests::test_no_diff",
"output_diff::tests::test_addition_diff",
"output_diff::tests::test_deletion_diff",
"output_diff::tests::test_change_diff",
"opt::tests::verify_opt",
"config::tests::test_override_syntax",
"config::tests::test_override_call_parentheses",
"config::tests::test_override_line_endings",
"config::tests::test_override_column_width",
"config::tests::test_override_quote_style",
"config::tests::test_override_indent_width",
"config::tests::test_override_indent_type",
"tests::test_no_files_provided",
"tests::explicitly_provided_files_dont_check_ignores_stdin",
"tests::test_format_stdin",
"tests::test_respect_config_path_override_for_stdin_filepath",
"tests::test_respect_ignores",
"tests::test_respect_ignores_directory_no_glob",
"tests::test_stdin_filepath_respects_cwd_configuration_for_nested_file",
"tests::test_respect_ignores_stdin",
"tests::test_stdin_filepath_respects_cwd_configuration_next_to_file",
"tests::test_uses_cli_overrides_instead_of_default_configuration_stdin_filepath",
"tests::test_cwd_configuration_respected_for_nested_file",
"tests::test_configuration_is_searched_next_to_file",
"tests::test_respect_config_path_override",
"tests::test_format_file",
"tests::explicitly_provided_files_dont_check_ignores",
"tests::test_uses_cli_overrides_instead_of_found_configuration_stdin_filepath",
"tests::test_uses_cli_overrides_instead_of_default_configuration",
"tests::test_configuration_is_not_used_outside_of_cwd",
"tests::test_configuration_is_used_closest_to_the_file",
"tests::test_configuration_used_outside_of_cwd_when_search_parent_directories_is_enabled",
"tests::test_stylua_ignore",
"tests::test_cwd_configuration_respected_for_file_in_cwd",
"test_call_parens_comments",
"test_call_parens_semicolons",
"test_call_parens_none_handles_table_correctly",
"test_call_parens_no_single_table_handles_table_correctly",
"test_call_parens_always_handles_table_correctly",
"test_call_parens_no_single_string_handles_table_correctly",
"test_call_parens_always_handles_string_correctly",
"test_call_parens_no_single_table_handles_string_correctly",
"test_call_parens_no_single_string_handles_string_correctly",
"test_call_parens_input",
"test_call_parens_none_handles_string_correctly",
"test_call_parens_has_no_affect_on_multi_arg_fn_calls_",
"test_empty_root",
"test_global",
"test_root",
"test_local",
"test_stylua_toml",
"test_no_parens_brackets_string",
"test_omit_parens_brackets_string",
"test_no_parens_method_chain_1",
"test_no_parens_singleline_table",
"test_no_parens_string",
"test_omit_parens_string",
"test_keep_parens_binop_string",
"test_no_parens_method_chain_2",
"test_no_parens_large_example",
"test_no_parens_multiline_table",
"test_force_single_quotes",
"test_auto_prefer_single_quotes",
"test_auto_prefer_double_quotes",
"test_force_double_quotes",
"test_default",
"test_ignore_last_stmt",
"test_dont_modify_eof",
"test_nested_range_do",
"test_incomplete_range",
"test_nested_range_function_call",
"test_nested_range_generic_for",
"test_nested_range_else_if",
"test_nested_range_binop",
"test_nested_range_function_call_table",
"test_nested_range",
"test_large_example",
"test_no_range_end",
"test_nested_range_while",
"test_nested_range_repeat",
"test_no_range_start",
"test_nested_range_table_1",
"test_nested_range_table_2",
"test_nested_range_local_function",
"test_space_after_function_calls",
"test_space_after_function_definitions",
"test_never_space_after_function_names",
"test_always_space_after_function_names",
"test_crlf_in_multiline_strings",
"test_crlf_in_multiline_comments",
"test_collapse_single_statement_lua_52",
"test_lua54",
"test_lua53",
"test_lua52",
"test_ignores",
"test_sort_requires",
"test_full_moon_test_suite",
"test_collapse_single_statement",
"test_luau_full_moon",
"test_luau",
"test_standard"
] |
[] |
[] |
JohnnyMorganz/StyLua
| 916
|
JohnnyMorganz__StyLua-916
|
[
"831",
"915"
] |
d7d532b4baf2bcf2adf1925d7248f659788e5b58
|
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -229,7 +229,8 @@ StyLua has opinionated defaults, but also provides a few options that can be set
### Finding the configuration
-The CLI looks for `stylua.toml` or `.stylua.toml` in the directory where the tool was executed.
+The CLI looks for a `stylua.toml` or `.stylua.toml` starting from the directory of the file being formatted.
+It will keep searching upwards until it reaches the current directory where the tool was executed.
If not found, we search for an `.editorconfig` file, otherwise fall back to the default configuration.
This feature can be disabled using `--no-editorconfig`.
See [EditorConfig](https://editorconfig.org/) for more details.
diff --git a/src/cli/config.rs b/src/cli/config.rs
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -1,12 +1,16 @@
use crate::opt::Opt;
use anyhow::{Context, Result};
use log::*;
+use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use stylua_lib::Config;
use stylua_lib::SortRequiresConfig;
+#[cfg(feature = "editorconfig")]
+use stylua_lib::editorconfig;
+
static CONFIG_FILE_NAME: [&str; 2] = ["stylua.toml", ".stylua.toml"];
fn read_config_file(path: &Path) -> Result<Config> {
diff --git a/src/cli/config.rs b/src/cli/config.rs
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -16,144 +20,217 @@ fn read_config_file(path: &Path) -> Result<Config> {
Ok(config)
}
-/// Searches the directory for the configuration toml file (i.e. `stylua.toml` or `.stylua.toml`)
-fn find_toml_file(directory: &Path) -> Option<PathBuf> {
- for name in &CONFIG_FILE_NAME {
- let file_path = directory.join(name);
- if file_path.exists() {
- return Some(file_path);
- }
- }
+fn read_and_apply_overrides(path: &Path, opt: &Opt) -> Result<Config> {
+ read_config_file(path).map(|config| load_overrides(config, opt))
+}
- None
+pub struct ConfigResolver<'a> {
+ config_cache: HashMap<PathBuf, Option<Config>>,
+ forced_configuration: Option<Config>,
+ current_directory: PathBuf,
+ default_configuration: Config,
+ opt: &'a Opt,
}
-/// Looks for a configuration file in the directory provided (and its parent's recursively, if specified)
-fn find_config_file(mut directory: PathBuf, recursive: bool) -> Result<Option<Config>> {
- debug!("config: looking for config in {}", directory.display());
- let config_file = find_toml_file(&directory);
- match config_file {
- Some(file_path) => {
- debug!("config: found config at {}", file_path.display());
- read_config_file(&file_path).map(Some)
+impl ConfigResolver<'_> {
+ pub fn new(opt: &Opt) -> Result<ConfigResolver> {
+ let forced_configuration = opt
+ .config_path
+ .as_ref()
+ .map(|config_path| {
+ debug!(
+ "config: explicit config path provided at {}",
+ config_path.display()
+ );
+ read_and_apply_overrides(config_path, opt)
+ })
+ .transpose()?;
+
+ Ok(ConfigResolver {
+ config_cache: HashMap::new(),
+ forced_configuration,
+ current_directory: env::current_dir().context("Could not find current directory")?,
+ default_configuration: load_overrides(Config::default(), opt),
+ opt,
+ })
+ }
+
+ pub fn load_configuration(&mut self, path: &Path) -> Result<Config> {
+ if let Some(configuration) = self.forced_configuration {
+ return Ok(configuration);
}
- None => {
- // Both don't exist, search up the tree if necessary
- // directory.pop() mutates the path to get its parent, and returns false if no more parent
- if recursive && directory.pop() {
- find_config_file(directory, recursive)
- } else {
- Ok(None)
+
+ let root = match self.opt.search_parent_directories {
+ true => None,
+ false => Some(self.current_directory.to_path_buf()),
+ };
+
+ let absolute_path = self.current_directory.join(path);
+ let parent_path = &absolute_path
+ .parent()
+ .with_context(|| format!("no parent directory found for {}", path.display()))?;
+
+ match self.find_config_file(parent_path, root)? {
+ Some(config) => Ok(config),
+ None => {
+ #[cfg(feature = "editorconfig")]
+ if self.opt.no_editorconfig {
+ Ok(self.default_configuration)
+ } else {
+ editorconfig::parse(self.default_configuration, path)
+ .context("could not parse editorconfig")
+ }
+ #[cfg(not(feature = "editorconfig"))]
+ Ok(self.default_configuration)
}
}
}
-}
-pub fn find_ignore_file_path(mut directory: PathBuf, recursive: bool) -> Option<PathBuf> {
- debug!("config: looking for ignore file in {}", directory.display());
- let file_path = directory.join(".styluaignore");
- if file_path.is_file() {
- Some(file_path)
- } else if recursive && directory.pop() {
- find_ignore_file_path(directory, recursive)
- } else {
- None
- }
-}
+ pub fn load_configuration_for_stdin(&mut self) -> Result<Config> {
+ if let Some(configuration) = self.forced_configuration {
+ return Ok(configuration);
+ }
-/// Looks for a configuration file at either `$XDG_CONFIG_HOME`, `$XDG_CONFIG_HOME/stylua`, `$HOME/.config` or `$HOME/.config/stylua`
-fn search_config_locations() -> Result<Option<Config>> {
- // Look in `$XDG_CONFIG_HOME`
- if let Ok(xdg_config) = std::env::var("XDG_CONFIG_HOME") {
- let xdg_config_path = Path::new(&xdg_config);
- if xdg_config_path.exists() {
- debug!("config: looking in $XDG_CONFIG_HOME");
+ match &self.opt.stdin_filepath {
+ Some(filepath) => self.load_configuration(filepath),
+ None => {
+ #[cfg(feature = "editorconfig")]
+ if self.opt.no_editorconfig {
+ Ok(self.default_configuration)
+ } else {
+ editorconfig::parse(self.default_configuration, &PathBuf::from("*.lua"))
+ .context("could not parse editorconfig")
+ }
+ #[cfg(not(feature = "editorconfig"))]
+ Ok(self.default_configuration)
+ }
+ }
+ }
- if let Some(config) = find_config_file(xdg_config_path.to_path_buf(), false)? {
- return Ok(Some(config));
+ fn lookup_config_file_in_directory(&self, directory: &Path) -> Result<Option<Config>> {
+ debug!("config: looking for config in {}", directory.display());
+ let config_file = find_toml_file(directory);
+ match config_file {
+ Some(file_path) => {
+ debug!("config: found config at {}", file_path.display());
+ read_config_file(&file_path).map(Some)
}
+ None => Ok(None),
+ }
+ }
- debug!("config: looking in $XDG_CONFIG_HOME/stylua");
- let xdg_config_path = xdg_config_path.join("stylua");
- if xdg_config_path.exists() {
- if let Some(config) = find_config_file(xdg_config_path, false)? {
- return Ok(Some(config));
+ /// Looks for a configuration file in the directory provided
+ /// Keep searching recursively upwards until we hit the root (if provided), then stop
+ /// When `--search-parent-directories` is enabled, root = None, else root = Some(cwd)
+ fn find_config_file(
+ &mut self,
+ directory: &Path,
+ root: Option<PathBuf>,
+ ) -> Result<Option<Config>> {
+ if let Some(config) = self.config_cache.get(directory) {
+ return Ok(*config);
+ }
+
+ let resolved_configuration = match self.lookup_config_file_in_directory(directory)? {
+ Some(config) => Some(config),
+ None => {
+ let parent_directory = directory.parent();
+ let should_stop = Some(directory) == root.as_deref() || parent_directory.is_none();
+
+ if should_stop {
+ debug!("config: no configuration file found");
+ if self.opt.search_parent_directories {
+ if let Some(config) = self.search_config_locations()? {
+ return Ok(Some(config));
+ }
+ }
+
+ debug!("config: falling back to default config");
+ None
+ } else {
+ self.find_config_file(parent_directory.unwrap(), root)?
}
}
- }
+ };
+
+ self.config_cache
+ .insert(directory.to_path_buf(), resolved_configuration);
+ Ok(resolved_configuration)
}
- // Look in `$HOME/.config`
- if let Ok(home) = std::env::var("HOME") {
- let home_config_path = Path::new(&home).join(".config");
+ /// Looks for a configuration file at either `$XDG_CONFIG_HOME`, `$XDG_CONFIG_HOME/stylua`, `$HOME/.config` or `$HOME/.config/stylua`
+ fn search_config_locations(&self) -> Result<Option<Config>> {
+ // Look in `$XDG_CONFIG_HOME`
+ if let Ok(xdg_config) = std::env::var("XDG_CONFIG_HOME") {
+ let xdg_config_path = Path::new(&xdg_config);
+ if xdg_config_path.exists() {
+ debug!("config: looking in $XDG_CONFIG_HOME");
- if home_config_path.exists() {
- debug!("config: looking in $HOME/.config");
+ if let Some(config) = self.lookup_config_file_in_directory(xdg_config_path)? {
+ return Ok(Some(config));
+ }
- if let Some(config) = find_config_file(home_config_path.to_owned(), false)? {
- return Ok(Some(config));
+ debug!("config: looking in $XDG_CONFIG_HOME/stylua");
+ let xdg_config_path = xdg_config_path.join("stylua");
+ if xdg_config_path.exists() {
+ if let Some(config) = self.lookup_config_file_in_directory(&xdg_config_path)? {
+ return Ok(Some(config));
+ }
+ }
}
+ }
+
+ // Look in `$HOME/.config`
+ if let Ok(home) = std::env::var("HOME") {
+ let home_config_path = Path::new(&home).join(".config");
- debug!("config: looking in $HOME/.config/stylua");
- let home_config_path = home_config_path.join("stylua");
if home_config_path.exists() {
- if let Some(config) = find_config_file(home_config_path, false)? {
+ debug!("config: looking in $HOME/.config");
+
+ if let Some(config) = self.lookup_config_file_in_directory(&home_config_path)? {
return Ok(Some(config));
}
+
+ debug!("config: looking in $HOME/.config/stylua");
+ let home_config_path = home_config_path.join("stylua");
+ if home_config_path.exists() {
+ if let Some(config) = self.lookup_config_file_in_directory(&home_config_path)? {
+ return Ok(Some(config));
+ }
+ }
}
}
- }
- Ok(None)
+ Ok(None)
+ }
}
-pub fn load_config(opt: &Opt) -> Result<Option<Config>> {
- match &opt.config_path {
- Some(config_path) => {
- debug!(
- "config: explicit config path provided at {}",
- config_path.display()
- );
- read_config_file(config_path).map(Some)
+/// Searches the directory for the configuration toml file (i.e. `stylua.toml` or `.stylua.toml`)
+fn find_toml_file(directory: &Path) -> Option<PathBuf> {
+ for name in &CONFIG_FILE_NAME {
+ let file_path = directory.join(name);
+ if file_path.exists() {
+ return Some(file_path);
}
- None => {
- let current_dir = match &opt.stdin_filepath {
- Some(file_path) => file_path
- .parent()
- .context("Could not find current directory from provided stdin filepath")?
- .to_path_buf(),
- None => env::current_dir().context("Could not find current directory")?,
- };
-
- debug!(
- "config: starting config search from {} - recursively searching parents: {}",
- current_dir.display(),
- opt.search_parent_directories
- );
- let config = find_config_file(current_dir, opt.search_parent_directories)?;
- match config {
- Some(config) => Ok(Some(config)),
- None => {
- debug!("config: no configuration file found");
+ }
- // Search the configuration directory for a file, if necessary
- if opt.search_parent_directories {
- if let Some(config) = search_config_locations()? {
- return Ok(Some(config));
- }
- }
+ None
+}
- // Fallback to a default configuration
- debug!("config: falling back to default config");
- Ok(None)
- }
- }
- }
+pub fn find_ignore_file_path(mut directory: PathBuf, recursive: bool) -> Option<PathBuf> {
+ debug!("config: looking for ignore file in {}", directory.display());
+ let file_path = directory.join(".styluaignore");
+ if file_path.is_file() {
+ Some(file_path)
+ } else if recursive && directory.pop() {
+ find_ignore_file_path(directory, recursive)
+ } else {
+ None
}
}
/// Handles any overrides provided by command line options
-pub fn load_overrides(config: Config, opt: &Opt) -> Config {
+fn load_overrides(config: Config, opt: &Opt) -> Config {
let mut new_config = config;
if let Some(syntax) = opt.format_opts.syntax {
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -8,16 +8,12 @@ use std::collections::HashSet;
use std::fs;
use std::io::{stderr, stdin, stdout, Read, Write};
use std::path::Path;
-#[cfg(feature = "editorconfig")]
-use std::path::PathBuf;
use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
use std::sync::Arc;
use std::time::Instant;
use thiserror::Error;
use threadpool::ThreadPool;
-#[cfg(feature = "editorconfig")]
-use stylua_lib::editorconfig;
use stylua_lib::{format_code, Config, OutputVerification, Range};
use crate::config::find_ignore_file_path;
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -272,14 +268,11 @@ fn format(opt: opt::Opt) -> Result<i32> {
}
// Load the configuration
- let loaded = config::load_config(&opt)?;
- #[cfg(feature = "editorconfig")]
- let is_default_config = loaded.is_none();
- let config = loaded.unwrap_or_default();
+ let opt_for_config_resolver = opt.clone();
+ let mut config_resolver = config::ConfigResolver::new(&opt_for_config_resolver)?;
- // Handle any configuration overrides provided by options
- let config = config::load_overrides(config, &opt);
- debug!("config: {:#?}", config);
+ // TODO:
+ // debug!("config: {:#?}", config);
// Create range if provided
let range = if opt.range_start.is_some() || opt.range_end.is_some() {
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -425,40 +418,24 @@ fn format(opt: opt::Opt) -> Result<i32> {
None => false,
};
- pool.execute(move || {
- #[cfg(not(feature = "editorconfig"))]
- let used_config = Ok(config);
- #[cfg(feature = "editorconfig")]
- let used_config = match is_default_config && !&opt.no_editorconfig {
- true => {
- let path = match &opt.stdin_filepath {
- Some(filepath) => filepath.to_path_buf(),
- None => PathBuf::from("*.lua"),
- };
- editorconfig::parse(config, &path)
- .context("could not parse editorconfig")
- }
- false => Ok(config),
- };
+ let config = config_resolver.load_configuration_for_stdin()?;
+ pool.execute(move || {
let mut buf = String::new();
tx.send(
- used_config
- .and_then(|used_config| {
- stdin()
- .read_to_string(&mut buf)
- .map_err(|err| err.into())
- .and_then(|_| {
- format_string(
- buf,
- used_config,
- range,
- &opt,
- verify_output,
- should_skip_format,
- )
- .context("could not format from stdin")
- })
+ stdin()
+ .read_to_string(&mut buf)
+ .map_err(|err| err.into())
+ .and_then(|_| {
+ format_string(
+ buf,
+ config,
+ range,
+ &opt,
+ verify_output,
+ should_skip_format,
+ )
+ .context("could not format from stdin")
})
.map_err(|error| {
ErrorFileWrapper {
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -506,29 +483,20 @@ fn format(opt: opt::Opt) -> Result<i32> {
continue;
}
+ let config = config_resolver.load_configuration(&path)?;
+
let tx = tx.clone();
pool.execute(move || {
- #[cfg(not(feature = "editorconfig"))]
- let used_config = Ok(config);
- #[cfg(feature = "editorconfig")]
- let used_config = match is_default_config && !&opt.no_editorconfig {
- true => editorconfig::parse(config, &path)
- .context("could not parse editorconfig"),
- false => Ok(config),
- };
-
tx.send(
- used_config
- .and_then(|used_config| {
- format_file(&path, used_config, range, &opt, verify_output)
- })
- .map_err(|error| {
+ format_file(&path, config, range, &opt, verify_output).map_err(
+ |error| {
ErrorFileWrapper {
file: path.display().to_string(),
error,
}
.into()
- }),
+ },
+ ),
)
.unwrap()
});
diff --git a/src/cli/opt.rs b/src/cli/opt.rs
--- a/src/cli/opt.rs
+++ b/src/cli/opt.rs
@@ -9,7 +9,7 @@ lazy_static::lazy_static! {
static ref NUM_CPUS: String = num_cpus::get().to_string();
}
-#[derive(StructOpt, Debug)]
+#[derive(StructOpt, Clone, Debug)]
#[structopt(name = "stylua", about = "A utility to format Lua code", version)]
pub struct Opt {
/// Specify path to stylua.toml configuration file.
diff --git a/src/cli/opt.rs b/src/cli/opt.rs
--- a/src/cli/opt.rs
+++ b/src/cli/opt.rs
@@ -160,7 +160,7 @@ pub enum OutputFormat {
Summary,
}
-#[derive(StructOpt, Debug)]
+#[derive(StructOpt, Clone, Copy, Debug)]
pub struct FormatOpts {
/// The type of Lua syntax to parse
#[structopt(long, arg_enum, ignore_case = true)]
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Update internal Lua parser version (full-moon) to v1.1.0. This includes parser performance improvements. ([#854](https://github.com/JohnnyMorganz/StyLua/issues/854))
- LuaJIT is now separated from Lua52, and is available in its own feature and syntax flag
+- `.stylua.toml` config resolution now supports looking up config files next to files being formatted, recursively going
+ upwards until reaching the current working directory, then stopping (unless `--search-parent-directories` was specified).
+ For example, for a file `./src/test.lua`, executing `stylua src/` will look for `./src/stylua.toml` and then `./stylua.toml`.
### Fixed
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -808,4 +776,181 @@ mod tests {
cwd.close().unwrap();
}
+
+ #[test]
+ fn test_stdin_filepath_respects_cwd_configuration_next_to_file() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferSingle'",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .args(["--stdin-filepath", "foo.lua", "-"])
+ .write_stdin("local x = \"hello\"")
+ .assert()
+ .success()
+ .stdout("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
+
+ #[test]
+ fn test_stdin_filepath_respects_cwd_configuration_for_nested_file() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferSingle'",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .args(["--stdin-filepath", "build/foo.lua", "-"])
+ .write_stdin("local x = \"hello\"")
+ .assert()
+ .success()
+ .stdout("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
+
+ #[test]
+ fn test_cwd_configuration_respected_for_file_in_cwd() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferSingle'",
+ "foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .arg("foo.lua")
+ .assert()
+ .success();
+
+ cwd.child("foo.lua").assert("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
+
+ #[test]
+ fn test_cwd_configuration_respected_for_nested_file() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferSingle'",
+ "build/foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .arg("build/foo.lua")
+ .assert()
+ .success();
+
+ cwd.child("build/foo.lua").assert("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
+
+ #[test]
+ fn test_configuration_is_not_used_outside_of_cwd() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferSingle'",
+ "build/foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.child("build").path())
+ .arg("foo.lua")
+ .assert()
+ .success();
+
+ cwd.child("build/foo.lua").assert("local x = \"hello\"\n");
+
+ cwd.close().unwrap();
+ }
+
+ #[test]
+ fn test_configuration_used_outside_of_cwd_when_search_parent_directories_is_enabled() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferSingle'",
+ "build/foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.child("build").path())
+ .args(["--search-parent-directories", "foo.lua"])
+ .assert()
+ .success();
+
+ cwd.child("build/foo.lua").assert("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
+
+ #[test]
+ fn test_configuration_is_searched_next_to_file() {
+ let cwd = construct_tree!({
+ "build/stylua.toml": "quote_style = 'AutoPreferSingle'",
+ "build/foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .arg("build/foo.lua")
+ .assert()
+ .success();
+
+ cwd.child("build/foo.lua").assert("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
+
+ #[test]
+ fn test_configuration_is_used_closest_to_the_file() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferDouble'",
+ "build/stylua.toml": "quote_style = 'AutoPreferSingle'",
+ "build/foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .arg("build/foo.lua")
+ .assert()
+ .success();
+
+ cwd.child("build/foo.lua").assert("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
+
+ #[test]
+ fn test_respect_config_path_override() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferDouble'",
+ "build/stylua.toml": "quote_style = 'AutoPreferSingle'",
+ "foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .args(["--config-path", "build/stylua.toml", "foo.lua"])
+ .assert()
+ .success();
+ }
+
+ #[test]
+ fn test_respect_config_path_override_for_stdin_filepath() {
+ let cwd = construct_tree!({
+ "stylua.toml": "quote_style = 'AutoPreferDouble'",
+ "build/stylua.toml": "quote_style = 'AutoPreferSingle'",
+ "foo.lua": "local x = \"hello\"",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .args(["--config-path", "build/stylua.toml", "-"])
+ .write_stdin("local x = \"hello\"")
+ .assert()
+ .success()
+ .stdout("local x = 'hello'\n");
+
+ cwd.close().unwrap();
+ }
}
|
feat: Use closest `stylua.toml` config to file being formatted
It would be nice if the formatter can be configured to stop looking for config files when reached a Git root (e.g. `git rev-parse --show-toplevel`) this will be useful such that when inside a lua repo and inside submodule, we stop at first `.stylelua` file, somehow it does not stop and merges? with the config file in the main repo, which contains the submodule...
VSCode Extension ignoring stylua.toml
Began coding this morning and upon formatting my files, had all my spaces turn into tabs. Saw the VSCode extension got updated to 1.7.0 last night.
Reverting back to 1.6.3 resolves the issue and formatting resumes back to the settings in my `stylua.toml`
|
> we stop at first .stylelua file, somehow it does not stop and merges
this sounds incorrect to me, we don't merge two stylua files together. That sounds like the underlying issue here, rather than adding something else to stop at git roots.
Ah maybe you start the discovery of the style file from the current working directory, which IMO is wrong. Could that be the issue here?
Ah yes, that seems more like it. Indeed, we just use the config found at the cwd across all the code.
I have been thinking about this though - maybe we should be using the closest configuration to the file.
I do question why you are running stylua on a sub module though. I typically think sub modules are vendored code, hence should be ignored by style tools, but maybe that is not the case for you.
Von meinem iPhone gesendetAm 23.12.2023 um 18:32 schrieb JohnnyMorganz ***@***.***>:
Ah yes, that seems more like it. Indeed, we just use the config found at the cwd across all the code.
I have been thinking about this though - maybe we should be using the closest configuration to the file.
I do question why you are running stylua on a sub module though. I typically think sub modules are vendored code, hence should be ignored by style tools, but maybe that is not the case for you.
—Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you authored the thread.Message ID: ***@***.***>
Ehm, hehe 😉 yes thats true, bitbthe astronvim distribution works differently :). But tou are right I meant I always executed the format with the cwd in the submodule and since it has a config file that one should be found, strange, I check again in a few days.
Anyway, all format tools actually do this as far as I know from clang-format - start from the file. Please check again, now a bit unsure.
Yes, I think it is valid still. I will restructure your feature request to "Use closest configuration to file"
@JohnnyMorganz : Would improve tooling much, since it will pick up the closest .stylelua.toml file and make an astronvim user install much nicer! Looking forward to this. BR
What is the structure of your workspace? (i.e. the location of the file relative to your stylua.toml and the folder you have open in VSCode)
I have `folder` open
```
folder
- stylua.toml
- test.lua
- src
- client
- Tiles
- TileBoard.lua
```
I get space indentation in `test.lua`, but tab indentation in `src/client/Tiles/TileBoard.lua`
`stylua.toml`
```
column_width = 140
line_endings = "Windows"
indent_type = "Spaces"
indent_width = 4
quote_style = "AutoPreferDouble"
call_parentheses = "Always"
collapse_simple_statement = "Never"
```
Agh, thanks.
This is unfortunately me misunderstanding the way I originally implemented `stdin-filepath` and how it relates to config resolution.
I'm going to fix this properly in #831 which will be in the next release. But for now, you can either use the older version or configure "search parent directories" in the vscode settings
|
2024-11-17T19:57:54Z
|
0.20
|
2024-11-17T16:13:53Z
|
26047670e05ba310afe9c1c1f91be6749e1f3ac9
|
[
"tests::test_configuration_is_used_closest_to_the_file",
"tests::test_configuration_is_searched_next_to_file",
"tests::test_stdin_filepath_respects_cwd_configuration_for_nested_file"
] |
[
"editorconfig::tests::test_call_parentheses_no_single_table",
"editorconfig::tests::test_call_parentheses_no_single_string",
"editorconfig::tests::test_call_parentheses_always",
"editorconfig::tests::test_call_parentheses_none",
"editorconfig::tests::test_collapse_simple_statement_always",
"editorconfig::tests::test_collapse_simple_statement_conditional_only",
"editorconfig::tests::test_collapse_simple_statement_function_only",
"editorconfig::tests::test_collapse_simple_statement_never",
"editorconfig::tests::test_end_of_line_cr",
"editorconfig::tests::test_end_of_line_crlf",
"editorconfig::tests::test_end_of_line_lf",
"editorconfig::tests::test_indent_size",
"editorconfig::tests::test_indent_size_use_tab_width",
"editorconfig::tests::test_indent_style_space",
"editorconfig::tests::test_indent_style_tab",
"editorconfig::tests::test_invalid_properties",
"editorconfig::tests::test_max_line_length",
"editorconfig::tests::test_max_line_length_off",
"editorconfig::tests::test_quote_type_auto",
"editorconfig::tests::test_quote_type_double",
"editorconfig::tests::test_quote_type_single",
"editorconfig::tests::test_sort_requires_disabled",
"editorconfig::tests::test_sort_requires_enabled",
"editorconfig::tests::test_space_after_function_names_always",
"editorconfig::tests::test_space_after_function_names_calls",
"editorconfig::tests::test_space_after_function_names_definitions",
"editorconfig::tests::test_space_after_function_names_never",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments_2",
"formatters::trivia_util::tests::test_token_contains_singleline_comments",
"sort_requires::tests::fail_extracting_non_identifier_token",
"sort_requires::tests::get_expression_kind_other_1",
"sort_requires::tests::get_expression_kind_other_2",
"tests::test_config_call_parentheses",
"tests::test_config_indent_type",
"tests::test_config_column_width",
"tests::test_config_indent_width",
"tests::test_config_line_endings",
"tests::test_config_quote_style",
"sort_requires::tests::get_expression_kind_get_service",
"sort_requires::tests::get_expression_kind_other_6",
"sort_requires::tests::get_expression_kind_other_3",
"sort_requires::tests::get_expression_kind_other_5",
"tests::test_invalid_input",
"sort_requires::tests::get_expression_kind_other_4",
"sort_requires::tests::get_expression_kind_require_stmt",
"sort_requires::tests::get_expression_kind_require_type_assertion",
"verify_ast::tests::test_equivalent_conditions",
"verify_ast::tests::test_equivalent_asts",
"tests::test_entry_point",
"verify_ast::tests::test_different_hex_numbers",
"verify_ast::tests::test_equivalent_binary_numbers",
"verify_ast::tests::test_equivalent_hex_numbers_very_large_number",
"verify_ast::tests::test_different_asts",
"tests::test_with_ast_verification",
"verify_ast::tests::test_different_binary_numbers",
"verify_ast::tests::test_equivalent_string_escapes",
"verify_ast::tests::test_equivalent_function_calls",
"verify_ast::tests::test_equivalent_numbers_2",
"verify_ast::tests::test_equivalent_stmt_semicolons",
"verify_ast::tests::test_equivalent_luajit_numbers",
"verify_ast::tests::test_equivalent_function_calls_2",
"verify_ast::tests::test_equivalent_hex_numbers",
"verify_ast::tests::test_equivalent_hex_numbers_with_separators",
"verify_ast::tests::test_equivalent_types_removed_parentheses",
"verify_ast::tests::test_equivalent_numbers",
"verify_ast::tests::test_equivalent_string_quote_types",
"verify_ast::tests::test_equivalent_table_separators",
"output_diff::tests::test_addition_diff",
"output_diff::tests::test_change_diff",
"output_diff::tests::test_deletion_diff",
"opt::tests::verify_opt",
"config::tests::test_override_column_width",
"config::tests::test_override_indent_width",
"config::tests::test_override_call_parentheses",
"config::tests::test_override_indent_type",
"config::tests::test_override_quote_style",
"output_diff::tests::test_no_diff",
"config::tests::test_override_line_endings",
"config::tests::test_override_syntax",
"tests::test_no_files_provided",
"tests::test_format_stdin",
"tests::explicitly_provided_files_dont_check_ignores_stdin",
"tests::test_respect_ignores",
"tests::test_respect_ignores_directory_no_glob",
"tests::test_respect_config_path_override_for_stdin_filepath",
"tests::test_respect_ignores_stdin",
"tests::explicitly_provided_files_dont_check_ignores",
"tests::test_format_file",
"tests::test_cwd_configuration_respected_for_nested_file",
"tests::test_stdin_filepath_respects_cwd_configuration_next_to_file",
"tests::test_configuration_used_outside_of_cwd_when_search_parent_directories_is_enabled",
"tests::test_cwd_configuration_respected_for_file_in_cwd",
"tests::test_respect_config_path_override",
"tests::test_configuration_is_not_used_outside_of_cwd",
"tests::test_stylua_ignore",
"test_call_parens_comments",
"test_call_parens_always_handles_table_correctly",
"test_call_parens_no_single_string_handles_table_correctly",
"test_call_parens_no_single_string_handles_string_correctly",
"test_call_parens_semicolons",
"test_call_parens_none_handles_table_correctly",
"test_call_parens_no_single_table_handles_string_correctly",
"test_call_parens_always_handles_string_correctly",
"test_call_parens_no_single_table_handles_table_correctly",
"test_call_parens_none_handles_string_correctly",
"test_call_parens_input",
"test_call_parens_has_no_affect_on_multi_arg_fn_calls_",
"test_local",
"test_empty_root",
"test_global",
"test_root",
"test_stylua_toml",
"test_omit_parens_brackets_string",
"test_no_parens_brackets_string",
"test_no_parens_multiline_table",
"test_no_parens_singleline_table",
"test_no_parens_method_chain_1",
"test_omit_parens_string",
"test_keep_parens_binop_string",
"test_no_parens_method_chain_2",
"test_no_parens_large_example",
"test_no_parens_string",
"test_auto_prefer_single_quotes",
"test_force_double_quotes",
"test_force_single_quotes",
"test_auto_prefer_double_quotes",
"test_dont_modify_eof",
"test_ignore_last_stmt",
"test_incomplete_range",
"test_nested_range_else_if",
"test_nested_range_generic_for",
"test_nested_range_function_call",
"test_default",
"test_nested_range_do",
"test_nested_range_binop",
"test_nested_range_function_call_table",
"test_nested_range",
"test_large_example",
"test_nested_range_repeat",
"test_no_range_start",
"test_nested_range_table_1",
"test_nested_range_while",
"test_nested_range_table_2",
"test_nested_range_local_function",
"test_no_range_end",
"test_always_space_after_function_names",
"test_never_space_after_function_names",
"test_space_after_function_definitions",
"test_space_after_function_calls",
"test_crlf_in_multiline_strings",
"test_crlf_in_multiline_comments",
"test_collapse_single_statement_lua_52",
"test_lua52",
"test_lua54",
"test_ignores",
"test_lua53",
"test_sort_requires",
"test_full_moon_test_suite",
"test_collapse_single_statement",
"test_luau_full_moon",
"test_luau",
"test_standard"
] |
[] |
[] |
JohnnyMorganz/StyLua
| 852
|
JohnnyMorganz__StyLua-852
|
[
"845"
] |
bc3ce881eaaee46e8eb851366d33cba808d2a1f7
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The CLI tool will now only write files if the contents differ, and not modify if no change ([#827](https://github.com/JohnnyMorganz/StyLua/issues/827))
- Fixed parentheses around a Luau compound type inside of a type table indexer being removed causing a syntax error ([#828](https://github.com/JohnnyMorganz/StyLua/issues/828))
- Fixed function body parentheses being placed on multiple lines unnecessarily when there are no parameters ([#830](https://github.com/JohnnyMorganz/StyLua/issues/830))
+- Fixed directory paths w/o globs in `.styluaignore` not matching when using `--respect-ignores` ([#845](https://github.com/JohnnyMorganz/StyLua/issues/845))
## [0.19.1] - 2023-11-15
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -262,7 +262,7 @@ fn path_is_stylua_ignored(path: &Path, search_parent_directories: bool) -> Resul
.context("failed to parse ignore file")?;
Ok(matches!(
- ignore.matched(path, false),
+ ignore.matched_path_or_any_parents(path, false),
ignore::Match::Ignore(_)
))
}
|
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -769,4 +769,21 @@ mod tests {
cwd.close().unwrap();
}
+
+ #[test]
+ fn test_respect_ignores_directory_no_glob() {
+ // https://github.com/JohnnyMorganz/StyLua/issues/845
+ let cwd = construct_tree!({
+ ".styluaignore": "build/",
+ "build/foo.lua": "local x = 1",
+ });
+
+ let mut cmd = create_stylua();
+ cmd.current_dir(cwd.path())
+ .args(["--check", "--respect-ignores", "build/foo.lua"])
+ .assert()
+ .success();
+
+ cwd.close().unwrap();
+ }
}
|
`--respect-ignores`: does not correctly ignore folders without the globbing pattern
Problem: `.styluaignore` does not ignore **folders** or **directories** like `.gitignore`, `.rgignore`, etc. do. Instead, full globbing patterns (`*.lua` or `**/*.lua`) would be needed to ignore all files under a directory.
EDIT: This seems to be the case only when used with `--respect-ignores <pattern>`.
## Example
(Tested with stylua 0.19.1, which already includes #765)
Let's say we have `src/foo.lua` and `build/foo.lua` in the project root (with `.styluaignore`).
### Current behavior
With the following `.styluaignore`:
```
build/
```
`$ stylua --check --respect-ignores build/foo.lua` would not ignore `build/foo.lua`.
### Expected behavior
`build/foo.lua` should be ignored.
### Current behavior (2)
With the following `.styluaignore`:
```
build/**/*.lua
```
`$ stylua --check --respect-ignores build/foo.lua` does ignore `build/foo.lua`. This behavior is consistent with `.gitignore`, etc.
|
We use the ignore crate to provide gitignore-style ignores: https://docs.rs/ignore/latest/ignore/. This may actually be an issue upstream, but I will verify it myself first
(Ignore my previous response - I did not read your issue properly!)
Yes, I find that ignoring a (sub)directory works when scanning, i.e., "stylua ." (unit tests: https://github.com/JohnnyMorganz/StyLua/blob/v0.19.1/src/cli/main.rs#L723), but doesn't work only for `--respect-ignores <individual filename>`.
|
2024-01-20T20:13:59Z
|
0.19
|
2024-01-20T12:37:21Z
|
bc3ce881eaaee46e8eb851366d33cba808d2a1f7
|
[
"tests::test_respect_ignores_directory_no_glob"
] |
[
"editorconfig::tests::test_call_parentheses_always",
"editorconfig::tests::test_call_parentheses_no_single_table",
"editorconfig::tests::test_call_parentheses_no_single_string",
"editorconfig::tests::test_call_parentheses_none",
"editorconfig::tests::test_collapse_simple_statement_always",
"editorconfig::tests::test_collapse_simple_statement_conditional_only",
"editorconfig::tests::test_collapse_simple_statement_never",
"editorconfig::tests::test_collapse_simple_statement_function_only",
"editorconfig::tests::test_end_of_line_cr",
"editorconfig::tests::test_end_of_line_lf",
"editorconfig::tests::test_indent_size",
"editorconfig::tests::test_end_of_line_crlf",
"editorconfig::tests::test_indent_size_use_tab_width",
"editorconfig::tests::test_indent_style_tab",
"editorconfig::tests::test_indent_style_space",
"editorconfig::tests::test_max_line_length",
"editorconfig::tests::test_max_line_length_off",
"editorconfig::tests::test_invalid_properties",
"editorconfig::tests::test_quote_type_auto",
"editorconfig::tests::test_quote_type_double",
"editorconfig::tests::test_quote_type_single",
"editorconfig::tests::test_sort_requires_disabled",
"editorconfig::tests::test_sort_requires_enabled",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments",
"formatters::trivia_util::tests::test_token_contains_singleline_comments",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments_2",
"sort_requires::tests::fail_extracting_non_identifier_token",
"tests::test_config_indent_type",
"tests::test_config_call_parentheses",
"tests::test_config_column_width",
"tests::test_config_indent_width",
"tests::test_config_line_endings",
"tests::test_config_quote_style",
"sort_requires::tests::get_expression_kind_other_2",
"sort_requires::tests::get_expression_kind_other_1",
"sort_requires::tests::get_expression_kind_get_service",
"sort_requires::tests::get_expression_kind_other_3",
"sort_requires::tests::get_expression_kind_other_6",
"sort_requires::tests::get_expression_kind_other_4",
"sort_requires::tests::get_expression_kind_require_stmt",
"sort_requires::tests::get_expression_kind_other_5",
"tests::test_invalid_input",
"tests::test_entry_point",
"sort_requires::tests::get_expression_kind_require_type_assertion",
"verify_ast::tests::test_different_hex_numbers",
"verify_ast::tests::test_different_asts",
"verify_ast::tests::test_equivalent_binary_numbers",
"verify_ast::tests::test_different_binary_numbers",
"tests::test_with_ast_verification",
"verify_ast::tests::test_equivalent_conditions",
"verify_ast::tests::test_equivalent_asts",
"verify_ast::tests::test_equivalent_function_calls",
"verify_ast::tests::test_equivalent_numbers",
"verify_ast::tests::test_equivalent_hex_numbers",
"verify_ast::tests::test_equivalent_luajit_numbers",
"verify_ast::tests::test_equivalent_string_quote_types",
"verify_ast::tests::test_equivalent_string_escapes",
"verify_ast::tests::test_equivalent_numbers_2",
"verify_ast::tests::test_equivalent_stmt_semicolons",
"verify_ast::tests::test_equivalent_types_removed_parentheses",
"verify_ast::tests::test_equivalent_function_calls_2",
"verify_ast::tests::test_equivalent_table_separators",
"output_diff::tests::test_addition_diff",
"output_diff::tests::test_deletion_diff",
"output_diff::tests::test_no_diff",
"output_diff::tests::test_change_diff",
"opt::tests::verify_opt",
"config::tests::test_override_indent_width",
"config::tests::test_override_indent_type",
"config::tests::test_override_column_width",
"config::tests::test_override_line_endings",
"config::tests::test_override_call_parentheses",
"config::tests::test_override_quote_style",
"tests::test_no_files_provided",
"tests::test_format_stdin",
"tests::explicitly_provided_files_dont_check_ignores",
"tests::test_format_file",
"tests::test_respect_ignores",
"tests::test_stylua_ignore",
"test_call_parens_comments",
"test_call_parens_semicolons",
"test_call_parens_none_handles_table_correctly",
"test_call_parens_none_handles_string_correctly",
"test_call_parens_always_handles_table_correctly",
"test_call_parens_no_single_string_handles_string_correctly",
"test_call_parens_no_single_string_handles_table_correctly",
"test_call_parens_no_single_table_handles_table_correctly",
"test_call_parens_input",
"test_call_parens_always_handles_string_correctly",
"test_call_parens_no_single_table_handles_string_correctly",
"test_call_parens_has_no_affect_on_multi_arg_fn_calls_",
"test_root",
"test_empty_root",
"test_global",
"test_local",
"test_stylua_toml",
"test_no_parens_singleline_table",
"test_omit_parens_brackets_string",
"test_no_parens_brackets_string",
"test_no_parens_multiline_table",
"test_no_parens_string",
"test_no_parens_method_chain_1",
"test_omit_parens_string",
"test_keep_parens_binop_string",
"test_no_parens_method_chain_2",
"test_no_parens_large_example",
"test_force_double_quotes",
"test_force_single_quotes",
"test_auto_prefer_single_quotes",
"test_auto_prefer_double_quotes",
"test_incomplete_range",
"test_ignore_last_stmt",
"test_default",
"test_dont_modify_eof",
"test_nested_range_do",
"test_nested_range_generic_for",
"test_nested_range_function_call",
"test_nested_range_function_call_table",
"test_nested_range_else_if",
"test_nested_range_local_function",
"test_nested_range_binop",
"test_nested_range",
"test_no_range_start",
"test_nested_range_while",
"test_no_range_end",
"test_nested_range_repeat",
"test_nested_range_table_1",
"test_nested_range_table_2",
"test_crlf_in_multiline_strings",
"test_crlf_in_multiline_comments",
"test_collapse_single_statement_lua_52",
"test_lua52",
"test_lua54",
"test_lua53",
"test_ignores",
"test_sort_requires",
"test_collapse_single_statement",
"test_luau_full_moon",
"test_luau"
] |
[] |
[] |
JohnnyMorganz/StyLua
| 752
|
JohnnyMorganz__StyLua-752
|
[
"750"
] |
fdf9f0c5952cb1565ba6449929514eb94ac5ef3f
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- Fixed LuaJIT suffixes `LL`/`ULL` causing a panic when running in `--verify` mode ([#750](https://github.com/JohnnyMorganz/StyLua/issues/750))
+
## [0.18.1] - 2023-07-15
### Fixed
diff --git a/src/verify_ast.rs b/src/verify_ast.rs
--- a/src/verify_ast.rs
+++ b/src/verify_ast.rs
@@ -146,6 +146,12 @@ impl VisitorMut for AstVerifier {
// Luau: cleanse number of any digit separators
#[cfg(feature = "luau")]
let text = text.replace('_', "");
+ // LuaJIT (Lua52): remove suffixes
+ #[cfg(feature = "lua52")]
+ let text = text
+ .trim_end_matches("ULL")
+ .trim_end_matches("LL")
+ .to_string();
let number = match text.as_str().parse::<f64>() {
Ok(num) => num,
|
diff --git a/src/verify_ast.rs b/src/verify_ast.rs
--- a/src/verify_ast.rs
+++ b/src/verify_ast.rs
@@ -305,6 +311,16 @@ mod tests {
assert!(!ast_verifier.compare(input_ast, output_ast));
}
+ #[test]
+ #[cfg(feature = "lua52")]
+ fn test_equivalent_luajit_numbers() {
+ let input_ast = full_moon::parse("local x = 2 ^ 63LL").unwrap();
+ let output_ast = full_moon::parse("local x = 2 ^ 63").unwrap();
+
+ let mut ast_verifier = AstVerifier::new();
+ assert!(ast_verifier.compare(input_ast, output_ast));
+ }
+
#[test]
fn test_equivalent_table_separators() {
let input_ast = full_moon::parse("local x = {'a'; 'b'; 'c';}").unwrap();
|
Panic when format luajit type with `--verify` flag
installed by `cargo install stylua --features lua52`
```
$ echo "return 2^63LL " | RUST_BACKTRACE=1 stylua -
return 2 ^ 63LL
$ echo "return 2^63LL " | RUST_BACKTRACE=1 stylua --verify -
thread '<unnamed>' panicked at 'internal error: entered unreachable code', ~/.cargo/registry/src/github.com-1ecc6299db9ec823/stylua-0.18.1/src/verify_ast.rs:162:35
stack backtrace:
0: rust_begin_unwind
at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:575:5
1: core::panicking::panic_fmt
at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/panicking.rs:65:14
2: core::panicking::panic
at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/panicking.rs:115:5
3: <stylua_lib::verify_ast::AstVerifier as full_moon::visitors::VisitorMut>::visit_number
4: <full_moon::tokenizer::Token as full_moon::visitors::VisitMut>::visit_mut
5: <full_moon::tokenizer::TokenReference as full_moon::visitors::VisitMut>::visit_mut
6: <full_moon::ast::Value as full_moon::visitors::VisitMut>::visit_mut
7: <alloc::boxed::Box<T> as full_moon::visitors::VisitMut>::visit_mut
8: full_moon::ast::visitors::<impl full_moon::visitors::VisitMut for full_moon::ast::Expression>::visit_mut
9: <alloc::boxed::Box<T> as full_moon::visitors::VisitMut>::visit_mut
10: full_moon::ast::visitors::<impl full_moon::visitors::VisitMut for full_moon::ast::Expression>::visit_mut
11: <full_moon::ast::punctuated::Pair<T> as full_moon::visitors::VisitMut>::visit_mut
12: <alloc::vec::Vec<T> as full_moon::visitors::VisitMut>::visit_mut
13: <(A,B) as full_moon::visitors::VisitMut>::visit_mut
14: <full_moon::ast::Block as full_moon::visitors::VisitMut>::visit_mut
15: full_moon::visitors::VisitorMut::visit_ast
16: stylua_lib::verify_ast::AstVerifier::compare
17: stylua_lib::format_ast
18: stylua_lib::format_code
19: <F as threadpool::FnBox>::call_box
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
```
|
2023-09-02T08:18:04Z
|
0.18
|
2023-09-02T00:44:03Z
|
095e2b0c79df0bac21915dd2deee9a0a25a9b382
|
[
"verify_ast::tests::test_equivalent_luajit_numbers",
"test_global",
"test_local",
"test_empty_root",
"test_root",
"test_stylua_toml",
"test_lua54"
] |
[
"editorconfig::tests::test_call_parentheses_always",
"editorconfig::tests::test_call_parentheses_no_single_table",
"editorconfig::tests::test_call_parentheses_no_single_string",
"editorconfig::tests::test_call_parentheses_none",
"editorconfig::tests::test_collapse_simple_statement_always",
"editorconfig::tests::test_collapse_simple_statement_conditional_only",
"editorconfig::tests::test_collapse_simple_statement_function_only",
"editorconfig::tests::test_end_of_line_cr",
"editorconfig::tests::test_collapse_simple_statement_never",
"editorconfig::tests::test_end_of_line_lf",
"editorconfig::tests::test_end_of_line_crlf",
"editorconfig::tests::test_indent_size",
"editorconfig::tests::test_indent_size_use_tab_width",
"editorconfig::tests::test_indent_style_space",
"editorconfig::tests::test_indent_style_tab",
"editorconfig::tests::test_max_line_length",
"editorconfig::tests::test_invalid_properties",
"editorconfig::tests::test_max_line_length_off",
"editorconfig::tests::test_quote_type_auto",
"editorconfig::tests::test_quote_type_double",
"editorconfig::tests::test_quote_type_single",
"editorconfig::tests::test_sort_requires_disabled",
"editorconfig::tests::test_sort_requires_enabled",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments",
"formatters::trivia_util::tests::test_token_contains_singleline_comments",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments_2",
"sort_requires::tests::fail_extracting_non_identifier_token",
"tests::test_config_indent_type",
"tests::test_config_column_width",
"tests::test_config_indent_width",
"sort_requires::tests::get_expression_kind_other_1",
"sort_requires::tests::get_expression_kind_other_2",
"tests::test_config_quote_style",
"sort_requires::tests::get_expression_kind_other_4",
"sort_requires::tests::get_expression_kind_get_service",
"sort_requires::tests::get_expression_kind_require_stmt",
"tests::test_config_call_parentheses",
"sort_requires::tests::get_expression_kind_other_3",
"tests::test_invalid_input",
"verify_ast::tests::test_different_asts",
"sort_requires::tests::get_expression_kind_other_6",
"sort_requires::tests::get_expression_kind_other_5",
"verify_ast::tests::test_different_hex_numbers",
"tests::test_entry_point",
"verify_ast::tests::test_different_binary_numbers",
"verify_ast::tests::test_equivalent_binary_numbers",
"tests::test_with_ast_verification",
"tests::test_config_line_endings",
"verify_ast::tests::test_equivalent_conditions",
"verify_ast::tests::test_equivalent_stmt_semicolons",
"verify_ast::tests::test_equivalent_string_escapes",
"verify_ast::tests::test_equivalent_string_quote_types",
"verify_ast::tests::test_equivalent_numbers",
"verify_ast::tests::test_equivalent_asts",
"verify_ast::tests::test_equivalent_hex_numbers",
"verify_ast::tests::test_equivalent_table_separators",
"verify_ast::tests::test_equivalent_function_calls",
"verify_ast::tests::test_equivalent_types_removed_parentheses",
"verify_ast::tests::test_equivalent_numbers_2",
"verify_ast::tests::test_equivalent_function_calls_2",
"output_diff::tests::test_addition_diff",
"output_diff::tests::test_no_diff",
"output_diff::tests::test_deletion_diff",
"output_diff::tests::test_change_diff",
"opt::tests::verify_opt",
"config::tests::test_override_call_parentheses",
"config::tests::test_override_indent_width",
"config::tests::test_override_indent_type",
"config::tests::test_override_quote_style",
"config::tests::test_override_line_endings",
"config::tests::test_override_column_width",
"tests::test_no_files_provided",
"tests::test_format_stdin",
"test_call_parens_comments",
"test_call_parens_none_handles_string_correctly",
"test_call_parens_always_handles_string_correctly",
"test_call_parens_always_handles_table_correctly",
"test_call_parens_no_single_string_handles_table_correctly",
"test_call_parens_none_handles_table_correctly",
"test_call_parens_semicolons",
"test_call_parens_no_single_table_handles_string_correctly",
"test_call_parens_input",
"test_call_parens_no_single_table_handles_table_correctly",
"test_call_parens_no_single_string_handles_string_correctly",
"test_call_parens_has_no_affect_on_multi_arg_fn_calls_",
"test_no_parens_singleline_table",
"test_no_parens_multiline_table",
"test_no_parens_brackets_string",
"test_omit_parens_brackets_string",
"test_omit_parens_string",
"test_no_parens_string",
"test_keep_parens_binop_string",
"test_no_parens_method_chain_1",
"test_no_parens_method_chain_2",
"test_no_parens_large_example",
"test_auto_prefer_single_quotes",
"test_force_double_quotes",
"test_auto_prefer_double_quotes",
"test_force_single_quotes",
"test_ignore_last_stmt",
"test_dont_modify_eof",
"test_nested_range_do",
"test_default",
"test_incomplete_range",
"test_nested_range_generic_for",
"test_nested_range_function_call_table",
"test_nested_range_else_if",
"test_nested_range_function_call",
"test_nested_range_binop",
"test_nested_range",
"test_large_example",
"test_no_range_end",
"test_no_range_start",
"test_nested_range_repeat",
"test_nested_range_while",
"test_nested_range_table_1",
"test_nested_range_table_2",
"test_nested_range_local_function",
"test_crlf_in_multiline_strings",
"test_crlf_in_multiline_comments",
"test_collapse_single_statement_lua_52",
"test_lua53",
"test_lua52",
"test_ignores",
"test_sort_requires",
"test_collapse_single_statement",
"test_luau_full_moon",
"test_luau"
] |
[] |
[] |
|
JohnnyMorganz/StyLua
| 666
|
JohnnyMorganz__StyLua-666
|
[
"665"
] |
46457ad4e4130d07ee0f9a5cf95ac10023c8ceeb
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Bumped internal parser dependency which should fix parsing problems for comments with Chinese characters, and multiline string escapes
- Fixed comments in punctuated lists for return statements or assignments being incorrectly formatted leading to syntax errors ([#662](https://github.com/JohnnyMorganz/StyLua/issues/662))
+- Fixed line endings not being correctly formatted in multiline string literals and comments ([#665](https://github.com/JohnnyMorganz/StyLua/issues/665))
## [0.17.0] - 2023-03-11
diff --git a/src/context.rs b/src/context.rs
--- a/src/context.rs
+++ b/src/context.rs
@@ -155,7 +155,7 @@ impl Context {
}
/// Returns the relevant line ending string from the [`LineEndings`] enum
-fn line_ending_character(line_endings: LineEndings) -> String {
+pub fn line_ending_character(line_endings: LineEndings) -> String {
match line_endings {
LineEndings::Unix => String::from("\n"),
LineEndings::Windows => String::from("\r\n"),
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -1,5 +1,7 @@
use crate::{
- context::{create_indent_trivia, create_newline_trivia, Context, FormatNode},
+ context::{
+ create_indent_trivia, create_newline_trivia, line_ending_character, Context, FormatNode,
+ },
formatters::{
trivia::{FormatTriviaType, UpdateLeadingTrivia, UpdateTrailingTrivia, UpdateTrivia},
trivia_util::{
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -121,8 +123,14 @@ pub fn format_token(
} => {
// If we have a brackets string, don't mess with it
if let StringLiteralQuoteType::Brackets = quote_type {
+ // Convert the string to the correct line endings, by first normalising to LF
+ // then converting LF to output
+ let literal = literal
+ .replace("\r\n", "\n")
+ .replace('\n', &line_ending_character(ctx.config().line_endings));
+
TokenType::StringLiteral {
- literal: literal.to_owned(),
+ literal: literal.into(),
multi_line: *multi_line,
quote_type: StringLiteralQuoteType::Brackets,
}
diff --git a/src/formatters/general.rs b/src/formatters/general.rs
--- a/src/formatters/general.rs
+++ b/src/formatters/general.rs
@@ -209,9 +217,15 @@ pub fn format_token(
trailing_trivia = Some(vec![create_newline_trivia(ctx)]);
}
+ // Convert the comment to the correct line endings, by first normalising to LF
+ // then converting LF to output
+ let comment = comment
+ .replace("\r\n", "\n")
+ .replace('\n', &line_ending_character(ctx.config().line_endings));
+
TokenType::MultiLineComment {
blocks: *blocks,
- comment: comment.to_owned(),
+ comment: comment.into(),
}
}
TokenType::Whitespace { characters } => TokenType::Whitespace {
|
diff --git a/tests/tests.rs b/tests/tests.rs
--- a/tests/tests.rs
+++ b/tests/tests.rs
@@ -127,3 +127,40 @@ fn test_sort_requires() {
.unwrap());
})
}
+
+#[test]
+fn test_crlf_in_multiline_comments() {
+ // We need to do this outside of insta since it normalises line endings to LF
+ let code = r###"
+local a = "testing"
+--[[
+ This comment
+ is multiline
+ and we want to ensure the line endings
+ convert to CRLF
+]]
+local x = 1
+"###;
+
+ let code_crlf = code.lines().collect::<Vec<_>>().join("\r\n");
+ let output = format(&code_crlf);
+ assert_eq!(output.find("\r\n"), None);
+}
+
+#[test]
+fn test_crlf_in_multiline_strings() {
+ // We need to do this outside of insta since it normalises line endings to LF
+ let code = r###"
+local a = [[
+ This string
+ is multiline
+ and we want to ensure the line endings
+ convert to CRLF
+]]
+local x = 1
+"###;
+
+ let code_crlf = code.lines().collect::<Vec<_>>().join("\r\n");
+ let output = format(&code_crlf);
+ assert_eq!(output.find("\r\n"), None);
+}
|
Line endings appear to not be converted when they occur in multiline comments (?)
Heyo, we've run into an odd formatting glitch that causes huge git diffs in combination with VS Code's LF/CRLF setting.
In this example file, we have CRLFs present in the comment but LFs everywhere else (as created by StyLua, using the default config):

Copy these hex bytes for a simple test case (CRLF/LF distinction):
```
0D 0A 2D 2D 5B 5B 0D 0A 20 20 20 20 20 20 74 65 73 74 0D 0A 20 20 20 20 20 20 2D 2D 20 61 73 64 66 0D 0A 20 20 5D 5D 0D 0A
```
After running StyLua on this CRLF-based file, all CRLFs in the regular code are correctly turned into LF, but those in the comment are not:

Again, the hex bytes show that this is the case:
```
0A 2D 2D 5B 5B 0D 0A 20 20 20 20 20 20 74 65 73 74 0D 0A 20 20 20 20 20 20 2D 2D 20 61 73 64 66 0D 0A 20 20 5D 5D 0A
```
I would expect all line endings to be consistent after running the formatter, which is is preferable to ugly hacks like `autocrlf`:

Expected hex bytes:
```
0A 2D 2D 5B 5B 0A 20 20 20 20 20 20 74 65 73 74 0A 20 20 20 20 20 20 2D 2D 20 61 73 64 66 0A 20 20 5D 5D 0A
```
I don't know Rust at all so I can't contribute a fix, but feel free to use the above as a test case if this is unintended :)
|
Definitely unintended, let me take a look. Thanks for the report!
|
2023-03-30T23:38:41Z
|
0.17
|
2023-03-30T15:47:25Z
|
5c6d59135f419274121349799a5227be467358b1
|
[
"test_global",
"test_root",
"test_local",
"test_stylua_toml",
"test_crlf_in_multiline_strings",
"test_crlf_in_multiline_comments",
"test_lua54"
] |
[
"editorconfig::tests::test_call_parentheses_always",
"editorconfig::tests::test_call_parentheses_no_single_string",
"editorconfig::tests::test_call_parentheses_no_single_table",
"editorconfig::tests::test_call_parentheses_none",
"editorconfig::tests::test_collapse_simple_statement_always",
"editorconfig::tests::test_collapse_simple_statement_conditional_only",
"editorconfig::tests::test_collapse_simple_statement_never",
"editorconfig::tests::test_collapse_simple_statement_function_only",
"editorconfig::tests::test_end_of_line_cr",
"editorconfig::tests::test_end_of_line_crlf",
"editorconfig::tests::test_indent_size",
"editorconfig::tests::test_end_of_line_lf",
"editorconfig::tests::test_indent_size_use_tab_width",
"editorconfig::tests::test_indent_style_space",
"editorconfig::tests::test_indent_style_tab",
"editorconfig::tests::test_invalid_properties",
"editorconfig::tests::test_max_line_length",
"editorconfig::tests::test_max_line_length_off",
"editorconfig::tests::test_quote_type_auto",
"editorconfig::tests::test_quote_type_double",
"editorconfig::tests::test_quote_type_single",
"editorconfig::tests::test_sort_requires_disabled",
"editorconfig::tests::test_sort_requires_enabled",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments_2",
"formatters::trivia_util::tests::test_token_contains_singleline_comments",
"sort_requires::tests::fail_extracting_non_identifier_token",
"tests::test_config_indent_width",
"tests::test_config_indent_type",
"tests::test_config_column_width",
"tests::test_config_line_endings",
"tests::test_config_call_parentheses",
"tests::test_config_quote_style",
"sort_requires::tests::get_expression_kind_other_6",
"tests::test_invalid_input",
"sort_requires::tests::get_expression_kind_other_4",
"sort_requires::tests::get_expression_kind_other_1",
"sort_requires::tests::get_expression_kind_other_3",
"verify_ast::tests::test_different_asts",
"sort_requires::tests::get_expression_kind_other_5",
"sort_requires::tests::get_expression_kind_require_stmt",
"tests::test_entry_point",
"sort_requires::tests::get_expression_kind_other_2",
"sort_requires::tests::get_expression_kind_get_service",
"tests::test_with_ast_verification",
"verify_ast::tests::test_different_hex_numbers",
"verify_ast::tests::test_equivalent_asts",
"verify_ast::tests::test_different_binary_numbers",
"verify_ast::tests::test_equivalent_binary_numbers",
"verify_ast::tests::test_equivalent_stmt_semicolons",
"verify_ast::tests::test_equivalent_hex_numbers",
"verify_ast::tests::test_equivalent_numbers_2",
"verify_ast::tests::test_equivalent_function_calls",
"verify_ast::tests::test_equivalent_conditions",
"verify_ast::tests::test_equivalent_numbers",
"verify_ast::tests::test_equivalent_string_quote_types",
"verify_ast::tests::test_equivalent_types_removed_parentheses",
"verify_ast::tests::test_equivalent_string_escapes",
"verify_ast::tests::test_equivalent_function_calls_2",
"verify_ast::tests::test_equivalent_table_separators",
"output_diff::tests::test_deletion_diff",
"output_diff::tests::test_addition_diff",
"output_diff::tests::test_no_diff",
"output_diff::tests::test_change_diff",
"opt::tests::verify_opt",
"config::tests::test_override_quote_style",
"config::tests::test_override_line_endings",
"config::tests::test_override_indent_type",
"config::tests::test_override_call_parentheses",
"config::tests::test_override_column_width",
"config::tests::test_override_indent_width",
"tests::test_no_files_provided",
"tests::test_format_stdin",
"test_call_parens_comments",
"test_call_parens_semicolons",
"test_call_parens_no_single_string_handles_string_correctly",
"test_call_parens_no_single_table_handles_string_correctly",
"test_call_parens_none_handles_string_correctly",
"test_call_parens_always_handles_string_correctly",
"test_call_parens_always_handles_table_correctly",
"test_call_parens_no_single_table_handles_table_correctly",
"test_call_parens_none_handles_table_correctly",
"test_call_parens_no_single_string_handles_table_correctly",
"test_call_parens_has_no_affect_on_multi_arg_fn_calls_",
"test_empty_root",
"test_no_parens_multiline_table",
"test_no_parens_singleline_table",
"test_omit_parens_brackets_string",
"test_no_parens_string",
"test_no_parens_brackets_string",
"test_omit_parens_string",
"test_no_parens_method_chain_1",
"test_keep_parens_binop_string",
"test_no_parens_method_chain_2",
"test_no_parens_large_example",
"test_auto_prefer_double_quotes",
"test_auto_prefer_single_quotes",
"test_force_single_quotes",
"test_force_double_quotes",
"test_incomplete_range",
"test_ignore_last_stmt",
"test_default",
"test_dont_modify_eof",
"test_nested_range_do",
"test_nested_range_generic_for",
"test_nested_range_else_if",
"test_nested_range_function_call",
"test_nested_range_function_call_table",
"test_nested_range_binop",
"test_nested_range",
"test_nested_range_repeat",
"test_no_range_start",
"test_no_range_end",
"test_nested_range_while",
"test_nested_range_table_1",
"test_nested_range_local_function",
"test_nested_range_table_2",
"test_large_example",
"test_collapse_single_statement_lua_52",
"test_lua53",
"test_lua52",
"test_ignores",
"test_sort_requires",
"test_collapse_single_statement",
"test_luau_full_moon",
"test_luau"
] |
[] |
[] |
JohnnyMorganz/StyLua
| 645
|
JohnnyMorganz__StyLua-645
|
[
"75"
] |
15c1f0d4880dbcfe37dd2828da10745f95a13825
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,10 @@ enabled = true
Note: we assume that all requires are **pure** with no side effects. It is not recommended to use this feature if the ordering of your requires matter.
+- Added support for [EditorConfig](https://editorconfig.org/), which is taken into account only if no `stylua.toml` was found.
+
+This feature is enabled by default, it can be disabled using `--no-editorconfig`.
+
## [0.16.1] - 2023-02-10
### Fixed
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -294,6 +294,12 @@ version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56899898ce76aaf4a0f24d914c97ea6ed976d42fec6ad33fcbb0a1103e07b2b0"
+[[package]]
+name = "ec4rs"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db540f6c584d6e2960617a2b550632715bbe0a50a4d79c0f682a13da100b34eb"
+
[[package]]
name = "either"
version = "1.6.1"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -926,6 +932,7 @@ dependencies = [
"console",
"criterion",
"crossbeam-channel",
+ "ec4rs",
"env_logger",
"full_moon",
"globset",
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -23,13 +23,14 @@ path = "src/cli/main.rs"
bench = false
[features]
-default = ["wasm-bindgen"]
+default = ["editorconfig", "wasm-bindgen"]
serialize = []
fromstr = ["strum"]
luau = ["full_moon/roblox"]
lua52 = ["full_moon/lua52"]
lua53 = ["lua52", "full_moon/lua53"]
lua54 = ["lua53", "full_moon/lua54"]
+editorconfig = ["ec4rs"]
[dependencies]
anyhow = "1.0.53"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -37,6 +38,7 @@ cfg-if = "1.0.0"
clap = { version = "3.1.6", features = ["derive"] }
console = "0.15.0"
crossbeam-channel = "0.5.4"
+ec4rs = { version = "1.0.1", optional = true }
env_logger = { version = "0.9.0", default-features = false }
full_moon = "0.17.0"
globset = "0.4.8"
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -208,7 +208,9 @@ StyLua is **opinionated**, so only a few options are provided.
### Finding the configuration
The CLI looks for `stylua.toml` or `.stylua.toml` in the directory where the tool was executed.
-If not found, the default configuration is used.
+If not found, we search for an `.editorconfig` file, otherwise fall back to the default configuration.
+This feature can be disabled using `--no-editorconfig`.
+See [EditorConfig](https://editorconfig.org/) for more details.
A custom path can be provided using `--config-path <path>`.
If the path provided is not found/malformed, StyLua will exit with an error.
diff --git a/src/cli/config.rs b/src/cli/config.rs
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -106,14 +106,14 @@ fn search_config_locations() -> Result<Option<Config>> {
Ok(None)
}
-pub fn load_config(opt: &Opt) -> Result<Config> {
+pub fn load_config(opt: &Opt) -> Result<Option<Config>> {
match &opt.config_path {
Some(config_path) => {
debug!(
"config: explicit config path provided at {}",
config_path.display()
);
- read_config_file(config_path)
+ read_config_file(config_path).map(Some)
}
None => {
let current_dir = match &opt.stdin_filepath {
diff --git a/src/cli/config.rs b/src/cli/config.rs
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -123,6 +123,7 @@ pub fn load_config(opt: &Opt) -> Result<Config> {
.to_path_buf(),
None => env::current_dir().context("Could not find current directory")?,
};
+
debug!(
"config: starting config search from {} - recursively searching parents: {}",
current_dir.display(),
diff --git a/src/cli/config.rs b/src/cli/config.rs
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -130,20 +131,20 @@ pub fn load_config(opt: &Opt) -> Result<Config> {
);
let config = find_config_file(current_dir, opt.search_parent_directories)?;
match config {
- Some(config) => Ok(config),
+ Some(config) => Ok(Some(config)),
None => {
debug!("config: no configuration file found");
// Search the configuration directory for a file, if necessary
if opt.search_parent_directories {
if let Some(config) = search_config_locations()? {
- return Ok(config);
+ return Ok(Some(config));
}
}
// Fallback to a default configuration
debug!("config: falling back to default config");
- Ok(Config::default())
+ Ok(None)
}
}
}
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -7,12 +7,16 @@ use serde_json::json;
use std::fs;
use std::io::{stderr, stdin, stdout, Read, Write};
use std::path::Path;
+#[cfg(feature = "editorconfig")]
+use std::path::PathBuf;
use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
use std::sync::Arc;
use std::time::Instant;
use thiserror::Error;
use threadpool::ThreadPool;
+#[cfg(feature = "editorconfig")]
+use stylua_lib::editorconfig;
use stylua_lib::{format_code, Config, OutputVerification, Range};
use crate::config::find_ignore_file_path;
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -245,7 +249,10 @@ fn format(opt: opt::Opt) -> Result<i32> {
}
// Load the configuration
- let config = config::load_config(&opt)?;
+ let loaded = config::load_config(&opt)?;
+ #[cfg(feature = "editorconfig")]
+ let is_default_config = loaded.is_none();
+ let config = loaded.unwrap_or_default();
// Handle any configuration overrides provided by options
let config = config::load_overrides(config, &opt);
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -404,25 +411,49 @@ fn format(opt: opt::Opt) -> Result<i32> {
};
pool.execute(move || {
+ #[cfg(not(feature = "editorconfig"))]
+ let used_config = Ok(config);
+ #[cfg(feature = "editorconfig")]
+ let used_config = match is_default_config && !&opt.no_editorconfig {
+ true => {
+ let path = match &opt.stdin_filepath {
+ Some(filepath) => filepath.to_path_buf(),
+ None => PathBuf::from("*.lua"),
+ };
+ editorconfig::parse(config, &path)
+ .context("could not parse editorconfig")
+ }
+ false => Ok(config),
+ };
+
let mut buf = String::new();
- match stdin().read_to_string(&mut buf) {
- Ok(_) => tx.send(format_string(
- buf,
- config,
- range,
- &opt,
- verify_output,
- should_skip_format,
- )),
- Err(error) => tx.send(
- Err(ErrorFileWrapper {
- file: "stdin".to_string(),
- error: error.into(),
+ tx.send(
+ used_config
+ .and_then(|used_config| {
+ stdin()
+ .read_to_string(&mut buf)
+ .map_err(|err| err.into())
+ .and_then(|_| {
+ format_string(
+ buf,
+ used_config,
+ range,
+ &opt,
+ verify_output,
+ should_skip_format,
+ )
+ .context("could not format from stdin")
+ })
})
- .context("could not format from stdin"),
- ),
- }
- .unwrap();
+ .map_err(|error| {
+ ErrorFileWrapper {
+ file: "stdin".to_string(),
+ error,
+ }
+ .into()
+ }),
+ )
+ .unwrap()
});
} else {
let path = entry.path().to_owned(); // TODO: stop to_owned?
diff --git a/src/cli/main.rs b/src/cli/main.rs
--- a/src/cli/main.rs
+++ b/src/cli/main.rs
@@ -447,16 +478,27 @@ fn format(opt: opt::Opt) -> Result<i32> {
let tx = tx.clone();
pool.execute(move || {
+ #[cfg(not(feature = "editorconfig"))]
+ let used_config = Ok(config);
+ #[cfg(feature = "editorconfig")]
+ let used_config = match is_default_config && !&opt.no_editorconfig {
+ true => editorconfig::parse(config, &path)
+ .context("could not parse editorconfig"),
+ false => Ok(config),
+ };
+
tx.send(
- format_file(&path, config, range, &opt, verify_output).map_err(
- |error| {
+ used_config
+ .and_then(|used_config| {
+ format_file(&path, used_config, range, &opt, verify_output)
+ })
+ .map_err(|error| {
ErrorFileWrapper {
file: path.display().to_string(),
error,
}
.into()
- },
- ),
+ }),
)
.unwrap()
});
diff --git a/src/cli/opt.rs b/src/cli/opt.rs
--- a/src/cli/opt.rs
+++ b/src/cli/opt.rs
@@ -94,6 +94,13 @@ pub struct Opt {
/// Whether to traverse hidden files/directories.
#[structopt(short, long)]
pub allow_hidden: bool,
+
+ /// Disables the EditorConfig feature.
+ ///
+ /// Has no effect if a stylua.toml configuration file is found.
+ #[cfg(feature = "editorconfig")]
+ #[structopt(long)]
+ pub no_editorconfig: bool,
}
#[derive(ArgEnum, Clone, Copy, Debug, PartialEq, Eq)]
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -7,6 +7,8 @@ use wasm_bindgen::prelude::*;
#[macro_use]
mod context;
+#[cfg(feature = "editorconfig")]
+pub mod editorconfig;
mod formatters;
mod shape;
pub mod sort_requires;
|
diff --git a/.gitattributes b/.gitattributes
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,3 +1,3 @@
* text=auto
*.lua text eol=lf
-tests/inputs/* linguist-vendored
\ No newline at end of file
+tests/inputs/* linguist-vendored
diff --git /dev/null b/src/editorconfig.rs
new file mode 100644
--- /dev/null
+++ b/src/editorconfig.rs
@@ -0,0 +1,408 @@
+use crate::{
+ CallParenType, CollapseSimpleStatement, Config, IndentType, LineEndings, QuoteStyle,
+ SortRequiresConfig,
+};
+use ec4rs::{
+ properties_of,
+ property::{EndOfLine, IndentSize, IndentStyle, MaxLineLen, TabWidth, UnknownValueError},
+ rawvalue::RawValue,
+ Error, Properties, PropertyKey, PropertyValue,
+};
+use std::path::Path;
+
+// Extracted from ec4rs::property
+macro_rules! property_choice {
+ ($prop_id:ident, $name:literal; $(($variant:ident, $string:literal)),+) => {
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
+ #[repr(u8)]
+ pub enum $prop_id {$($variant),+}
+
+ impl PropertyValue for $prop_id {
+ const MAYBE_UNSET: bool = false;
+ type Err = UnknownValueError;
+ fn parse(raw: &RawValue) -> Result<Self, Self::Err> {
+ match raw.into_str().to_lowercase().as_str() {
+ $($string => Ok($prop_id::$variant),)+
+ _ => Err(UnknownValueError)
+ }
+ }
+ }
+
+ impl From<$prop_id> for RawValue {
+ fn from(val: $prop_id) -> RawValue {
+ match val {
+ $($prop_id::$variant => RawValue::from($string)),*
+ }
+ }
+ }
+
+ impl PropertyKey for $prop_id {
+ fn key() -> &'static str {$name}
+ }
+
+ impl std::fmt::Display for $prop_id {
+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ write!(f, "{}", match self {
+ $($prop_id::$variant => $string),*
+ })
+ }
+ }
+ }
+}
+
+property_choice! {
+ QuoteTypeChoice, "quote_type";
+ (Double, "double"),
+ (Single, "single"),
+ (Auto, "auto")
+}
+
+property_choice! {
+ CallParenthesesChoice, "call_parentheses";
+ (Always, "always"),
+ (NoSingleString, "nosinglestring"),
+ (NoSingleTable, "nosingletable"),
+ (None, "none")
+}
+
+property_choice! {
+ CollapseSimpleStatementChoice, "collapse_simple_statement";
+ (Never, "never"),
+ (FunctionOnly, "functiononly"),
+ (ConditionalOnly, "conditionalonly"),
+ (Always, "always")
+}
+
+property_choice! {
+ SortRequiresChoice, "sort_requires";
+ (True, "true"),
+ (False, "false")
+}
+
+// Override StyLua config with EditorConfig properties
+fn load(mut config: Config, properties: &Properties) -> Config {
+ if let Ok(end_of_line) = properties.get::<EndOfLine>() {
+ config = match end_of_line {
+ EndOfLine::Cr | EndOfLine::Lf => config.with_line_endings(LineEndings::Unix),
+ EndOfLine::CrLf => config.with_line_endings(LineEndings::Windows),
+ }
+ }
+ if let Ok(indent_size) = properties.get::<IndentSize>() {
+ config = match indent_size {
+ IndentSize::Value(indent_width) => config.with_indent_width(indent_width),
+ IndentSize::UseTabWidth => {
+ properties
+ .get::<TabWidth>()
+ .map_or(config, |tab_width| match tab_width {
+ TabWidth::Value(indent_width) => config.with_indent_width(indent_width),
+ })
+ }
+ }
+ }
+ if let Ok(indent_style) = properties.get::<IndentStyle>() {
+ config = match indent_style {
+ IndentStyle::Tabs => config.with_indent_type(IndentType::Tabs),
+ IndentStyle::Spaces => config.with_indent_type(IndentType::Spaces),
+ }
+ }
+ if let Ok(max_line_length) = properties.get::<MaxLineLen>() {
+ config = match max_line_length {
+ MaxLineLen::Value(column_width) => config.with_column_width(column_width),
+ MaxLineLen::Off => config.with_column_width(usize::MAX),
+ }
+ }
+ if let Ok(quote_type) = properties.get::<QuoteTypeChoice>() {
+ config = match quote_type {
+ QuoteTypeChoice::Double => config.with_quote_style(QuoteStyle::AutoPreferDouble),
+ QuoteTypeChoice::Single => config.with_quote_style(QuoteStyle::AutoPreferSingle),
+ QuoteTypeChoice::Auto => config,
+ }
+ }
+ if let Ok(call_parentheses) = properties.get::<CallParenthesesChoice>() {
+ config = match call_parentheses {
+ CallParenthesesChoice::Always => config.with_call_parentheses(CallParenType::Always),
+ CallParenthesesChoice::NoSingleString => {
+ config.with_call_parentheses(CallParenType::NoSingleString)
+ }
+ CallParenthesesChoice::NoSingleTable => {
+ config.with_call_parentheses(CallParenType::NoSingleTable)
+ }
+ CallParenthesesChoice::None => config.with_call_parentheses(CallParenType::None),
+ }
+ }
+ if let Ok(collapse_simple_statement) = properties.get::<CollapseSimpleStatementChoice>() {
+ config = match collapse_simple_statement {
+ CollapseSimpleStatementChoice::Never => {
+ config.with_collapse_simple_statement(CollapseSimpleStatement::Never)
+ }
+ CollapseSimpleStatementChoice::FunctionOnly => {
+ config.with_collapse_simple_statement(CollapseSimpleStatement::FunctionOnly)
+ }
+ CollapseSimpleStatementChoice::ConditionalOnly => {
+ config.with_collapse_simple_statement(CollapseSimpleStatement::ConditionalOnly)
+ }
+ CollapseSimpleStatementChoice::Always => {
+ config.with_collapse_simple_statement(CollapseSimpleStatement::Always)
+ }
+ }
+ }
+ if let Ok(sort_requires) = properties.get::<SortRequiresChoice>() {
+ config = match sort_requires {
+ SortRequiresChoice::True => {
+ config.with_sort_requires(SortRequiresConfig { enabled: true })
+ }
+ SortRequiresChoice::False => {
+ config.with_sort_requires(SortRequiresConfig { enabled: false })
+ }
+ }
+ }
+
+ config
+}
+
+// Read the EditorConfig files that would apply to a file at the given path
+pub fn parse(config: Config, path: &Path) -> Result<Config, Error> {
+ let properties = properties_of(path)?;
+
+ if properties.iter().count() == 0 {
+ return Ok(config);
+ }
+
+ log::debug!("editorconfig: found properties for {}", path.display());
+ let new_config = load(config, &properties);
+
+ Ok(new_config)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ impl From<&Properties> for Config {
+ fn from(properties: &Properties) -> Self {
+ load(Config::default(), properties)
+ }
+ }
+
+ #[test]
+ fn test_end_of_line_cr() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("end_of_line", "CR");
+ let config = Config::from(&properties);
+ assert_eq!(config.line_endings(), LineEndings::Unix);
+ }
+
+ #[test]
+ fn test_end_of_line_lf() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("end_of_line", "lf");
+ let config = Config::from(&properties);
+ assert_eq!(config.line_endings(), LineEndings::Unix);
+ }
+
+ #[test]
+ fn test_end_of_line_crlf() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("end_of_line", "CrLf");
+ let config = Config::from(&properties);
+ assert_eq!(config.line_endings(), LineEndings::Windows);
+ }
+
+ #[test]
+ fn test_indent_size() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("indent_size", "2");
+ let config = Config::from(&properties);
+ assert_eq!(config.indent_width(), 2);
+ }
+
+ #[test]
+ fn test_indent_size_use_tab_width() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("tab_width", "8");
+ properties.insert_raw_for_key("indent_size", "tab");
+ let config = Config::from(&properties);
+ assert_eq!(config.indent_width(), 8);
+ }
+
+ #[test]
+ fn test_indent_style_space() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("indent_style", "space");
+ let config = Config::from(&properties);
+ assert_eq!(config.indent_type(), IndentType::Spaces);
+ }
+
+ #[test]
+ fn test_indent_style_tab() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("indent_style", "Tab");
+ let config = Config::from(&properties);
+ assert_eq!(config.indent_type(), IndentType::Tabs);
+ }
+
+ #[test]
+ fn test_max_line_length() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("max_line_length", "80");
+ let config = Config::from(&properties);
+ assert_eq!(config.column_width(), 80);
+ }
+
+ #[test]
+ fn test_max_line_length_off() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("max_line_length", "off");
+ let config = Config::from(&properties);
+ assert_eq!(config.column_width(), usize::MAX);
+ }
+
+ #[test]
+ fn test_quote_type_double() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("quote_type", "double");
+ let config = Config::from(&properties);
+ assert_eq!(config.quote_style(), QuoteStyle::AutoPreferDouble);
+ }
+
+ #[test]
+ fn test_quote_type_single() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("quote_type", "Single");
+ let config = Config::from(&properties);
+ assert_eq!(config.quote_style(), QuoteStyle::AutoPreferSingle);
+ }
+
+ #[test]
+ fn test_quote_type_auto() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("quote_type", "auto");
+ let config = Config::from(&properties);
+ assert_eq!(config.quote_style(), QuoteStyle::AutoPreferDouble);
+ }
+
+ #[test]
+ fn test_call_parentheses_always() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("call_parentheses", "always");
+ let config = Config::from(&properties);
+ assert_eq!(config.call_parentheses(), CallParenType::Always);
+ }
+
+ #[test]
+ fn test_call_parentheses_no_single_string() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("call_parentheses", "NoSingleString");
+ let config = Config::from(&properties);
+ assert_eq!(config.call_parentheses(), CallParenType::NoSingleString);
+ }
+
+ #[test]
+ fn test_call_parentheses_no_single_table() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("call_parentheses", "NoSingleTable");
+ let config = Config::from(&properties);
+ assert_eq!(config.call_parentheses(), CallParenType::NoSingleTable);
+ }
+
+ #[test]
+ fn test_call_parentheses_none() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("call_parentheses", "None");
+ let config = Config::from(&properties);
+ assert_eq!(config.call_parentheses(), CallParenType::None);
+ }
+
+ #[test]
+ fn test_collapse_simple_statement_never() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("collapse_simple_statement", "Never");
+ let config = Config::from(&properties);
+ assert_eq!(
+ config.collapse_simple_statement(),
+ CollapseSimpleStatement::Never
+ );
+ }
+
+ #[test]
+ fn test_collapse_simple_statement_function_only() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("collapse_simple_statement", "FunctionOnly");
+ let config = Config::from(&properties);
+ assert_eq!(
+ config.collapse_simple_statement(),
+ CollapseSimpleStatement::FunctionOnly
+ );
+ }
+
+ #[test]
+ fn test_collapse_simple_statement_conditional_only() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("collapse_simple_statement", "ConditionalOnly");
+ let config = Config::from(&properties);
+ assert_eq!(
+ config.collapse_simple_statement(),
+ CollapseSimpleStatement::ConditionalOnly
+ );
+ }
+
+ #[test]
+ fn test_collapse_simple_statement_always() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("collapse_simple_statement", "always");
+ let config = Config::from(&properties);
+ assert_eq!(
+ config.collapse_simple_statement(),
+ CollapseSimpleStatement::Always
+ );
+ }
+
+ #[test]
+ fn test_sort_requires_enabled() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("sort_requires", "true");
+ let config = Config::from(&properties);
+ assert!(config.sort_requires().enabled);
+ }
+
+ #[test]
+ fn test_sort_requires_disabled() {
+ let mut properties = Properties::new();
+ properties.insert_raw_for_key("sort_requires", "false");
+ let config = Config::from(&properties);
+ assert!(!config.sort_requires().enabled);
+ }
+
+ #[test]
+ fn test_invalid_properties() {
+ let mut properties = Properties::new();
+ let default_config = Config::new();
+ let invalid_value = " ";
+ for key in [
+ "end_of_line",
+ "indent_size",
+ "indent_style",
+ "quote_style",
+ "call_parentheses",
+ "collapse_simple_statement",
+ "sort_requires",
+ ] {
+ properties.insert_raw_for_key(key, invalid_value);
+ }
+ let config = Config::from(&properties);
+ assert_eq!(config.line_endings, default_config.line_endings);
+ assert_eq!(config.indent_width, default_config.indent_width);
+ assert_eq!(config.indent_type, default_config.indent_type);
+ assert_eq!(config.column_width, default_config.column_width);
+ assert_eq!(config.quote_style, default_config.quote_style);
+ assert_eq!(config.call_parentheses, default_config.call_parentheses);
+ assert_eq!(
+ config.collapse_simple_statement,
+ default_config.collapse_simple_statement
+ );
+ assert_eq!(
+ config.sort_requires.enabled,
+ default_config.sort_requires.enabled
+ );
+ }
+}
diff --git /dev/null b/tests/inputs-editorconfig/.editorconfig
new file mode 100644
--- /dev/null
+++ b/tests/inputs-editorconfig/.editorconfig
@@ -0,0 +1,9 @@
+root = true
+
+[*]
+indent_style = space
+indent_size = 2
+
+[global/tab-single.lua]
+indent_style = tab
+quote_type = single
diff --git /dev/null b/tests/inputs-editorconfig/empty-root/.editorconfig
new file mode 100644
--- /dev/null
+++ b/tests/inputs-editorconfig/empty-root/.editorconfig
@@ -0,0 +1,1 @@
+root = true
diff --git /dev/null b/tests/inputs-editorconfig/empty-root/tab-double.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-editorconfig/empty-root/tab-double.lua
@@ -0,0 +1,5 @@
+local foo = {
+ a = 1,
+}
+
+local bar = ""
diff --git /dev/null b/tests/inputs-editorconfig/global/tab-single.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-editorconfig/global/tab-single.lua
@@ -0,0 +1,5 @@
+local foo = {
+ a = 1,
+}
+
+local bar = ""
diff --git /dev/null b/tests/inputs-editorconfig/local/.editorconfig
new file mode 100644
--- /dev/null
+++ b/tests/inputs-editorconfig/local/.editorconfig
@@ -0,0 +1,3 @@
+[*.lua]
+indent_style = Space
+indent_size = 4
diff --git /dev/null b/tests/inputs-editorconfig/local/space-4.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-editorconfig/local/space-4.lua
@@ -0,0 +1,5 @@
+local foo = {
+ a = 1,
+}
+
+local bar = ""
diff --git /dev/null b/tests/inputs-editorconfig/space-2.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-editorconfig/space-2.lua
@@ -0,0 +1,5 @@
+local foo = {
+ a = 1,
+}
+
+local bar = ""
diff --git /dev/null b/tests/inputs-editorconfig/stylua-toml/.editorconfig
new file mode 100644
--- /dev/null
+++ b/tests/inputs-editorconfig/stylua-toml/.editorconfig
@@ -0,0 +1,3 @@
+[*.lua]
+indent_style = tab
+quote_type = double
diff --git /dev/null b/tests/inputs-editorconfig/stylua-toml/single-space-8.lua
new file mode 100644
--- /dev/null
+++ b/tests/inputs-editorconfig/stylua-toml/single-space-8.lua
@@ -0,0 +1,5 @@
+local foo = {
+ a = 1,
+}
+
+local bar = ""
diff --git /dev/null b/tests/inputs-editorconfig/stylua-toml/stylua.toml
new file mode 100644
--- /dev/null
+++ b/tests/inputs-editorconfig/stylua-toml/stylua.toml
@@ -0,0 +1,3 @@
+indent_type = "Spaces"
+indent_width = 8
+quote_style = "AutoPreferSingle"
diff --git /dev/null b/tests/snapshots/test_editorconfig__empty_root@tab-double.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/test_editorconfig__empty_root@tab-double.lua.snap
@@ -0,0 +1,10 @@
+---
+source: tests/test_editorconfig.rs
+expression: "format(&contents, path.to_str().unwrap())"
+---
+local foo = {
+ a = 1,
+}
+
+local bar = ""
+
diff --git /dev/null b/tests/snapshots/test_editorconfig__global@tab-single.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/test_editorconfig__global@tab-single.lua.snap
@@ -0,0 +1,10 @@
+---
+source: tests/test_editorconfig.rs
+expression: "format(&contents, path.to_str().unwrap())"
+---
+local foo = {
+ a = 1,
+}
+
+local bar = ''
+
diff --git /dev/null b/tests/snapshots/test_editorconfig__local@space-4.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/test_editorconfig__local@space-4.lua.snap
@@ -0,0 +1,10 @@
+---
+source: tests/test_editorconfig.rs
+expression: "format(&contents, path.to_str().unwrap())"
+---
+local foo = {
+ a = 1,
+}
+
+local bar = ""
+
diff --git /dev/null b/tests/snapshots/test_editorconfig__root@space-2.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/test_editorconfig__root@space-2.lua.snap
@@ -0,0 +1,10 @@
+---
+source: tests/test_editorconfig.rs
+expression: "format(&contents, path.to_str().unwrap())"
+---
+local foo = {
+ a = 1,
+}
+
+local bar = ""
+
diff --git /dev/null b/tests/snapshots/test_editorconfig__stylua_toml@single-space-8.lua.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/test_editorconfig__stylua_toml@single-space-8.lua.snap
@@ -0,0 +1,10 @@
+---
+source: tests/test_editorconfig.rs
+expression: "&contents"
+---
+local foo = {
+ a = 1,
+}
+
+local bar = ''
+
diff --git /dev/null b/tests/test_editorconfig.rs
new file mode 100644
--- /dev/null
+++ b/tests/test_editorconfig.rs
@@ -0,0 +1,80 @@
+#[cfg(feature = "editorconfig")]
+use {
+ std::path::Path,
+ stylua_lib::{editorconfig, format_code, Config, OutputVerification},
+};
+
+#[cfg(feature = "editorconfig")]
+fn format(input: &str, directory: &str) -> String {
+ let config = editorconfig::parse(
+ Config::default(),
+ &Path::new("tests")
+ .join("inputs-editorconfig")
+ .join(directory),
+ )
+ .unwrap();
+ format_code(input, config, None, OutputVerification::None).unwrap()
+}
+
+// EditorConfig file with the `root` key set to true
+#[test]
+#[cfg(feature = "editorconfig")]
+fn test_root() {
+ insta::glob!("inputs-editorconfig/*.lua", |path| {
+ let contents = std::fs::read_to_string(path).unwrap();
+ insta::assert_snapshot!(format(&contents, path.to_str().unwrap()));
+ })
+}
+
+// Subdirectory with an EditorConfig file
+#[test]
+#[cfg(feature = "editorconfig")]
+fn test_local() {
+ insta::glob!("inputs-editorconfig/local/*.lua", |path| {
+ let contents = std::fs::read_to_string(path).unwrap();
+ insta::assert_snapshot!(format(&contents, path.to_str().unwrap()));
+ })
+}
+
+// Subdirectory without an EditorConfig file
+#[test]
+#[cfg(feature = "editorconfig")]
+fn test_global() {
+ insta::glob!("inputs-editorconfig/global/*.lua", |path| {
+ let contents = std::fs::read_to_string(path).unwrap();
+ insta::assert_snapshot!(format(&contents, path.to_str().unwrap()));
+ })
+}
+
+// Subdirectory with an empty configuration should use defaults
+#[test]
+#[cfg(feature = "editorconfig")]
+fn test_empty_root() {
+ insta::glob!("inputs-editorconfig/empty-root/*.lua", |path| {
+ let contents = std::fs::read_to_string(path).unwrap();
+ insta::assert_snapshot!(format(&contents, path.to_str().unwrap()));
+ })
+}
+
+// Subdirectory with a StyLua configuration file
+#[test]
+#[cfg(feature = "editorconfig")]
+fn test_stylua_toml() {
+ insta::glob!("inputs-editorconfig/stylua-toml/*.lua", |path| {
+ // Save file contents
+ let original = std::fs::read_to_string(path).unwrap();
+ let result = std::panic::catch_unwind(|| {
+ let mut cmd = assert_cmd::Command::cargo_bin(env!("CARGO_PKG_NAME")).unwrap();
+ cmd.arg("--config-path")
+ .arg("tests/inputs-editorconfig/stylua-toml/stylua.toml")
+ .arg(path)
+ .assert()
+ .success();
+ std::fs::read_to_string(path).unwrap()
+ });
+ // Restore file contents
+ std::fs::write(path, original).unwrap();
+ let contents = result.unwrap();
+ insta::assert_snapshot!(&contents);
+ })
+}
|
[Suggestion] Support .editorconfig
Given that [.editorconfig file](https://editorconfig.org/) provides some settings that are supported by stylua, it could be handy to read that file to avoid duplicating these settings.
|
I believe the way prettier does this is to allow an option to defer to the `.editorconfig` file. Would probably be a good option here as well.
Interesting idea, which might be nice to have.
I think I'll most likely support project-level editorconfig, rather than a global one, so that it is more noticeable what kind of settings are being used.
>
>
> I believe the way prettier does this is to allow an option to defer to the `.editorconfig` file. Would probably be a good option here as well.
editorconfig provides libraries for several languages, so prettier probably used the one for js.
There seems to be a relatively new crate for parsing .editorconfig files which looks promising: https://github.com/TheDaemoness/ec4rs
This issue hasn't really been tackled yet since there wasn't great support for editorconfig files
|
2023-02-04T22:22:18Z
|
0.16
|
2023-11-20T17:38:32Z
|
12d3f3d31b203d90d615183d6ac356b3cb71b913
|
[
"test_lua54"
] |
[
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments_2",
"formatters::trivia_util::tests::test_token_contains_singleline_comments",
"sort_requires::tests::fail_extracting_non_identifier_token",
"tests::test_config_call_parentheses",
"tests::test_config_indent_width",
"tests::test_config_indent_type",
"tests::test_config_column_width",
"tests::test_config_line_endings",
"tests::test_config_quote_style",
"sort_requires::tests::get_expression_kind_other_2",
"sort_requires::tests::get_expression_kind_other_1",
"sort_requires::tests::get_expression_kind_other_4",
"sort_requires::tests::get_expression_kind_other_6",
"sort_requires::tests::get_expression_kind_other_3",
"sort_requires::tests::get_expression_kind_get_service",
"sort_requires::tests::get_expression_kind_other_5",
"tests::test_invalid_input",
"sort_requires::tests::get_expression_kind_require_stmt",
"tests::test_entry_point",
"verify_ast::tests::test_different_asts",
"verify_ast::tests::test_equivalent_asts",
"verify_ast::tests::test_different_hex_numbers",
"verify_ast::tests::test_different_binary_numbers",
"verify_ast::tests::test_equivalent_binary_numbers",
"tests::test_with_ast_verification",
"verify_ast::tests::test_equivalent_conditions",
"verify_ast::tests::test_equivalent_numbers",
"verify_ast::tests::test_equivalent_stmt_semicolons",
"verify_ast::tests::test_equivalent_string_quote_types",
"verify_ast::tests::test_equivalent_string_escapes",
"verify_ast::tests::test_equivalent_types_removed_parentheses",
"verify_ast::tests::test_equivalent_numbers_2",
"verify_ast::tests::test_equivalent_function_calls",
"verify_ast::tests::test_equivalent_hex_numbers",
"verify_ast::tests::test_equivalent_function_calls_2",
"verify_ast::tests::test_equivalent_table_separators",
"output_diff::tests::test_deletion_diff",
"output_diff::tests::test_addition_diff",
"output_diff::tests::test_no_diff",
"output_diff::tests::test_change_diff",
"opt::tests::verify_opt",
"config::tests::test_override_line_endings",
"config::tests::test_override_quote_style",
"config::tests::test_override_call_parentheses",
"config::tests::test_override_column_width",
"config::tests::test_override_indent_type",
"config::tests::test_override_indent_width",
"tests::test_no_files_provided",
"tests::test_format_stdin",
"test_call_parens_comments",
"test_call_parens_semicolons",
"test_call_parens_no_single_string_handles_string_correctly",
"test_call_parens_none_handles_string_correctly",
"test_call_parens_always_handles_table_correctly",
"test_call_parens_always_handles_string_correctly",
"test_call_parens_no_single_table_handles_string_correctly",
"test_call_parens_no_single_string_handles_table_correctly",
"test_call_parens_none_handles_table_correctly",
"test_call_parens_no_single_table_handles_table_correctly",
"test_call_parens_has_no_affect_on_multi_arg_fn_calls_",
"test_no_parens_brackets_string",
"test_omit_parens_brackets_string",
"test_no_parens_multiline_table",
"test_no_parens_singleline_table",
"test_omit_parens_string",
"test_no_parens_string",
"test_no_parens_method_chain_1",
"test_keep_parens_binop_string",
"test_no_parens_method_chain_2",
"test_no_parens_large_example",
"test_auto_prefer_single_quotes",
"test_force_single_quotes",
"test_force_double_quotes",
"test_auto_prefer_double_quotes",
"test_ignore_last_stmt",
"test_dont_modify_eof",
"test_nested_range_do",
"test_incomplete_range",
"test_nested_range_generic_for",
"test_default",
"test_nested_range_function_call",
"test_nested_range_else_if",
"test_nested_range_function_call_table",
"test_nested_range",
"test_nested_range_binop",
"test_large_example",
"test_no_range_end",
"test_no_range_start",
"test_nested_range_repeat",
"test_nested_range_while",
"test_nested_range_table_1",
"test_nested_range_table_2",
"test_nested_range_local_function",
"test_collapse_single_statement_lua_52",
"test_lua53",
"test_lua52",
"test_ignores",
"test_sort_requires",
"test_luau_full_moon",
"test_collapse_single_statement",
"test_luau"
] |
[] |
[] |
JohnnyMorganz/StyLua
| 631
|
JohnnyMorganz__StyLua-631
|
[
"618"
] |
3699358f0ceebe6651789cff25f289d3ac84c937
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Unnecessary parentheses around Luau types will now be removed ([#611](https://github.com/JohnnyMorganz/StyLua/issues/611))
+- Collapse a body containing only a `goto` statement when `collapse_simple_statement` is set ([#618](https://github.com/JohnnyMorganz/StyLua/issues/618))
## [0.15.3] - 2022-12-07
diff --git a/src/formatters/lua52.rs b/src/formatters/lua52.rs
--- a/src/formatters/lua52.rs
+++ b/src/formatters/lua52.rs
@@ -24,6 +24,13 @@ pub fn format_goto(ctx: &Context, goto: &Goto, shape: Shape) -> Goto {
Goto::new(label_name).with_goto_token(goto_token)
}
+pub fn format_goto_no_trivia(ctx: &Context, goto: &Goto, shape: Shape) -> Goto {
+ let goto_token = fmt_symbol!(ctx, goto.goto_token(), "goto ", shape);
+ let label_name = format_token_reference(ctx, goto.label_name(), shape);
+
+ Goto::new(label_name).with_goto_token(goto_token)
+}
+
pub fn format_label(ctx: &Context, label: &Label, shape: Shape) -> Label {
// Calculate trivia
let leading_trivia = vec![create_indent_trivia(ctx, shape)];
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -1,5 +1,5 @@
#[cfg(feature = "lua52")]
-use crate::formatters::lua52::{format_goto, format_label};
+use crate::formatters::lua52::{format_goto, format_goto_no_trivia, format_label};
#[cfg(feature = "luau")]
use crate::formatters::luau::{
format_compound_assignment, format_exported_type_declaration, format_type_declaration_stmt,
diff --git a/src/formatters/stmt.rs b/src/formatters/stmt.rs
--- a/src/formatters/stmt.rs
+++ b/src/formatters/stmt.rs
@@ -1117,6 +1117,8 @@ pub fn format_stmt_no_trivia(ctx: &Context, stmt: &Stmt, shape: Shape) -> Stmt {
}
Stmt::Assignment(stmt) => Stmt::Assignment(format_assignment_no_trivia(ctx, stmt, shape)),
Stmt::FunctionCall(stmt) => Stmt::FunctionCall(format_function_call(ctx, stmt, shape)),
- _ => unreachable!("format_stmt_no_trivia: node != assignment/function call"),
+ #[cfg(feature = "lua52")]
+ Stmt::Goto(goto) => Stmt::Goto(format_goto_no_trivia(ctx, goto, shape)),
+ _ => unreachable!("format_stmt_no_trivia: node != assignment/function call/goto"),
}
}
diff --git a/src/formatters/trivia_util.rs b/src/formatters/trivia_util.rs
--- a/src/formatters/trivia_util.rs
+++ b/src/formatters/trivia_util.rs
@@ -100,6 +100,8 @@ pub fn is_block_simple(block: &Block) -> bool {
true
}
Stmt::FunctionCall(_) => true,
+ #[cfg(feature = "lua52")]
+ Stmt::Goto(_) => true,
_ => false,
})
}
|
diff --git a/tests/tests.rs b/tests/tests.rs
--- a/tests/tests.rs
+++ b/tests/tests.rs
@@ -89,3 +89,25 @@ fn test_collapse_single_statement() {
.unwrap());
})
}
+
+// Collapse simple statement for goto
+#[test]
+#[cfg(feature = "lua52")]
+fn test_collapse_single_statement_lua_52() {
+ insta::assert_snapshot!(
+ format_code(
+ r###"
+ if key == "s" then
+ goto continue
+ end
+ "###,
+ Config::default().with_collapse_simple_statement(CollapseSimpleStatement::Always),
+ None,
+ OutputVerification::None
+ )
+ .unwrap(),
+ @r###"
+ if key == "s" then goto continue end
+ "###
+ );
+}
|
`collapse_simple_statement` for goto
using `collapse_simple_statement = "Always"`:
```lua
-- won't collapse
if key == "s" then
goto continue
end
-- on the other hand something like this does collapse
local modes = { "n", "v" }
if key == "p" then modes = { "n" } end
-- ...
```
|
2022-12-18T22:08:23Z
|
0.15
|
2023-01-04T20:16:33Z
|
540ecfb832e3bccf86e0e037b9c855aa464fc4e7
|
[
"test_collapse_single_statement_lua_52",
"test_lua54"
] |
[
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments",
"formatters::trivia_util::tests::test_token_contains_no_singleline_comments_2",
"formatters::trivia_util::tests::test_token_contains_singleline_comments",
"tests::test_config_call_parentheses",
"tests::test_config_column_width",
"tests::test_config_indent_type",
"tests::test_config_indent_width",
"tests::test_config_line_endings",
"tests::test_config_quote_style",
"tests::test_invalid_input",
"verify_ast::tests::test_different_asts",
"verify_ast::tests::test_equivalent_asts",
"verify_ast::tests::test_equivalent_hex_numbers",
"verify_ast::tests::test_different_hex_numbers",
"verify_ast::tests::test_different_binary_numbers",
"tests::test_entry_point",
"verify_ast::tests::test_equivalent_binary_numbers",
"verify_ast::tests::test_equivalent_conditions",
"tests::test_with_ast_verification",
"verify_ast::tests::test_equivalent_function_calls",
"verify_ast::tests::test_equivalent_stmt_semicolons",
"verify_ast::tests::test_equivalent_numbers",
"verify_ast::tests::test_equivalent_string_quote_types",
"verify_ast::tests::test_equivalent_numbers_2",
"verify_ast::tests::test_equivalent_string_escapes",
"verify_ast::tests::test_equivalent_function_calls_2",
"verify_ast::tests::test_equivalent_table_separators",
"output_diff::tests::test_addition_diff",
"output_diff::tests::test_no_diff",
"output_diff::tests::test_deletion_diff",
"output_diff::tests::test_change_diff",
"config::tests::test_override_indent_width",
"config::tests::test_override_call_parentheses",
"config::tests::test_override_indent_type",
"config::tests::test_override_quote_style",
"opt::tests::verify_opt",
"config::tests::test_override_column_width",
"config::tests::test_override_line_endings",
"tests::test_no_files_provided",
"tests::test_format_stdin",
"test_call_parens_comments",
"test_call_parens_semicolons",
"test_call_parens_no_single_string_handles_string_correctly",
"test_call_parens_none_handles_string_correctly",
"test_call_parens_no_single_table_handles_string_correctly",
"test_call_parens_always_handles_string_correctly",
"test_call_parens_always_handles_table_correctly",
"test_call_parens_no_single_string_handles_table_correctly",
"test_call_parens_none_handles_table_correctly",
"test_call_parens_no_single_table_handles_table_correctly",
"test_call_parens_has_no_affect_on_multi_arg_fn_calls_",
"test_no_parens_brackets_string",
"test_omit_parens_brackets_string",
"test_no_parens_multiline_table",
"test_no_parens_singleline_table",
"test_no_parens_string",
"test_omit_parens_string",
"test_keep_parens_binop_string",
"test_no_parens_method_chain_1",
"test_no_parens_method_chain_2",
"test_no_parens_large_example",
"test_auto_prefer_double_quotes",
"test_force_single_quotes",
"test_force_double_quotes",
"test_auto_prefer_single_quotes",
"test_incomplete_range",
"test_nested_range_do",
"test_ignore_last_stmt",
"test_dont_modify_eof",
"test_default",
"test_nested_range_generic_for",
"test_nested_range_function_call",
"test_nested_range_else_if",
"test_nested_range_function_call_table",
"test_nested_range",
"test_nested_range_binop",
"test_no_range_end",
"test_no_range_start",
"test_nested_range_while",
"test_nested_range_repeat",
"test_nested_range_table_1",
"test_nested_range_local_function",
"test_nested_range_table_2",
"test_large_example",
"test_lua53",
"test_lua52",
"test_ignores",
"test_luau_full_moon",
"test_collapse_single_statement",
"test_luau"
] |
[] |
[] |
|
Zokrates/ZoKrates
| 101
|
Zokrates__ZoKrates-101
|
[
"38"
] |
97c2a30e59a799e06344b5553554768c868e0ae9
|
diff --git /dev/null b/examples/left_side_call.code
new file mode 100644
--- /dev/null
+++ b/examples/left_side_call.code
@@ -0,0 +1,6 @@
+def foo():
+ return 1
+
+def main():
+ foo() + (1 + 44*3) == 1
+ return 1
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -879,6 +879,41 @@ fn parse_statement1<T: Field>(
},
Err(err) => Err(err)
},
+ (Token::Open, s1, p1) => match parse_function_call(ide, s1, p1) {
+ Ok((e3, s3, p3)) => match next_token(&s3, &p3) {
+ (Token::Eqeq, s4, p4) => match parse_expr(&s4, &p4) {
+ Ok((e5, s5, p5)) => match next_token(&s5, &p5) {
+ (Token::InlineComment(_), ref s6, _) => {
+ assert_eq!(s6, "");
+ Ok((Statement::Condition(e3, e5), s5, p5))
+ }
+ (Token::Unknown(ref t6), ref s6, _) if t6 == "" => {
+ assert_eq!(s6, "");
+ Ok((Statement::Condition(e3, e5), s5, p5))
+ }
+ (t6, _, p6) => Err(Error {
+ expected: vec![
+ Token::Add,
+ Token::Sub,
+ Token::Pow,
+ Token::Mult,
+ Token::Div,
+ Token::Unknown("".to_string()),
+ ],
+ got: t6,
+ pos: p6,
+ }),
+ },
+ Err(err) => Err(err),
+ },
+ (t4, _, p4) => Err(Error {
+ expected: vec![Token::Eqeq],
+ got: t4,
+ pos: p4,
+ }),
+ },
+ Err(err) => Err(err)
+ },
_ => match parse_term1(Expression::Identifier(ide), input, pos) {
Ok((e2, s2, p2)) => match parse_expr1(e2, s2, p2) {
Ok((e3, s3, p3)) => match next_token(&s3, &p3) {
|
diff --git a/src/parser.rs b/src/parser.rs
--- a/src/parser.rs
+++ b/src/parser.rs
@@ -1592,6 +1627,22 @@ mod tests {
}
}
+ mod parse_statement1 {
+ use super::*;
+ #[test]
+ fn left_call_in_assertion() {
+ let pos = Position { line: 45, col: 121 };
+ let string = String::from("() == 1");
+ let cond = Statement::Condition(
+ Expression::FunctionCall(String::from("foo"), vec![]),
+ Expression::Number(FieldPrime::from(1))
+ );
+ assert_eq!(Ok((cond, String::from(""), pos.col(string.len() as isize))),
+ parse_statement1(String::from("foo"), string, pos)
+ );
+ }
+ }
+
// parse_ide
// skip_whitespaces
// next_token
|
Inline constraints cannot take function calls as left expression
```
foo() == 1 // syntax error
1 == foo() // OK
```
|
2018-08-09T17:44:22Z
|
0.2
|
2018-09-26T12:30:47Z
|
97c2a30e59a799e06344b5553554768c868e0ae9
|
[
"parser::tests::parse_statement1::left_call_in_assertion"
] |
[
"field::tests::bigint_assertions",
"field::tests::field_prime::addition",
"field::tests::field_prime::addition_negative",
"field::tests::field_prime::dec_string_ser_deser",
"field::tests::field_prime::addition_negative_small",
"field::tests::field_prime::bytes_ser_deser",
"field::tests::field_prime::multiplication_two_negative",
"field::tests::field_prime::multiplication_negative",
"field::tests::field_prime::multiplication",
"field::tests::field_prime::positive_number",
"field::tests::field_prime::division_negative",
"field::tests::field_prime::division_two_negative",
"field::tests::field_prime::negative_number",
"field::tests::field_prime::pow_small",
"field::tests::field_prime::pow",
"field::tests::field_prime::pow_usize",
"field::tests::field_prime::division",
"field::tests::field_prime::multiplication_overflow",
"field::tests::field_prime::subtraction_overflow",
"field::tests::field_prime::subtraction",
"field::tests::field_prime::subtraction_negative",
"field::tests::test_extended_euclid",
"field::tests::field_prime::serde_ser_deser",
"helpers::tests::eq_condition::execute",
"flatten::multiple_definition::multiple_definition",
"flatten::multiple_definition::redefine_argument",
"imports::tests::create_with_no_alias",
"flatten::multiple_definition::multiple_definition2",
"parser::tests::inline_comment",
"flatten::multiple_definition::simple_definition",
"helpers::tests::eq_condition::execute_non_eq",
"parser::tests::parse_comma_separated_list::comma_separated_list_single",
"parser::tests::parse_comma_separated_list::comma_separated_list",
"parser::tests::parse_factor::ide",
"imports::tests::create_with_alias",
"field::tests::field_prime::pow_negative",
"parser::tests::parse_comma_separated_list::comma_separated_list_three",
"parser::tests::parse_imports::parse_import_test",
"parser::tests::parse_factor::num",
"parser::tests::parse_imports::import",
"parser::tests::parse_num::add",
"parser::tests::parse_imports::parse_import_with_alias_test",
"parser::tests::parse_imports::quoted_path",
"parser::tests::parse_if_then_else_ok",
"parser::tests::parse_num::space_after",
"parser::tests::parse_num::single",
"parser::tests::parse_factor::brackets",
"parser::tests::position_col",
"parser::tests::parse_factor::if_then_else",
"flatten::multiple_definition::overload",
"parser::tests::parse_num::x_before",
"parser::tests::parse_num::space_before",
"flatten::multiple_definition::if_else",
"r1cs::tests::r1cs_expression::add",
"r1cs::tests::r1cs_expression::add_mult",
"r1cs::tests::r1cs_expression::div",
"r1cs::tests::r1cs_expression::sub",
"r1cs::tests::r1cs_expression::add_sub_mix",
"semantics::tests::duplicate_function_declaration",
"semantics::tests::declared_in_other_function",
"r1cs::tests::r1cs_expression::sub_multiple",
"semantics::tests::function_undefined_in_multidef",
"semantics::tests::function_undefined",
"semantics::tests::duplicate_main_function",
"semantics::tests::declared_in_two_scopes",
"semantics::tests::for_index_after_end",
"semantics::tests::for_index_in_for",
"semantics::tests::multi_return_outside_multidef",
"semantics::tests::multi_def",
"semantics::tests::return_undefined",
"semantics::tests::undefined_variable_in_statement",
"semantics::tests::defined_variable_in_statement",
"standard::tests::deserialize_constraint",
"substitution::direct_substitution::tests::insert_simple_variable",
"substitution::direct_substitution::tests::insert_binary_variable",
"substitution::direct_substitution::tests::insert_twice_with_same_prefix",
"substitution::direct_substitution::tests::two_separators",
"semantics::tests::arity_mismatch",
"semantics::tests::undefined_variable_in_multireturn_call",
"standard::tests::constraint_into_flat_statement",
"optimizer::tests::remove_synonyms",
"optimizer::tests::remove_multiple_synonyms",
"substitution::prefixed_substitution::tests::insert_binary_variable",
"substitution::prefixed_substitution::tests::insert_twice_with_same_prefix",
"substitution::prefixed_substitution::tests::insert_simple_variable",
"tests::examples_with_input",
"tests::examples",
"integration::run_integration_tests"
] |
[] |
[] |
|
Zokrates/ZoKrates
| 97
|
Zokrates__ZoKrates-97
|
[
"96"
] |
3c36637521495d9632c8c5c524e790cf61081f6e
|
diff --git /dev/null b/examples/argument_reassign.code
new file mode 100644
--- /dev/null
+++ b/examples/argument_reassign.code
@@ -0,0 +1,6 @@
+def sub(a):
+ a = a + 3
+ return a
+
+def main():
+ return sub(4)
\ No newline at end of file
diff --git a/src/flatten.rs b/src/flatten.rs
--- a/src/flatten.rs
+++ b/src/flatten.rs
@@ -694,6 +694,7 @@ impl Flattener {
let mut statements_flattened: Vec<FlatStatement<T>> = Vec::new();
// push parameters
for arg in funct.arguments {
+ self.variables.insert(arg.id.to_string());
arguments_flattened.push(Parameter {
id: arg.id.to_string(),
private: arg.private
|
diff --git a/src/flatten.rs b/src/flatten.rs
--- a/src/flatten.rs
+++ b/src/flatten.rs
@@ -920,6 +921,48 @@ mod multiple_definition {
);
}
+ #[test]
+ fn redefine_argument() {
+
+ // def foo(a)
+ // a = a + 1
+ // return 1
+
+ // should flatten to no redefinition
+ // def foo(a)
+ // a_0 = a + 1
+ // return 1
+
+ let mut flattener = Flattener::new(FieldPrime::get_required_bits());
+ let mut functions_flattened = vec![];
+
+ let funct = Function {
+ id: "foo".to_string(),
+ arguments: vec![Parameter { id: "a".to_string(), private: true }],
+ statements: vec![
+ Statement::Definition("a".to_string(), Expression::Add(box Expression::Identifier("a".to_string()), box Expression::Number(FieldPrime::from(1)))),
+ Statement::Return(
+ ExpressionList {
+ expressions: vec![
+ Expression::Number(FieldPrime::from(1))
+ ]
+ }
+ )
+ ],
+ return_count: 1,
+ };
+
+ let flat_funct = flattener.flatten_function(
+ &mut functions_flattened,
+ funct,
+ );
+
+ assert_eq!(
+ flat_funct.statements[0],
+ FlatStatement::Definition("a_0".to_string(), FlatExpression::Add(box FlatExpression::Identifier("a".to_string()), box FlatExpression::Number(FieldPrime::from(1))))
+ );
+ }
+
#[test]
fn overload() {
|
[Runtime Crash] Cannot re-assign function parameter when it is used in assignment
Assume the following sample code
```
def sub(a):
a = a + 3
return a
def main():
a = 4
return sub(a)
```
It compiles fine, however when computing a witness it crashes with:
```
thread 'main' panicked at 'Variable "sub_i1o1_1_a" is undeclared in inputs: {"a": 4, "sub_i1o1_1_param_0": 4, "~one": 1}', src/flat_absy.rs:302:25
note: Run with `RUST_BACKTRACE=1` for a backtrace.
```
I assume it has something to do with reassigning a function parameter while also using it in the assignment. Seems like a pretty edgy case, but something that should be allowed?
Workaround was to introduce a separate variable instead of reassigning `a`.
|
2018-08-02T00:15:14Z
|
0.2
|
2018-08-03T07:51:23Z
|
97c2a30e59a799e06344b5553554768c868e0ae9
|
[
"flatten::multiple_definition::redefine_argument"
] |
[
"direct_substitution::tests::two_separators",
"direct_substitution::tests::insert_binary_variable",
"direct_substitution::tests::insert_simple_variable",
"direct_substitution::tests::insert_twice_with_same_prefix",
"field::tests::bigint_assertions",
"field::tests::field_prime::bytes_ser_deser",
"field::tests::field_prime::addition",
"field::tests::field_prime::division_negative",
"field::tests::field_prime::dec_string_ser_deser",
"field::tests::field_prime::multiplication",
"field::tests::field_prime::addition_negative_small",
"field::tests::field_prime::addition_negative",
"field::tests::field_prime::division_two_negative",
"field::tests::field_prime::division",
"field::tests::field_prime::negative_number",
"field::tests::field_prime::multiplication_two_negative",
"field::tests::field_prime::multiplication_overflow",
"field::tests::field_prime::pow_small",
"field::tests::field_prime::positive_number",
"field::tests::field_prime::multiplication_negative",
"field::tests::field_prime::subtraction",
"field::tests::field_prime::pow_usize",
"field::tests::field_prime::pow",
"field::tests::field_prime::subtraction_negative",
"field::tests::field_prime::serde_ser_deser",
"field::tests::field_prime::subtraction_overflow",
"imports::tests::create_with_no_alias",
"imports::tests::create_with_alias",
"helpers::tests::eq_condition::execute",
"flatten::multiple_definition::multiple_definition",
"field::tests::test_extended_euclid",
"helpers::tests::eq_condition::execute_non_eq",
"parser::tests::inline_comment",
"flatten::multiple_definition::simple_definition",
"parser::tests::parse_comma_separated_list::comma_separated_list",
"parser::tests::parse_comma_separated_list::comma_separated_list_single",
"flatten::multiple_definition::multiple_definition2",
"parser::tests::parse_factor::ide",
"flatten::multiple_definition::overload",
"parser::tests::parse_comma_separated_list::comma_separated_list_three",
"parser::tests::parse_factor::brackets",
"parser::tests::parse_imports::parse_import_test",
"parser::tests::parse_factor::num",
"parser::tests::parse_factor::if_then_else",
"parser::tests::parse_imports::quoted_path",
"parser::tests::parse_num::add",
"parser::tests::parse_num::single",
"field::tests::field_prime::pow_negative",
"parser::tests::parse_num::space_after",
"parser::tests::position_col",
"parser::tests::parse_num::space_before",
"r1cs::tests::r1cs_expression::add",
"r1cs::tests::r1cs_expression::add_mult",
"r1cs::tests::r1cs_expression::div",
"r1cs::tests::r1cs_expression::add_sub_mix",
"r1cs::tests::r1cs_expression::sub",
"semantics::tests::arity_mismatch",
"parser::tests::parse_imports::import",
"parser::tests::parse_if_then_else_ok",
"r1cs::tests::r1cs_expression::sub_multiple",
"semantics::tests::declared_in_other_function",
"semantics::tests::defined_variable_in_statement",
"parser::tests::parse_imports::parse_import_with_alias_test",
"semantics::tests::duplicate_function_declaration",
"semantics::tests::declared_in_two_scopes",
"semantics::tests::for_index_after_end",
"parser::tests::parse_num::x_before",
"semantics::tests::function_undefined",
"optimizer::tests::remove_synonyms",
"prefixed_substitution::tests::insert_simple_variable",
"semantics::tests::multi_return_outside_multidef",
"semantics::tests::return_undefined",
"optimizer::tests::remove_multiple_synonyms",
"semantics::tests::multi_def",
"semantics::tests::function_undefined_in_multidef",
"semantics::tests::undefined_variable_in_statement",
"semantics::tests::for_index_in_for",
"semantics::tests::undefined_variable_in_multireturn_call",
"prefixed_substitution::tests::insert_twice_with_same_prefix",
"standard::tests::deserialize_constraint",
"standard::tests::constraint_into_flat_statement",
"prefixed_substitution::tests::insert_binary_variable",
"semantics::tests::duplicate_main_function",
"tests::examples_with_input",
"tests::examples"
] |
[
"helpers::tests::sha256libsnark::execute",
"integration::run_integration_tests"
] |
[] |
|
gfx-rs/naga
| 1,611
|
gfx-rs__naga-1611
|
[
"1545"
] |
33c1daeceef9268a9502df0720d69c9aa9b464da
|
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3470,9 +3470,20 @@ impl Parser {
lexer.expect(Token::Paren(')'))?;
let accept = self.parse_block(lexer, context.reborrow(), false)?;
+
let mut elsif_stack = Vec::new();
let mut elseif_span_start = lexer.current_byte_offset();
- while lexer.skip(Token::Word("elseif")) {
+ let mut reject = loop {
+ if !lexer.skip(Token::Word("else")) {
+ break crate::Block::new();
+ }
+
+ if !lexer.skip(Token::Word("if")) {
+ // ... else { ... }
+ break self.parse_block(lexer, context.reborrow(), false)?;
+ }
+
+ // ... else if (...) { ... }
let mut sub_emitter = super::Emitter::default();
lexer.expect(Token::Paren('('))?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3491,12 +3502,8 @@ impl Parser {
other_block,
));
elseif_span_start = lexer.current_byte_offset();
- }
- let mut reject = if lexer.skip(Token::Word("else")) {
- self.parse_block(lexer, context.reborrow(), false)?
- } else {
- crate::Block::new()
};
+
let span_end = lexer.current_byte_offset();
// reverse-fold the else-if blocks
//Note: we may consider uplifting this to the IR
|
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -215,7 +215,7 @@ fn parse_if() {
if (0 != 1) {}
if (false) {
return;
- } elseif (true) {
+ } else if (true) {
return;
} else {}
}
|
The else if statement is not supported
Naga does not allow an if_statement inside an else_statement, but the [spec](https://www.w3.org/TR/WGSL/#if-statement) allows for it.
```
if (true) {} else if (false) {}
```
```
Parse Error: expected '{', found 'if'
```
|
2021-12-17T23:11:03Z
|
0.7
|
2021-12-17T16:19:39Z
|
33c1daeceef9268a9502df0720d69c9aa9b464da
|
[
"front::wgsl::tests::parse_if"
] |
[
"arena::tests::fetch_or_append_unique",
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"back::msl::test_error_size",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"front::glsl::constants::tests::access",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::implicit_conversions",
"front::spv::test::parse",
"front::glsl::parser_tests::control_flow",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::swizzles",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_hex_floats",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_decimal_floats",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::expressions",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_storage_buffers",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::namer::test",
"proc::test_matrix_size",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_types",
"convert_spv_inverse_hyperbolic_trig_functions",
"convert_spv_empty_global_name",
"convert_spv_quad_vert",
"convert_spv_shadow",
"convert_glsl_folder",
"convert_wgsl",
"storage1d",
"cube_array",
"sampler1d",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"bad_texture_sample_type",
"function_without_identifier",
"bad_for_initializer",
"inconsistent_binding",
"invalid_float",
"invalid_integer",
"bad_type_cast",
"dead_code",
"invalid_arrays",
"invalid_texture_sample_type",
"let_type_mismatch",
"invalid_structs",
"invalid_runtime_sized_arrays",
"bad_texture",
"last_case_falltrough",
"local_var_missing_type",
"local_var_type_mismatch",
"invalid_local_vars",
"invalid_functions",
"missing_default_case",
"invalid_access",
"reserved_identifier_prefix",
"struct_member_zero_align",
"unknown_access",
"unknown_attribute",
"struct_member_zero_size",
"negative_index",
"unknown_conservative_depth",
"unknown_ident",
"pointer_type_equivalence",
"module_scope_identifier_redefinition",
"missing_bindings",
"unknown_local_function",
"unknown_identifier",
"reserved_keyword",
"unknown_built_in",
"unknown_storage_class",
"unknown_storage_format",
"unknown_type",
"postfix_pointers",
"unknown_shader_stage",
"unknown_scalar_type",
"zero_array_stride",
"wrong_access_mode",
"select",
"valid_access",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,567
|
gfx-rs__naga-1567
|
[
"1533"
] |
cadc052ab33084d884ba484a1c2be1bcaf8e440b
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,21 @@
# Change Log
+## v0.7.2 (2021-12-01)
+ - validator:
+ - check stores for proper pointer class
+ - HLSL-out:
+ - fix stores into `mat3`
+ - respect array strides
+ - SPV-out:
+ - fix multi-word constants
+ - WGSL-in:
+ - permit names starting with underscores
+ - SPV-in:
+ - cull unused builtins
+ - support empty debug labels
+ - GLSL-in:
+ - don't panic on invalid integer operations
+
## v0.7.1 (2021-10-12)
- implement casts from and to booleans in the backends
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "naga"
-version = "0.7.1"
+version = "0.7.2"
authors = ["Naga Developers"]
edition = "2018"
description = "Shader translation infrastructure"
diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs
--- a/src/back/hlsl/storage.rs
+++ b/src/back/hlsl/storage.rs
@@ -129,7 +129,6 @@ impl<W: fmt::Write> super::Writer<'_, W> {
crate::VectorSize::Tri => 4,
columns => columns as u32,
};
-
let row_stride = width as u32 * padded_columns;
let iter = (0..rows as u32).map(|i| {
let ty_inner = crate::TypeInner::Vector {
diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs
--- a/src/back/hlsl/storage.rs
+++ b/src/back/hlsl/storage.rs
@@ -267,8 +266,15 @@ impl<W: fmt::Write> super::Writer<'_, W> {
)?;
self.write_store_value(module, &value, func_ctx)?;
writeln!(self.out, ";")?;
+
+ // Note: Matrices containing vec3s, due to padding, act like they contain vec4s.
+ let padded_columns = match columns {
+ crate::VectorSize::Tri => 4,
+ columns => columns as u32,
+ };
+ let row_stride = width as u32 * padded_columns;
+
// then iterate the stores
- let row_stride = width as u32 * columns as u32;
for i in 0..rows as u32 {
self.temp_access_chain
.push(SubAccess::Offset(i * row_stride));
diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs
--- a/src/back/hlsl/storage.rs
+++ b/src/back/hlsl/storage.rs
@@ -361,39 +367,22 @@ impl<W: fmt::Write> super::Writer<'_, W> {
mut cur_expr: Handle<crate::Expression>,
func_ctx: &FunctionCtx,
) -> Result<Handle<crate::GlobalVariable>, Error> {
+ enum AccessIndex {
+ Expression(Handle<crate::Expression>),
+ Constant(u32),
+ }
+ enum Parent<'a> {
+ Array { stride: u32 },
+ Struct(&'a [crate::StructMember]),
+ }
self.temp_access_chain.clear();
- loop {
- // determine the size of the pointee
- let stride = match *func_ctx.info[cur_expr].ty.inner_with(&module.types) {
- crate::TypeInner::Pointer { base, class: _ } => {
- module.types[base].inner.span(&module.constants)
- }
- crate::TypeInner::ValuePointer { size, width, .. } => {
- size.map_or(1, |s| s as u32) * width as u32
- }
- _ => 0,
- };
- let (next_expr, sub) = match func_ctx.expressions[cur_expr] {
+ loop {
+ let (next_expr, access_index) = match func_ctx.expressions[cur_expr] {
crate::Expression::GlobalVariable(handle) => return Ok(handle),
- crate::Expression::Access { base, index } => (
- base,
- SubAccess::Index {
- value: index,
- stride,
- },
- ),
+ crate::Expression::Access { base, index } => (base, AccessIndex::Expression(index)),
crate::Expression::AccessIndex { base, index } => {
- let sub = match *func_ctx.info[base].ty.inner_with(&module.types) {
- crate::TypeInner::Pointer { base, .. } => match module.types[base].inner {
- crate::TypeInner::Struct { ref members, .. } => {
- SubAccess::Offset(members[index as usize].offset)
- }
- _ => SubAccess::Offset(index * stride),
- },
- _ => SubAccess::Offset(index * stride),
- };
- (base, sub)
+ (base, AccessIndex::Constant(index))
}
ref other => {
return Err(Error::Unimplemented(format!(
diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs
--- a/src/back/hlsl/storage.rs
+++ b/src/back/hlsl/storage.rs
@@ -402,6 +391,38 @@ impl<W: fmt::Write> super::Writer<'_, W> {
)))
}
};
+
+ let parent = match *func_ctx.info[next_expr].ty.inner_with(&module.types) {
+ crate::TypeInner::Pointer { base, .. } => match module.types[base].inner {
+ crate::TypeInner::Struct { ref members, .. } => Parent::Struct(members),
+ crate::TypeInner::Array { stride, .. } => Parent::Array { stride },
+ crate::TypeInner::Vector { width, .. } => Parent::Array {
+ stride: width as u32,
+ },
+ crate::TypeInner::Matrix { rows, width, .. } => Parent::Array {
+ stride: width as u32 * if rows > crate::VectorSize::Bi { 4 } else { 2 },
+ },
+ _ => unreachable!(),
+ },
+ crate::TypeInner::ValuePointer { width, .. } => Parent::Array {
+ stride: width as u32,
+ },
+ _ => unreachable!(),
+ };
+
+ let sub = match (parent, access_index) {
+ (Parent::Array { stride }, AccessIndex::Expression(value)) => {
+ SubAccess::Index { value, stride }
+ }
+ (Parent::Array { stride }, AccessIndex::Constant(index)) => {
+ SubAccess::Offset(stride * index)
+ }
+ (Parent::Struct(members), AccessIndex::Constant(index)) => {
+ SubAccess::Offset(members[index as usize].offset)
+ }
+ (Parent::Struct(_), AccessIndex::Expression(_)) => unreachable!(),
+ };
+
self.temp_access_chain.push(sub);
cur_expr = next_expr;
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1004,7 +1004,7 @@ impl Writer {
&solo[..]
}
8 => {
- pair = [(val >> 32) as u32, val as u32];
+ pair = [val as u32, (val >> 32) as u32];
&pair
}
_ => unreachable!(),
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1018,7 +1018,7 @@ impl Writer {
&solo[..]
}
8 => {
- pair = [(val >> 32) as u32, val as u32];
+ pair = [val as u32, (val >> 32) as u32];
&pair
}
_ => unreachable!(),
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1033,7 +1033,7 @@ impl Writer {
}
8 => {
let bits = f64::to_bits(val);
- pair = [(bits >> 32) as u32, bits as u32];
+ pair = [bits as u32, (bits >> 32) as u32];
&pair
}
_ => unreachable!(),
diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs
--- a/src/front/glsl/constants.rs
+++ b/src/front/glsl/constants.rs
@@ -317,16 +317,6 @@ impl<'a> ConstantSolver<'a> {
target_width: crate::Bytes,
span: crate::Span,
) -> Result<Handle<Constant>, ConstantSolvingError> {
- fn inner_cast<A: num_traits::FromPrimitive>(value: ScalarValue) -> A {
- match value {
- ScalarValue::Sint(v) => A::from_i64(v),
- ScalarValue::Uint(v) => A::from_u64(v),
- ScalarValue::Float(v) => A::from_f64(v),
- ScalarValue::Bool(v) => A::from_u64(v as u64),
- }
- .unwrap()
- }
-
let mut inner = self.constants[constant].inner.clone();
match inner {
diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs
--- a/src/front/glsl/constants.rs
+++ b/src/front/glsl/constants.rs
@@ -336,10 +326,30 @@ impl<'a> ConstantSolver<'a> {
} => {
*width = target_width;
*value = match kind {
- ScalarKind::Sint => ScalarValue::Sint(inner_cast(*value)),
- ScalarKind::Uint => ScalarValue::Uint(inner_cast(*value)),
- ScalarKind::Float => ScalarValue::Float(inner_cast(*value)),
- ScalarKind::Bool => ScalarValue::Bool(inner_cast::<u64>(*value) != 0),
+ ScalarKind::Sint => ScalarValue::Sint(match *value {
+ ScalarValue::Sint(v) => v,
+ ScalarValue::Uint(v) => v as i64,
+ ScalarValue::Float(v) => v as i64,
+ ScalarValue::Bool(v) => v as i64,
+ }),
+ ScalarKind::Uint => ScalarValue::Uint(match *value {
+ ScalarValue::Sint(v) => v as u64,
+ ScalarValue::Uint(v) => v,
+ ScalarValue::Float(v) => v as u64,
+ ScalarValue::Bool(v) => v as u64,
+ }),
+ ScalarKind::Float => ScalarValue::Float(match *value {
+ ScalarValue::Sint(v) => v as f64,
+ ScalarValue::Uint(v) => v as f64,
+ ScalarValue::Float(v) => v,
+ ScalarValue::Bool(v) => v as u64 as f64,
+ }),
+ ScalarKind::Bool => ScalarValue::Bool(match *value {
+ ScalarValue::Sint(v) => v != 0,
+ ScalarValue::Uint(v) => v != 0,
+ ScalarValue::Float(v) => v != 0.0,
+ ScalarValue::Bool(v) => v,
+ }),
}
}
ConstantInner::Composite {
diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs
--- a/src/front/glsl/constants.rs
+++ b/src/front/glsl/constants.rs
@@ -446,31 +456,36 @@ impl<'a> ConstantSolver<'a> {
_ => match (left_value, right_value) {
(ScalarValue::Sint(a), ScalarValue::Sint(b)) => {
ScalarValue::Sint(match op {
- BinaryOperator::Add => a + b,
- BinaryOperator::Subtract => a - b,
- BinaryOperator::Multiply => a * b,
- BinaryOperator::Divide => a / b,
- BinaryOperator::Modulo => a % b,
+ BinaryOperator::Add => a.wrapping_add(b),
+ BinaryOperator::Subtract => a.wrapping_sub(b),
+ BinaryOperator::Multiply => a.wrapping_mul(b),
+ BinaryOperator::Divide => a.checked_div(b).unwrap_or(0),
+ BinaryOperator::Modulo => a.checked_rem(b).unwrap_or(0),
BinaryOperator::And => a & b,
BinaryOperator::ExclusiveOr => a ^ b,
BinaryOperator::InclusiveOr => a | b,
- BinaryOperator::ShiftLeft => a << b,
- BinaryOperator::ShiftRight => a >> b,
+ _ => return Err(ConstantSolvingError::InvalidBinaryOpArgs),
+ })
+ }
+ (ScalarValue::Sint(a), ScalarValue::Uint(b)) => {
+ ScalarValue::Sint(match op {
+ BinaryOperator::ShiftLeft => a.wrapping_shl(b as u32),
+ BinaryOperator::ShiftRight => a.wrapping_shr(b as u32),
_ => return Err(ConstantSolvingError::InvalidBinaryOpArgs),
})
}
(ScalarValue::Uint(a), ScalarValue::Uint(b)) => {
ScalarValue::Uint(match op {
- BinaryOperator::Add => a + b,
- BinaryOperator::Subtract => a - b,
- BinaryOperator::Multiply => a * b,
- BinaryOperator::Divide => a / b,
- BinaryOperator::Modulo => a % b,
+ BinaryOperator::Add => a.wrapping_add(b),
+ BinaryOperator::Subtract => a.wrapping_sub(b),
+ BinaryOperator::Multiply => a.wrapping_mul(b),
+ BinaryOperator::Divide => a.checked_div(b).unwrap_or(0),
+ BinaryOperator::Modulo => a.checked_rem(b).unwrap_or(0),
BinaryOperator::And => a & b,
BinaryOperator::ExclusiveOr => a ^ b,
BinaryOperator::InclusiveOr => a | b,
- BinaryOperator::ShiftLeft => a << b,
- BinaryOperator::ShiftRight => a >> b,
+ BinaryOperator::ShiftLeft => a.wrapping_shl(b as u32),
+ BinaryOperator::ShiftRight => a.wrapping_shr(b as u32),
_ => return Err(ConstantSolvingError::InvalidBinaryOpArgs),
})
}
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -376,9 +376,16 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
..
} => {
for (index, sm) in sub_members.iter().enumerate() {
- if sm.binding.is_none() {
+ match sm.binding {
+ Some(crate::Binding::BuiltIn(builtin)) => {
+ // Cull unused builtins to preserve performances
+ if !self.builtin_usage.contains(&builtin) {
+ continue;
+ }
+ }
// unrecognized binding, skip
- continue;
+ None => continue,
+ _ => {}
}
members.push(sm.clone());
components.push(function.expressions.append(
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -37,7 +37,7 @@ use function::*;
use crate::{
arena::{Arena, Handle, UniqueArena},
proc::Layouter,
- FastHashMap,
+ FastHashMap, FastHashSet,
};
use num_traits::cast::FromPrimitive;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -549,6 +549,10 @@ pub struct Parser<I> {
(BodyIndex, Vec<i32>),
std::hash::BuildHasherDefault<fxhash::FxHasher>,
>,
+
+ /// Tracks usage of builtins, used to cull unused builtins since they can
+ /// have serious performance implications.
+ builtin_usage: FastHashSet<crate::BuiltIn>,
}
impl<I: Iterator<Item = u32>> Parser<I> {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -582,6 +586,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
index_constants: Vec::new(),
index_constant_expressions: Vec::new(),
switch_cases: indexmap::IndexMap::default(),
+ builtin_usage: FastHashSet::default(),
}
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1294,9 +1299,10 @@ impl<I: Iterator<Item = u32>> Parser<I> {
let type_lookup = self.lookup_type.lookup(acex.type_id)?;
acex = match ctx.type_arena[type_lookup.handle].inner {
// can only index a struct with a constant
- crate::TypeInner::Struct { .. } => {
+ crate::TypeInner::Struct { ref members, .. } => {
let index = index_maybe
.ok_or_else(|| Error::InvalidAccess(index_expr_data.clone()))?;
+
let lookup_member = self
.lookup_member
.get(&(type_lookup.handle, index))
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1308,6 +1314,13 @@ impl<I: Iterator<Item = u32>> Parser<I> {
},
span,
);
+
+ if let Some(crate::Binding::BuiltIn(builtin)) =
+ members[index as usize].binding
+ {
+ self.builtin_usage.insert(builtin);
+ }
+
AccessExpression {
base_handle,
type_id: lookup_member.type_id,
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -193,6 +193,7 @@ tree.
clippy::unneeded_field_pattern,
clippy::match_like_matches_macro,
clippy::manual_strip,
+ clippy::if_same_then_else,
clippy::unknown_clippy_lints,
)]
#![warn(
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -184,6 +184,21 @@ impl super::TypeInner {
}
}
+impl super::StorageClass {
+ pub fn access(self) -> crate::StorageAccess {
+ use crate::StorageAccess as Sa;
+ match self {
+ crate::StorageClass::Function
+ | crate::StorageClass::Private
+ | crate::StorageClass::WorkGroup => Sa::LOAD | Sa::STORE,
+ crate::StorageClass::Uniform => Sa::LOAD,
+ crate::StorageClass::Storage { access } => access,
+ crate::StorageClass::Handle => Sa::LOAD,
+ crate::StorageClass::PushConstant => Sa::LOAD,
+ }
+ }
+}
+
impl super::MathFunction {
pub fn argument_count(&self) -> usize {
match *self {
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -1,7 +1,8 @@
use crate::{arena::Handle, FastHashMap, FastHashSet};
-use std::collections::hash_map::Entry;
+use std::borrow::Cow;
pub type EntryPointIndex = u16;
+const SEPARATOR: char = '_';
#[derive(Debug, Eq, Hash, PartialEq)]
pub enum NameKey {
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -30,26 +31,40 @@ pub struct Namer {
impl Namer {
/// Return a form of `string` suitable for use as the base of an identifier.
///
- /// Retain only alphanumeric and `_` characters. Drop leading digits. Ensure
- /// that the string does not end with a digit, so we can attach numeric
- /// suffixes without merging. Avoid prefixes in
- /// [`Namer::reserved_prefixes`].
- fn sanitize(&self, string: &str) -> String {
- let mut base = string
- .chars()
- .skip_while(|&c| c.is_numeric() || c == '_')
- .filter(|&c| c.is_ascii_alphanumeric() || c == '_')
- .collect::<String>();
- // close the name by '_' if the re is a number, so that
- // we can have our own number!
- match base.chars().next_back() {
- Some(c) if !c.is_numeric() => {}
- _ => base.push('_'),
+ /// - Drop leading digits.
+ /// - Retain only alphanumeric and `_` characters.
+ /// - Avoid prefixes in [`Namer::reserved_prefixes`].
+ ///
+ /// The return value is a valid identifier prefix in all of Naga's output languages,
+ /// and it never ends with a `SEPARATOR` character.
+ /// It is used as a key into the unique table.
+ fn sanitize<'s>(&self, string: &'s str) -> Cow<'s, str> {
+ let string = string
+ .trim_start_matches(|c: char| c.is_numeric())
+ .trim_end_matches(SEPARATOR);
+
+ let base = if !string.is_empty()
+ && string
+ .chars()
+ .all(|c: char| c.is_ascii_alphanumeric() || c == '_')
+ {
+ Cow::Borrowed(string)
+ } else {
+ let mut filtered = string
+ .chars()
+ .filter(|&c| c.is_ascii_alphanumeric() || c == '_')
+ .collect::<String>();
+ let stripped_len = filtered.trim_end_matches(SEPARATOR).len();
+ filtered.truncate(stripped_len);
+ if filtered.is_empty() {
+ filtered.push_str("unnamed");
+ }
+ Cow::Owned(filtered)
};
for prefix in &self.reserved_prefixes {
if base.starts_with(prefix) {
- return format!("gen_{}", base);
+ return Cow::Owned(format!("gen_{}", base));
}
}
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -66,23 +81,34 @@ impl Namer {
///
/// Guarantee uniqueness by applying a numeric suffix when necessary.
pub fn call(&mut self, label_raw: &str) -> String {
+ use std::fmt::Write as _; // for write!-ing to Strings
+
let base = self.sanitize(label_raw);
- match self.unique.entry(base) {
- Entry::Occupied(mut e) => {
- *e.get_mut() += 1;
- format!("{}{}", e.key(), e.get())
+ debug_assert!(!base.is_empty() && !base.ends_with(SEPARATOR));
+
+ // This would seem to be a natural place to use `HashMap::entry`. However, `entry`
+ // requires an owned key, and we'd like to avoid heap-allocating strings we're
+ // just going to throw away. The approach below double-hashes only when we create
+ // a new entry, in which case the heap allocation of the owned key was more
+ // expensive anyway.
+ match self.unique.get_mut(base.as_ref()) {
+ Some(count) => {
+ *count += 1;
+ // Add the suffix. This may fit in base's existing allocation.
+ let mut suffixed = base.into_owned();
+ write!(&mut suffixed, "{}{}", SEPARATOR, *count).unwrap();
+ suffixed
}
- Entry::Vacant(e) => {
- let name = e.key();
- if self.keywords.contains(e.key()) {
- let name = format!("{}1", name);
- e.insert(1);
- name
- } else {
- let name = name.to_string();
- e.insert(0);
- name
+ None => {
+ let mut suffixed = base.to_string();
+ if base.ends_with(char::is_numeric) || self.keywords.contains(base.as_ref()) {
+ suffixed.push(SEPARATOR);
}
+ debug_assert!(!self.keywords.contains(&suffixed));
+ // `self.unique` wants to own its keys. This allocates only if we haven't
+ // already done so earlier.
+ self.unique.insert(base.into_owned(), 0);
+ suffixed
}
}
}
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -513,7 +513,10 @@ impl super::Validator {
}
_ => {}
}
- let good = match *context.resolve_pointer_type(pointer)? {
+
+ let pointer_ty = context.resolve_pointer_type(pointer)?;
+
+ let good = match *pointer_ty {
Ti::Pointer { base, class: _ } => match context.types[base].inner {
Ti::Atomic { kind, width } => *value_ty == Ti::Scalar { kind, width },
ref other => value_ty == other,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -535,6 +538,12 @@ impl super::Validator {
if !good {
return Err(FunctionError::InvalidStoreTypes { pointer, value });
}
+
+ if let Some(class) = pointer_ty.pointer_class() {
+ if !class.access().contains(crate::StorageAccess::STORE) {
+ return Err(FunctionError::InvalidStorePointer(pointer));
+ }
+ }
}
S::ImageStore {
image,
|
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -224,3 +250,11 @@ impl Namer {
}
}
}
+
+#[test]
+fn test() {
+ let mut namer = Namer::default();
+ assert_eq!(namer.call("x"), "x");
+ assert_eq!(namer.call("x"), "x_1");
+ assert_eq!(namer.call("x1"), "x1_");
+}
diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl
--- a/tests/in/access.wgsl
+++ b/tests/in/access.wgsl
@@ -5,7 +5,7 @@ struct Bar {
matrix: mat4x4<f32>;
atom: atomic<i32>;
arr: [[stride(8)]] array<vec2<u32>, 2>;
- data: [[stride(4)]] array<i32>;
+ data: [[stride(8)]] array<i32>;
};
[[group(0), binding(0)]]
diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl
--- a/tests/in/access.wgsl
+++ b/tests/in/access.wgsl
@@ -37,6 +37,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4<f32> {
bar.matrix[1].z = 1.0;
bar.matrix = mat4x4<f32>(vec4<f32>(0.0), vec4<f32>(1.0), vec4<f32>(2.0), vec4<f32>(3.0));
bar.arr = array<vec2<u32>, 2>(vec2<u32>(0u), vec2<u32>(1u));
+ bar.data[1] = 1;
// test array indexing
var c = array<i32, 5>(a, i32(b), 3, 4, 5);
diff --git a/tests/in/bounds-check-zero.wgsl b/tests/in/bounds-check-zero.wgsl
--- a/tests/in/bounds-check-zero.wgsl
+++ b/tests/in/bounds-check-zero.wgsl
@@ -7,7 +7,7 @@ struct Globals {
m: mat3x4<f32>;
};
-[[group(0), binding(0)]] var<storage> globals: Globals;
+[[group(0), binding(0)]] var<storage, read_write> globals: Globals;
fn index_array(i: i32) -> f32 {
return globals.a[i];
diff --git a/tests/in/glsl/bevy-pbr.frag b/tests/in/glsl/bevy-pbr.frag
--- a/tests/in/glsl/bevy-pbr.frag
+++ b/tests/in/glsl/bevy-pbr.frag
@@ -115,7 +115,7 @@ float getDistanceAttenuation(float distanceSquare, float inverseRangeSquared) {
float factor = distanceSquare * inverseRangeSquared;
float smoothFactor = saturate(1.0 - factor * factor);
float attenuation = smoothFactor * smoothFactor;
- return attenuation * 1.0 / max(distanceSquare, 1e-4);
+ return attenuation * 1.0 / max(distanceSquare, 1e-3);
}
// Normal distribution function (specular D)
diff --git a/tests/in/glsl/bevy-pbr.frag b/tests/in/glsl/bevy-pbr.frag
--- a/tests/in/glsl/bevy-pbr.frag
+++ b/tests/in/glsl/bevy-pbr.frag
@@ -353,7 +353,7 @@ void main() {
emissive.rgb *= texture(sampler2D(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler), v_Uv).rgb;
vec3 V = normalize(CameraPos.xyz - v_WorldPosition.xyz);
// Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
- float NdotV = max(dot(N, V), 1e-4);
+ float NdotV = max(dot(N, V), 1e-3);
// Remapping [0,1] reflectance to F0
// See https://google.github.io/filament/Filament.html#materialsystem/parameterization/remapping
diff --git /dev/null b/tests/in/glsl/empty-global-name.frag
new file mode 100644
--- /dev/null
+++ b/tests/in/glsl/empty-global-name.frag
@@ -0,0 +1,7 @@
+layout(set = 1, binding = 1) uniform TextureData {
+ vec4 material;
+};
+
+void main() {
+ vec2 coords = vec2(material.xy);
+}
diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl
--- a/tests/out/glsl/access.atomics.Compute.glsl
+++ b/tests/out/glsl/access.atomics.Compute.glsl
@@ -13,8 +13,8 @@ layout(std430) buffer Bar_block_0Cs {
} _group_0_binding_0;
-float read_from_private(inout float foo2) {
- float _e2 = foo2;
+float read_from_private(inout float foo_2) {
+ float _e2 = foo_2;
return _e2;
}
diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl
--- a/tests/out/glsl/access.foo.Vertex.glsl
+++ b/tests/out/glsl/access.foo.Vertex.glsl
@@ -11,25 +11,26 @@ layout(std430) buffer Bar_block_0Vs {
} _group_0_binding_0;
-float read_from_private(inout float foo2) {
- float _e2 = foo2;
+float read_from_private(inout float foo_2) {
+ float _e2 = foo_2;
return _e2;
}
void main() {
uint vi = uint(gl_VertexID);
- float foo1 = 0.0;
+ float foo_1 = 0.0;
int c[5];
- float baz = foo1;
- foo1 = 1.0;
+ float baz = foo_1;
+ foo_1 = 1.0;
mat4x4 matrix = _group_0_binding_0.matrix;
uvec2 arr[2] = _group_0_binding_0.arr;
float b = _group_0_binding_0.matrix[3][0];
int a = _group_0_binding_0.data[(uint(_group_0_binding_0.data.length()) - 2u)];
- float _e25 = read_from_private(foo1);
+ float _e25 = read_from_private(foo_1);
_group_0_binding_0.matrix[1][2] = 1.0;
_group_0_binding_0.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0));
_group_0_binding_0.arr = uvec2[2](uvec2(0u), uvec2(1u));
+ _group_0_binding_0.data[1] = 1;
c = int[5](a, int(b), 3, 4, 5);
c[(vi + 1u)] = 42;
int value = c[vi];
diff --git a/tests/out/glsl/interpolate.main.Fragment.glsl b/tests/out/glsl/interpolate.main.Fragment.glsl
--- a/tests/out/glsl/interpolate.main.Fragment.glsl
+++ b/tests/out/glsl/interpolate.main.Fragment.glsl
@@ -1,7 +1,7 @@
#version 400 core
struct FragmentInput {
vec4 position;
- uint flat1;
+ uint flat_;
float linear;
vec2 linear_centroid;
vec3 linear_sample;
diff --git a/tests/out/glsl/interpolate.main.Vertex.glsl b/tests/out/glsl/interpolate.main.Vertex.glsl
--- a/tests/out/glsl/interpolate.main.Vertex.glsl
+++ b/tests/out/glsl/interpolate.main.Vertex.glsl
@@ -1,7 +1,7 @@
#version 400 core
struct FragmentInput {
vec4 position;
- uint flat1;
+ uint flat_;
float linear;
vec2 linear_centroid;
vec3 linear_sample;
diff --git a/tests/out/glsl/interpolate.main.Vertex.glsl b/tests/out/glsl/interpolate.main.Vertex.glsl
--- a/tests/out/glsl/interpolate.main.Vertex.glsl
+++ b/tests/out/glsl/interpolate.main.Vertex.glsl
@@ -19,18 +19,18 @@ smooth centroid out float _vs2fs_location5;
smooth sample out float _vs2fs_location6;
void main() {
- FragmentInput out1;
- out1.position = vec4(2.0, 4.0, 5.0, 6.0);
- out1.flat1 = 8u;
- out1.linear = 27.0;
- out1.linear_centroid = vec2(64.0, 125.0);
- out1.linear_sample = vec3(216.0, 343.0, 512.0);
- out1.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0);
- out1.perspective_centroid = 2197.0;
- out1.perspective_sample = 2744.0;
- FragmentInput _e30 = out1;
+ FragmentInput out_;
+ out_.position = vec4(2.0, 4.0, 5.0, 6.0);
+ out_.flat_ = 8u;
+ out_.linear = 27.0;
+ out_.linear_centroid = vec2(64.0, 125.0);
+ out_.linear_sample = vec3(216.0, 343.0, 512.0);
+ out_.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0);
+ out_.perspective_centroid = 2197.0;
+ out_.perspective_sample = 2744.0;
+ FragmentInput _e30 = out_;
gl_Position = _e30.position;
- _vs2fs_location0 = _e30.flat1;
+ _vs2fs_location0 = _e30.flat_;
_vs2fs_location1 = _e30.linear;
_vs2fs_location2 = _e30.linear_centroid;
_vs2fs_location3 = _e30.linear_sample;
diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl
--- a/tests/out/glsl/operators.main.Compute.glsl
+++ b/tests/out/glsl/operators.main.Compute.glsl
@@ -50,8 +50,8 @@ float constructors() {
}
void modulo() {
- int a1 = (1 % 1);
- float b1 = (1.0 - 1.0 * trunc(1.0 / 1.0));
+ int a_1 = (1 % 1);
+ float b_1 = (1.0 - 1.0 * trunc(1.0 / 1.0));
ivec3 c = (ivec3(1) % ivec3(1));
vec3 d = (vec3(1.0) - vec3(1.0) * trunc(vec3(1.0) / vec3(1.0)));
}
diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl
--- a/tests/out/glsl/quad-vert.main.Vertex.glsl
+++ b/tests/out/glsl/quad-vert.main.Vertex.glsl
@@ -3,17 +3,14 @@
precision highp float;
precision highp int;
-struct type9 {
+struct type_9 {
vec2 member;
vec4 gen_gl_Position;
- float gen_gl_PointSize;
- float gen_gl_ClipDistance[1];
- float gen_gl_CullDistance[1];
};
vec2 v_uv = vec2(0.0, 0.0);
-vec2 a_uv1 = vec2(0.0, 0.0);
+vec2 a_uv_1 = vec2(0.0, 0.0);
struct gen_gl_PerVertex_block_0Vs {
vec4 gen_gl_Position;
diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl
--- a/tests/out/glsl/quad-vert.main.Vertex.glsl
+++ b/tests/out/glsl/quad-vert.main.Vertex.glsl
@@ -22,16 +19,16 @@ struct gen_gl_PerVertex_block_0Vs {
float gen_gl_CullDistance[1];
} perVertexStruct;
-vec2 a_pos1 = vec2(0.0, 0.0);
+vec2 a_pos_1 = vec2(0.0, 0.0);
layout(location = 1) in vec2 _p2vs_location1;
layout(location = 0) in vec2 _p2vs_location0;
layout(location = 0) smooth out vec2 _vs2fs_location0;
-void main2() {
- vec2 _e12 = a_uv1;
+void main_1() {
+ vec2 _e12 = a_uv_1;
v_uv = _e12;
- vec2 _e13 = a_pos1;
+ vec2 _e13 = a_pos_1;
perVertexStruct.gen_gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0);
return;
}
diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl
--- a/tests/out/glsl/quad-vert.main.Vertex.glsl
+++ b/tests/out/glsl/quad-vert.main.Vertex.glsl
@@ -39,15 +36,12 @@ void main2() {
void main() {
vec2 a_uv = _p2vs_location1;
vec2 a_pos = _p2vs_location0;
- a_uv1 = a_uv;
- a_pos1 = a_pos;
- main2();
- vec2 _e10 = v_uv;
- vec4 _e11 = perVertexStruct.gen_gl_Position;
- float _e12 = perVertexStruct.gen_gl_PointSize;
- float _e13[1] = perVertexStruct.gen_gl_ClipDistance;
- float _e14[1] = perVertexStruct.gen_gl_CullDistance;
- type9 _tmp_return = type9(_e10, _e11, _e12, _e13, _e14);
+ a_uv_1 = a_uv;
+ a_pos_1 = a_pos;
+ main_1();
+ vec2 _e7 = v_uv;
+ vec4 _e8 = perVertexStruct.gen_gl_Position;
+ type_9 _tmp_return = type_9(_e7, _e8);
_vs2fs_location0 = _tmp_return.member;
gl_Position = _tmp_return.gen_gl_Position;
gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);
diff --git a/tests/out/glsl/quad.main.Fragment.glsl b/tests/out/glsl/quad.main.Fragment.glsl
--- a/tests/out/glsl/quad.main.Fragment.glsl
+++ b/tests/out/glsl/quad.main.Fragment.glsl
@@ -14,8 +14,8 @@ smooth in vec2 _vs2fs_location0;
layout(location = 0) out vec4 _fs2p_location0;
void main() {
- vec2 uv1 = _vs2fs_location0;
- vec4 color = texture(_group_0_binding_0, vec2(uv1));
+ vec2 uv_1 = _vs2fs_location0;
+ vec4 color = texture(_group_0_binding_0, vec2(uv_1));
if ((color.w == 0.0)) {
discard;
}
diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl
--- a/tests/out/glsl/skybox.fs_main.Fragment.glsl
+++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl
@@ -14,8 +14,8 @@ layout(location = 0) smooth in vec3 _vs2fs_location0;
layout(location = 0) out vec4 _fs2p_location0;
void main() {
- VertexOutput in1 = VertexOutput(gl_FragCoord, _vs2fs_location0);
- vec4 _e5 = texture(_group_0_binding_1, vec3(in1.uv));
+ VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0);
+ vec4 _e5 = texture(_group_0_binding_1, vec3(in_.uv));
_fs2p_location0 = _e5;
return;
}
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -1,9 +1,9 @@
RWByteAddressBuffer bar : register(u0);
-float read_from_private(inout float foo2)
+float read_from_private(inout float foo_2)
{
- float _expr2 = foo2;
+ float _expr2 = foo_2;
return _expr2;
}
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -16,16 +16,16 @@ uint NagaBufferLengthRW(RWByteAddressBuffer buffer)
float4 foo(uint vi : SV_VertexID) : SV_Position
{
- float foo1 = 0.0;
+ float foo_1 = 0.0;
int c[5] = {(int)0,(int)0,(int)0,(int)0,(int)0};
- float baz = foo1;
- foo1 = 1.0;
- float4x4 matrix1 = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48)));
+ float baz = foo_1;
+ foo_1 = 1.0;
+ float4x4 matrix_ = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48)));
uint2 arr[2] = {asuint(bar.Load2(72+0)), asuint(bar.Load2(72+8))};
float b = asfloat(bar.Load(0+48+0));
- int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 4) - 2u)*4+88));
- const float _e25 = read_from_private(foo1);
+ int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 8) - 2u)*8+88));
+ const float _e25 = read_from_private(foo_1);
bar.Store(8+16+0, asuint(1.0));
{
float4x4 _value2 = float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx));
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -39,13 +39,14 @@ float4 foo(uint vi : SV_VertexID) : SV_Position
bar.Store2(72+0, asuint(_value2[0]));
bar.Store2(72+8, asuint(_value2[1]));
}
+ bar.Store(8+88, asuint(1));
{
int _result[5]={ a, int(b), 3, 4, 5 };
for(int _i=0; _i<5; ++_i) c[_i] = _result[_i];
}
c[(vi + 1u)] = 42;
int value = c[vi];
- return mul(float4(int4(value.xxxx)), matrix1);
+ return mul(float4(int4(value.xxxx)), matrix_);
}
[numthreads(1, 1, 1)]
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -53,7 +54,7 @@ void atomics()
{
int tmp = (int)0;
- int value1 = asint(bar.Load(64));
+ int value_1 = asint(bar.Load(64));
int _e6; bar.InterlockedAdd(64, 5, _e6);
tmp = _e6;
int _e9; bar.InterlockedAdd(64, -5, _e9);
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -70,6 +71,6 @@ void atomics()
tmp = _e24;
int _e27; bar.InterlockedExchange(64, 5, _e27);
tmp = _e27;
- bar.Store(64, asuint(value1));
+ bar.Store(64, asuint(value_1));
return;
}
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -38,12 +38,12 @@ void main(uint3 local_id : SV_GroupThreadID)
}
[numthreads(16, 1, 1)]
-void depth_load(uint3 local_id1 : SV_GroupThreadID)
+void depth_load(uint3 local_id_1 : SV_GroupThreadID)
{
- int2 dim1 = NagaRWDimensions2D(image_storage_src);
- int2 itc1 = ((dim1 * int2(local_id1.xy)) % int2(10, 20));
- float val = image_depth_multisampled_src.Load(itc1, int(local_id1.z)).x;
- image_dst[itc1.x] = uint4(uint(val).xxxx);
+ int2 dim_1 = NagaRWDimensions2D(image_storage_src);
+ int2 itc_1 = ((dim_1 * int2(local_id_1.xy)) % int2(10, 20));
+ float val = image_depth_multisampled_src.Load(itc_1, int(local_id_1.z)).x;
+ image_dst[itc_1.x] = uint4(uint(val).xxxx);
return;
}
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -207,11 +207,11 @@ float4 levels_queries() : SV_Position
int num_layers_cube = NagaNumLayersCubeArray(image_cube_array);
int num_levels_3d = NagaNumLevels3D(image_3d);
int num_samples_aa = NagaMSNumSamples2D(image_aa);
- int sum1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array);
- return float4(float(sum1).xxxx);
+ int sum_1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array);
+ return float4(float(sum_1).xxxx);
}
-float4 sample1() : SV_Target0
+float4 sample_() : SV_Target0
{
float2 tc = float2(0.5.xx);
float4 s1d = image_1d.Sample(sampler_reg, tc.x);
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -224,8 +224,8 @@ float4 sample1() : SV_Target0
float sample_comparison() : SV_Target0
{
- float2 tc1 = float2(0.5.xx);
- float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc1, 0.5);
- float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc1, 0.5);
+ float2 tc_1 = float2(0.5.xx);
+ float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc_1, 0.5);
+ float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc_1, 0.5);
return (s2d_depth + s2d_depth_level);
}
diff --git a/tests/out/hlsl/image.hlsl.config b/tests/out/hlsl/image.hlsl.config
--- a/tests/out/hlsl/image.hlsl.config
+++ b/tests/out/hlsl/image.hlsl.config
@@ -1,3 +1,3 @@
vertex=(queries:vs_5_1 levels_queries:vs_5_1 )
-fragment=(sample1:ps_5_1 sample_comparison:ps_5_1 )
+fragment=(sample_:ps_5_1 sample_comparison:ps_5_1 )
compute=(main:cs_5_1 depth_load:cs_5_1 )
diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl
--- a/tests/out/hlsl/interface.hlsl
+++ b/tests/out/hlsl/interface.hlsl
@@ -24,11 +24,11 @@ struct VertexOutput_vertex {
};
struct FragmentInput_fragment {
- float varying1 : LOC1;
- float4 position1 : SV_Position;
- bool front_facing1 : SV_IsFrontFace;
- uint sample_index1 : SV_SampleIndex;
- uint sample_mask1 : SV_Coverage;
+ float varying_1 : LOC1;
+ float4 position_1 : SV_Position;
+ bool front_facing_1 : SV_IsFrontFace;
+ uint sample_index_1 : SV_SampleIndex;
+ uint sample_mask_1 : SV_Coverage;
};
VertexOutput ConstructVertexOutput(float4 arg0, float arg1) {
diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl
--- a/tests/out/hlsl/interface.hlsl
+++ b/tests/out/hlsl/interface.hlsl
@@ -42,8 +42,8 @@ VertexOutput_vertex vertex(uint vertex_index : SV_VertexID, uint instance_index
{
uint tmp = (((_NagaConstants.base_vertex + vertex_index) + (_NagaConstants.base_instance + instance_index)) + color);
const VertexOutput vertexoutput = ConstructVertexOutput(float4(1.0.xxxx), float(tmp));
- const VertexOutput_vertex vertexoutput1 = { vertexoutput.varying, vertexoutput.position };
- return vertexoutput1;
+ const VertexOutput_vertex vertexoutput_1 = { vertexoutput.varying, vertexoutput.position };
+ return vertexoutput_1;
}
FragmentOutput ConstructFragmentOutput(float arg0, uint arg1, float arg2) {
diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl
--- a/tests/out/hlsl/interface.hlsl
+++ b/tests/out/hlsl/interface.hlsl
@@ -56,13 +56,13 @@ FragmentOutput ConstructFragmentOutput(float arg0, uint arg1, float arg2) {
FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment)
{
- VertexOutput in1 = { fragmentinput_fragment.position1, fragmentinput_fragment.varying1 };
- bool front_facing = fragmentinput_fragment.front_facing1;
- uint sample_index = fragmentinput_fragment.sample_index1;
- uint sample_mask = fragmentinput_fragment.sample_mask1;
+ VertexOutput in_ = { fragmentinput_fragment.position_1, fragmentinput_fragment.varying_1 };
+ bool front_facing = fragmentinput_fragment.front_facing_1;
+ uint sample_index = fragmentinput_fragment.sample_index_1;
+ uint sample_mask = fragmentinput_fragment.sample_mask_1;
uint mask = (sample_mask & (1u << sample_index));
- float color1 = (front_facing ? 1.0 : 0.0);
- const FragmentOutput fragmentoutput = ConstructFragmentOutput(in1.varying, mask, color1);
+ float color_1 = (front_facing ? 1.0 : 0.0);
+ const FragmentOutput fragmentoutput = ConstructFragmentOutput(in_.varying, mask, color_1);
return fragmentoutput;
}
diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl
--- a/tests/out/hlsl/interpolate.hlsl
+++ b/tests/out/hlsl/interpolate.hlsl
@@ -2,7 +2,7 @@
struct FragmentInput {
float4 position : SV_Position;
nointerpolation uint flat : LOC0;
- noperspective float linear1 : LOC1;
+ noperspective float linear_ : LOC1;
noperspective centroid float2 linear_centroid : LOC2;
noperspective sample float3 linear_sample : LOC3;
linear float4 perspective : LOC4;
diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl
--- a/tests/out/hlsl/interpolate.hlsl
+++ b/tests/out/hlsl/interpolate.hlsl
@@ -12,7 +12,7 @@ struct FragmentInput {
struct VertexOutput_main {
uint flat : LOC0;
- float linear1 : LOC1;
+ float linear_ : LOC1;
float2 linear_centroid : LOC2;
float3 linear_sample : LOC3;
float4 perspective : LOC4;
diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl
--- a/tests/out/hlsl/interpolate.hlsl
+++ b/tests/out/hlsl/interpolate.hlsl
@@ -22,36 +22,36 @@ struct VertexOutput_main {
};
struct FragmentInput_main {
- uint flat1 : LOC0;
- float linear2 : LOC1;
- float2 linear_centroid1 : LOC2;
- float3 linear_sample1 : LOC3;
- float4 perspective1 : LOC4;
- float perspective_centroid1 : LOC5;
- float perspective_sample1 : LOC6;
- float4 position1 : SV_Position;
+ uint flat_1 : LOC0;
+ float linear_1 : LOC1;
+ float2 linear_centroid_1 : LOC2;
+ float3 linear_sample_1 : LOC3;
+ float4 perspective_1 : LOC4;
+ float perspective_centroid_1 : LOC5;
+ float perspective_sample_1 : LOC6;
+ float4 position_1 : SV_Position;
};
VertexOutput_main main()
{
- FragmentInput out1 = (FragmentInput)0;
+ FragmentInput out_ = (FragmentInput)0;
- out1.position = float4(2.0, 4.0, 5.0, 6.0);
- out1.flat = 8u;
- out1.linear1 = 27.0;
- out1.linear_centroid = float2(64.0, 125.0);
- out1.linear_sample = float3(216.0, 343.0, 512.0);
- out1.perspective = float4(729.0, 1000.0, 1331.0, 1728.0);
- out1.perspective_centroid = 2197.0;
- out1.perspective_sample = 2744.0;
- FragmentInput _expr30 = out1;
+ out_.position = float4(2.0, 4.0, 5.0, 6.0);
+ out_.flat = 8u;
+ out_.linear_ = 27.0;
+ out_.linear_centroid = float2(64.0, 125.0);
+ out_.linear_sample = float3(216.0, 343.0, 512.0);
+ out_.perspective = float4(729.0, 1000.0, 1331.0, 1728.0);
+ out_.perspective_centroid = 2197.0;
+ out_.perspective_sample = 2744.0;
+ FragmentInput _expr30 = out_;
const FragmentInput fragmentinput = _expr30;
- const VertexOutput_main fragmentinput1 = { fragmentinput.flat, fragmentinput.linear1, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position };
- return fragmentinput1;
+ const VertexOutput_main fragmentinput_1 = { fragmentinput.flat, fragmentinput.linear_, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position };
+ return fragmentinput_1;
}
-void main1(FragmentInput_main fragmentinput_main)
+void main_1(FragmentInput_main fragmentinput_main)
{
- FragmentInput val = { fragmentinput_main.position1, fragmentinput_main.flat1, fragmentinput_main.linear2, fragmentinput_main.linear_centroid1, fragmentinput_main.linear_sample1, fragmentinput_main.perspective1, fragmentinput_main.perspective_centroid1, fragmentinput_main.perspective_sample1 };
+ FragmentInput val = { fragmentinput_main.position_1, fragmentinput_main.flat_1, fragmentinput_main.linear_1, fragmentinput_main.linear_centroid_1, fragmentinput_main.linear_sample_1, fragmentinput_main.perspective_1, fragmentinput_main.perspective_centroid_1, fragmentinput_main.perspective_sample_1 };
return;
}
diff --git a/tests/out/hlsl/interpolate.hlsl.config b/tests/out/hlsl/interpolate.hlsl.config
--- a/tests/out/hlsl/interpolate.hlsl.config
+++ b/tests/out/hlsl/interpolate.hlsl.config
@@ -1,3 +1,3 @@
vertex=(main:vs_5_1 )
-fragment=(main1:ps_5_1 )
+fragment=(main_1:ps_5_1 )
compute=()
diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
--- a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
+++ b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
@@ -1,7 +1,7 @@
static float a = (float)0;
-void main1()
+void main_1()
{
float b = (float)0;
float c = (float)0;
diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
--- a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
+++ b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
@@ -18,5 +18,5 @@ void main1()
void main()
{
- main1();
+ main_1();
}
diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl
--- a/tests/out/hlsl/operators.hlsl
+++ b/tests/out/hlsl/operators.hlsl
@@ -61,8 +61,8 @@ float constructors()
void modulo()
{
- int a1 = (1 % 1);
- float b1 = (1.0 % 1.0);
+ int a_1 = (1 % 1);
+ float b_1 = (1.0 % 1.0);
int3 c = (int3(1.xxx) % int3(1.xxx));
float3 d = (float3(1.0.xxx) % float3(1.0.xxx));
}
diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl
--- a/tests/out/hlsl/quad-vert.hlsl
+++ b/tests/out/hlsl/quad-vert.hlsl
@@ -6,57 +6,45 @@ struct gl_PerVertex {
float gl_CullDistance[1] : SV_CullDistance;
};
-struct type9 {
+struct type_9 {
linear float2 member : LOC0;
float4 gl_Position : SV_Position;
- float gl_PointSize : PSIZE;
- float gl_ClipDistance[1] : SV_ClipDistance;
- float gl_CullDistance[1] : SV_CullDistance;
};
static float2 v_uv = (float2)0;
-static float2 a_uv1 = (float2)0;
+static float2 a_uv_1 = (float2)0;
static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, { 0.0 }, { 0.0 } };
-static float2 a_pos1 = (float2)0;
+static float2 a_pos_1 = (float2)0;
struct VertexOutput_main {
float2 member : LOC0;
float4 gl_Position : SV_Position;
- float gl_ClipDistance : SV_ClipDistance;
- float gl_CullDistance : SV_CullDistance;
- float gl_PointSize : PSIZE;
};
-void main1()
+void main_1()
{
- float2 _expr12 = a_uv1;
+ float2 _expr12 = a_uv_1;
v_uv = _expr12;
- float2 _expr13 = a_pos1;
+ float2 _expr13 = a_pos_1;
perVertexStruct.gl_Position = float4(_expr13.x, _expr13.y, 0.0, 1.0);
return;
}
-type9 Constructtype9(float2 arg0, float4 arg1, float arg2, float arg3[1], float arg4[1]) {
- type9 ret;
+type_9 Constructtype_9(float2 arg0, float4 arg1) {
+ type_9 ret;
ret.member = arg0;
ret.gl_Position = arg1;
- ret.gl_PointSize = arg2;
- ret.gl_ClipDistance = arg3;
- ret.gl_CullDistance = arg4;
return ret;
}
VertexOutput_main main(float2 a_uv : LOC1, float2 a_pos : LOC0)
{
- a_uv1 = a_uv;
- a_pos1 = a_pos;
- main1();
- float2 _expr10 = v_uv;
- float4 _expr11 = perVertexStruct.gl_Position;
- float _expr12 = perVertexStruct.gl_PointSize;
- float _expr13[1] = perVertexStruct.gl_ClipDistance;
- float _expr14[1] = perVertexStruct.gl_CullDistance;
- const type9 type9_ = Constructtype9(_expr10, _expr11, _expr12, _expr13, _expr14);
- const VertexOutput_main type9_1 = { type9_.member, type9_.gl_Position, type9_.gl_ClipDistance, type9_.gl_CullDistance, type9_.gl_PointSize };
- return type9_1;
+ a_uv_1 = a_uv;
+ a_pos_1 = a_pos;
+ main_1();
+ float2 _expr7 = v_uv;
+ float4 _expr8 = perVertexStruct.gl_Position;
+ const type_9 type_9_ = Constructtype_9(_expr7, _expr8);
+ const VertexOutput_main type_9_1 = { type_9_.member, type_9_.gl_Position };
+ return type_9_1;
}
diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl
--- a/tests/out/hlsl/quad.hlsl
+++ b/tests/out/hlsl/quad.hlsl
@@ -9,12 +9,12 @@ Texture2D<float4> u_texture : register(t0);
SamplerState u_sampler : register(s1);
struct VertexOutput_main {
- float2 uv2 : LOC0;
+ float2 uv_2 : LOC0;
float4 position : SV_Position;
};
struct FragmentInput_main {
- float2 uv3 : LOC0;
+ float2 uv_3 : LOC0;
};
VertexOutput ConstructVertexOutput(float2 arg0, float4 arg1) {
diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl
--- a/tests/out/hlsl/quad.hlsl
+++ b/tests/out/hlsl/quad.hlsl
@@ -27,14 +27,14 @@ VertexOutput ConstructVertexOutput(float2 arg0, float4 arg1) {
VertexOutput_main main(float2 pos : LOC0, float2 uv : LOC1)
{
const VertexOutput vertexoutput = ConstructVertexOutput(uv, float4((c_scale * pos), 0.0, 1.0));
- const VertexOutput_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position };
- return vertexoutput1;
+ const VertexOutput_main vertexoutput_1 = { vertexoutput.uv, vertexoutput.position };
+ return vertexoutput_1;
}
-float4 main1(FragmentInput_main fragmentinput_main) : SV_Target0
+float4 main_1(FragmentInput_main fragmentinput_main) : SV_Target0
{
- float2 uv1 = fragmentinput_main.uv3;
- float4 color = u_texture.Sample(u_sampler, uv1);
+ float2 uv_1 = fragmentinput_main.uv_3;
+ float4 color = u_texture.Sample(u_sampler, uv_1);
if ((color.w == 0.0)) {
discard;
}
diff --git a/tests/out/hlsl/quad.hlsl.config b/tests/out/hlsl/quad.hlsl.config
--- a/tests/out/hlsl/quad.hlsl.config
+++ b/tests/out/hlsl/quad.hlsl.config
@@ -1,3 +1,3 @@
vertex=(main:vs_5_1 )
-fragment=(main1:ps_5_1 fs_extra:ps_5_1 )
+fragment=(main_1:ps_5_1 fs_extra:ps_5_1 )
compute=()
diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl
--- a/tests/out/hlsl/shadow.hlsl
+++ b/tests/out/hlsl/shadow.hlsl
@@ -17,8 +17,8 @@ Texture2DArray<float> t_shadow : register(t2);
SamplerComparisonState sampler_shadow : register(s3);
struct FragmentInput_fs_main {
- float3 raw_normal1 : LOC0;
- float4 position1 : LOC1;
+ float3 raw_normal_1 : LOC0;
+ float4 position_1 : LOC1;
};
float fetch_shadow(uint light_id, float4 homogeneous_coords)
diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl
--- a/tests/out/hlsl/shadow.hlsl
+++ b/tests/out/hlsl/shadow.hlsl
@@ -34,8 +34,8 @@ float fetch_shadow(uint light_id, float4 homogeneous_coords)
float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0
{
- float3 raw_normal = fragmentinput_fs_main.raw_normal1;
- float4 position = fragmentinput_fs_main.position1;
+ float3 raw_normal = fragmentinput_fs_main.raw_normal_1;
+ float4 position = fragmentinput_fs_main.position_1;
float3 color = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806);
uint i = 0u;
diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl
--- a/tests/out/hlsl/skybox.hlsl
+++ b/tests/out/hlsl/skybox.hlsl
@@ -25,8 +25,8 @@ struct VertexOutput_vs_main {
};
struct FragmentInput_fs_main {
- float3 uv1 : LOC0;
- float4 position1 : SV_Position;
+ float3 uv_1 : LOC0;
+ float4 position_1 : SV_Position;
};
VertexOutput ConstructVertexOutput(float4 arg0, float3 arg1) {
diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl
--- a/tests/out/hlsl/skybox.hlsl
+++ b/tests/out/hlsl/skybox.hlsl
@@ -53,13 +53,13 @@ VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID)
float4x4 _expr40 = r_data.proj_inv;
float4 unprojected = mul(pos, _expr40);
const VertexOutput vertexoutput = ConstructVertexOutput(pos, mul(unprojected.xyz, inv_model_view));
- const VertexOutput_vs_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position };
- return vertexoutput1;
+ const VertexOutput_vs_main vertexoutput_1 = { vertexoutput.uv, vertexoutput.position };
+ return vertexoutput_1;
}
float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0
{
- VertexOutput in1 = { fragmentinput_fs_main.position1, fragmentinput_fs_main.uv1 };
- float4 _expr5 = r_texture.Sample(r_sampler, in1.uv);
+ VertexOutput in_ = { fragmentinput_fs_main.position_1, fragmentinput_fs_main.uv_1 };
+ float4 _expr5 = r_texture.Sample(r_sampler, in_.uv);
return _expr5;
}
diff --git a/tests/out/hlsl/standard.hlsl b/tests/out/hlsl/standard.hlsl
--- a/tests/out/hlsl/standard.hlsl
+++ b/tests/out/hlsl/standard.hlsl
@@ -1,11 +1,11 @@
struct FragmentInput_derivatives {
- float4 foo1 : SV_Position;
+ float4 foo_1 : SV_Position;
};
float4 derivatives(FragmentInput_derivatives fragmentinput_derivatives) : SV_Target0
{
- float4 foo = fragmentinput_derivatives.foo1;
+ float4 foo = fragmentinput_derivatives.foo_1;
float4 x = ddx(foo);
float4 y = ddy(foo);
float4 z = fwidth(foo);
diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl
--- a/tests/out/msl/access.msl
+++ b/tests/out/msl/access.msl
@@ -6,25 +6,25 @@ struct _mslBufferSizes {
metal::uint size0;
};
-struct type3 {
+struct type_3 {
metal::uint2 inner[2];
};
-typedef int type5[1];
+typedef int type_5[1];
struct Bar {
metal::float4x4 matrix;
metal::atomic_int atom;
char _pad2[4];
- type3 arr;
- type5 data;
+ type_3 arr;
+ type_5 data;
};
-struct type11 {
+struct type_11 {
int inner[5];
};
float read_from_private(
- thread float& foo2
+ thread float& foo_2
) {
- float _e2 = foo2;
+ float _e2 = foo_2;
return _e2;
}
diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl
--- a/tests/out/msl/access.msl
+++ b/tests/out/msl/access.msl
@@ -38,19 +38,20 @@ vertex fooOutput foo(
, device Bar& bar [[buffer(0)]]
, constant _mslBufferSizes& _buffer_sizes [[buffer(24)]]
) {
- float foo1 = 0.0;
- type11 c;
- float baz = foo1;
- foo1 = 1.0;
+ float foo_1 = 0.0;
+ type_11 c;
+ float baz = foo_1;
+ foo_1 = 1.0;
metal::float4x4 matrix = bar.matrix;
- type3 arr = bar.arr;
+ type_3 arr = bar.arr;
float b = bar.matrix[3].x;
- int a = bar.data[(1 + (_buffer_sizes.size0 - 88 - 4) / 4) - 2u];
- float _e25 = read_from_private(foo1);
+ int a = bar.data[(1 + (_buffer_sizes.size0 - 88 - 4) / 8) - 2u];
+ float _e25 = read_from_private(foo_1);
bar.matrix[1].z = 1.0;
bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0));
- for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type3 {metal::uint2(0u), metal::uint2(1u)}.inner[_i];
- for(int _i=0; _i<5; ++_i) c.inner[_i] = type11 {a, static_cast<int>(b), 3, 4, 5}.inner[_i];
+ for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_3 {metal::uint2(0u), metal::uint2(1u)}.inner[_i];
+ bar.data[1] = 1;
+ for(int _i=0; _i<5; ++_i) c.inner[_i] = type_11 {a, static_cast<int>(b), 3, 4, 5}.inner[_i];
c.inner[vi + 1u] = 42;
int value = c.inner[vi];
return fooOutput { matrix * static_cast<metal::float4>(metal::int4(value)) };
diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl
--- a/tests/out/msl/access.msl
+++ b/tests/out/msl/access.msl
@@ -62,7 +63,7 @@ kernel void atomics(
, constant _mslBufferSizes& _buffer_sizes [[buffer(24)]]
) {
int tmp;
- int value1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed);
+ int value_1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed);
int _e6 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed);
tmp = _e6;
int _e9 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed);
diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl
--- a/tests/out/msl/access.msl
+++ b/tests/out/msl/access.msl
@@ -79,6 +80,6 @@ kernel void atomics(
tmp = _e24;
int _e27 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed);
tmp = _e27;
- metal::atomic_store_explicit(&bar.atom, value1, metal::memory_order_relaxed);
+ metal::atomic_store_explicit(&bar.atom, value_1, metal::memory_order_relaxed);
return;
}
diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl
--- a/tests/out/msl/bits.msl
+++ b/tests/out/msl/bits.msl
@@ -3,7 +3,7 @@
#include <simd/simd.h>
-kernel void main1(
+kernel void main_(
) {
int i = 0;
metal::int2 i2_;
diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl
--- a/tests/out/msl/boids.msl
+++ b/tests/out/msl/boids.msl
@@ -21,14 +21,14 @@ struct SimParams {
float rule2Scale;
float rule3Scale;
};
-typedef Particle type3[1];
+typedef Particle type_3[1];
struct Particles {
- type3 particles;
+ type_3 particles;
};
-struct main1Input {
+struct main_Input {
};
-kernel void main1(
+kernel void main_(
metal::uint3 global_invocation_id [[thread_position_in_grid]]
, constant SimParams& params [[buffer(0)]]
, constant Particles& particlesSrc [[buffer(1)]]
diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl
--- a/tests/out/msl/collatz.msl
+++ b/tests/out/msl/collatz.msl
@@ -6,9 +6,9 @@ struct _mslBufferSizes {
metal::uint size0;
};
-typedef metal::uint type1[1];
+typedef metal::uint type_1[1];
struct PrimeIndices {
- type1 data;
+ type_1 data;
};
metal::uint collatz_iterations(
diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl
--- a/tests/out/msl/collatz.msl
+++ b/tests/out/msl/collatz.msl
@@ -37,9 +37,9 @@ metal::uint collatz_iterations(
return _e24;
}
-struct main1Input {
+struct main_Input {
};
-kernel void main1(
+kernel void main_(
metal::uint3 global_id [[thread_position_in_grid]]
, device PrimeIndices& v_indices [[user(fake0)]]
) {
diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl
--- a/tests/out/msl/control-flow.msl
+++ b/tests/out/msl/control-flow.msl
@@ -42,9 +42,9 @@ void loop_switch_continue(
return;
}
-struct main1Input {
+struct main_Input {
};
-kernel void main1(
+kernel void main_(
metal::uint3 global_id [[thread_position_in_grid]]
) {
int pos;
diff --git /dev/null b/tests/out/msl/empty-global-name.msl
new file mode 100644
--- /dev/null
+++ b/tests/out/msl/empty-global-name.msl
@@ -0,0 +1,21 @@
+// language: metal1.1
+#include <metal_stdlib>
+#include <simd/simd.h>
+
+struct type_1 {
+ int member;
+};
+
+void function(
+ device type_1& unnamed
+) {
+ int _e8 = unnamed.member;
+ unnamed.member = _e8 + 1;
+ return;
+}
+
+kernel void main_(
+ device type_1& unnamed [[user(fake0)]]
+) {
+ function(unnamed);
+}
diff --git a/tests/out/msl/empty.msl b/tests/out/msl/empty.msl
--- a/tests/out/msl/empty.msl
+++ b/tests/out/msl/empty.msl
@@ -3,7 +3,7 @@
#include <simd/simd.h>
-kernel void main1(
+kernel void main_(
) {
return;
}
diff --git a/tests/out/msl/extra.msl b/tests/out/msl/extra.msl
--- a/tests/out/msl/extra.msl
+++ b/tests/out/msl/extra.msl
@@ -5,27 +5,27 @@
struct PushConstants {
metal::uint index;
char _pad1[12];
- metal::float2 double1;
+ metal::float2 double_;
};
struct FragmentIn {
metal::float4 color;
metal::uint primitive_index;
};
-struct main1Input {
+struct main_Input {
metal::float4 color [[user(loc0), center_perspective]];
};
-struct main1Output {
+struct main_Output {
metal::float4 member [[color(0)]];
};
-fragment main1Output main1(
- main1Input varyings [[stage_in]]
+fragment main_Output main_(
+ main_Input varyings [[stage_in]]
, metal::uint primitive_index [[primitive_id]]
) {
const FragmentIn in = { varyings.color, primitive_index };
if ((in.primitive_index % 2u) == 0u) {
- return main1Output { in.color };
+ return main_Output { in.color };
} else {
- return main1Output { metal::float4(metal::float3(1.0) - in.color.xyz, in.color.w) };
+ return main_Output { metal::float4(metal::float3(1.0) - in.color.xyz, in.color.w) };
}
}
diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl
--- a/tests/out/msl/globals.msl
+++ b/tests/out/msl/globals.msl
@@ -3,12 +3,12 @@
#include <simd/simd.h>
constexpr constant bool Foo = true;
-struct type2 {
+struct type_2 {
float inner[10u];
};
-kernel void main1(
- threadgroup type2& wg
+kernel void main_(
+ threadgroup type_2& wg
, threadgroup metal::atomic_uint& at
) {
wg.inner[3] = 1.0;
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -2,11 +2,11 @@
#include <metal_stdlib>
#include <simd/simd.h>
-constant metal::int2 const_type8_ = {3, 1};
+constant metal::int2 const_type_8_ = {3, 1};
-struct main1Input {
+struct main_Input {
};
-kernel void main1(
+kernel void main_(
metal::uint3 local_id [[thread_position_in_threadgroup]]
, metal::texture2d<uint, metal::access::sample> image_mipmapped_src [[user(fake0)]]
, metal::texture2d_ms<uint, metal::access::read> image_multisampled_src [[user(fake0)]]
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -28,21 +28,21 @@ kernel void main1(
struct depth_loadInput {
};
kernel void depth_load(
- metal::uint3 local_id1 [[thread_position_in_threadgroup]]
+ metal::uint3 local_id_1 [[thread_position_in_threadgroup]]
, metal::depth2d_ms<float, metal::access::read> image_depth_multisampled_src [[user(fake0)]]
, metal::texture2d<uint, metal::access::read> image_storage_src [[user(fake0)]]
, metal::texture1d<uint, metal::access::write> image_dst [[user(fake0)]]
) {
- metal::int2 dim1 = int2(image_storage_src.get_width(), image_storage_src.get_height());
- metal::int2 itc1 = (dim1 * static_cast<metal::int2>(local_id1.xy)) % metal::int2(10, 20);
- float val = image_depth_multisampled_src.read(metal::uint2(itc1), static_cast<int>(local_id1.z));
- image_dst.write(metal::uint4(static_cast<uint>(val)), metal::uint(itc1.x));
+ metal::int2 dim_1 = int2(image_storage_src.get_width(), image_storage_src.get_height());
+ metal::int2 itc_1 = (dim_1 * static_cast<metal::int2>(local_id_1.xy)) % metal::int2(10, 20);
+ float val = image_depth_multisampled_src.read(metal::uint2(itc_1), static_cast<int>(local_id_1.z));
+ image_dst.write(metal::uint4(static_cast<uint>(val)), metal::uint(itc_1.x));
return;
}
struct queriesOutput {
- metal::float4 member2 [[position]];
+ metal::float4 member_2 [[position]];
};
vertex queriesOutput queries(
metal::texture1d<float, metal::access::sample> image_1d [[user(fake0)]]
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -69,7 +69,7 @@ vertex queriesOutput queries(
struct levels_queriesOutput {
- metal::float4 member3 [[position]];
+ metal::float4 member_3 [[position]];
};
vertex levels_queriesOutput levels_queries(
metal::texture2d<float, metal::access::sample> image_2d [[user(fake0)]]
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -87,13 +87,13 @@ vertex levels_queriesOutput levels_queries(
int num_layers_cube = int(image_cube_array.get_array_size());
int num_levels_3d = int(image_3d.get_num_mip_levels());
int num_samples_aa = int(image_aa.get_num_samples());
- int sum1 = ((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array;
- return levels_queriesOutput { metal::float4(static_cast<float>(sum1)) };
+ int sum_1 = ((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array;
+ return levels_queriesOutput { metal::float4(static_cast<float>(sum_1)) };
}
struct sampleOutput {
- metal::float4 member4 [[color(0)]];
+ metal::float4 member_4 [[color(0)]];
};
fragment sampleOutput sample(
metal::texture1d<float, metal::access::sample> image_1d [[user(fake0)]]
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -103,22 +103,22 @@ fragment sampleOutput sample(
metal::float2 tc = metal::float2(0.5);
metal::float4 s1d = image_1d.sample(sampler_reg, tc.x);
metal::float4 s2d = image_2d.sample(sampler_reg, tc);
- metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type8_);
+ metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type_8_);
metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284));
- metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type8_);
+ metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_8_);
return sampleOutput { (((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset };
}
struct sample_comparisonOutput {
- float member5 [[color(0)]];
+ float member_5 [[color(0)]];
};
fragment sample_comparisonOutput sample_comparison(
metal::sampler sampler_cmp [[user(fake0)]]
, metal::depth2d<float, metal::access::sample> image_2d_depth [[user(fake0)]]
) {
- metal::float2 tc1 = metal::float2(0.5);
- float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc1, 0.5);
- float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc1, 0.5);
+ metal::float2 tc_1 = metal::float2(0.5);
+ float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5);
+ float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5);
return sample_comparisonOutput { s2d_depth + s2d_depth_level };
}
diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl
--- a/tests/out/msl/interface.msl
+++ b/tests/out/msl/interface.msl
@@ -11,61 +11,61 @@ struct FragmentOutput {
metal::uint sample_mask;
float color;
};
-struct type4 {
+struct type_4 {
metal::uint inner[1];
};
-struct vertex1Input {
+struct vertex_Input {
metal::uint color [[attribute(10)]];
};
-struct vertex1Output {
+struct vertex_Output {
metal::float4 position [[position]];
float varying [[user(loc1), center_perspective]];
};
-vertex vertex1Output vertex1(
- vertex1Input varyings [[stage_in]]
+vertex vertex_Output vertex_(
+ vertex_Input varyings [[stage_in]]
, metal::uint vertex_index [[vertex_id]]
, metal::uint instance_index [[instance_id]]
) {
const auto color = varyings.color;
metal::uint tmp = (vertex_index + instance_index) + color;
const auto _tmp = VertexOutput {metal::float4(1.0), static_cast<float>(tmp)};
- return vertex1Output { _tmp.position, _tmp.varying };
+ return vertex_Output { _tmp.position, _tmp.varying };
}
-struct fragment1Input {
+struct fragment_Input {
float varying [[user(loc1), center_perspective]];
};
-struct fragment1Output {
+struct fragment_Output {
float depth [[depth(any)]];
metal::uint sample_mask [[sample_mask]];
float color [[color(0)]];
};
-fragment fragment1Output fragment1(
- fragment1Input varyings1 [[stage_in]]
+fragment fragment_Output fragment_(
+ fragment_Input varyings_1 [[stage_in]]
, metal::float4 position [[position]]
, bool front_facing [[front_facing]]
, metal::uint sample_index [[sample_id]]
, metal::uint sample_mask [[sample_mask]]
) {
- const VertexOutput in = { position, varyings1.varying };
+ const VertexOutput in = { position, varyings_1.varying };
metal::uint mask = sample_mask & (1u << sample_index);
- float color1 = front_facing ? 1.0 : 0.0;
- const auto _tmp = FragmentOutput {in.varying, mask, color1};
- return fragment1Output { _tmp.depth, _tmp.sample_mask, _tmp.color };
+ float color_1 = front_facing ? 1.0 : 0.0;
+ const auto _tmp = FragmentOutput {in.varying, mask, color_1};
+ return fragment_Output { _tmp.depth, _tmp.sample_mask, _tmp.color };
}
-struct compute1Input {
+struct compute_Input {
};
-kernel void compute1(
+kernel void compute_(
metal::uint3 global_id [[thread_position_in_grid]]
, metal::uint3 local_id [[thread_position_in_threadgroup]]
, metal::uint local_index [[thread_index_in_threadgroup]]
, metal::uint3 wg_id [[threadgroup_position_in_grid]]
, metal::uint3 num_wgs [[threadgroups_per_grid]]
-, threadgroup type4& output
+, threadgroup type_4& output
) {
output.inner[0] = (((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x;
return;
diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl
--- a/tests/out/msl/interpolate.msl
+++ b/tests/out/msl/interpolate.msl
@@ -13,7 +13,7 @@ struct FragmentInput {
float perspective_sample;
};
-struct main1Output {
+struct main_Output {
metal::float4 position [[position]];
metal::uint flat [[user(loc0), flat]];
float linear [[user(loc1), center_no_perspective]];
diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl
--- a/tests/out/msl/interpolate.msl
+++ b/tests/out/msl/interpolate.msl
@@ -23,7 +23,7 @@ struct main1Output {
float perspective_centroid [[user(loc5), centroid_perspective]];
float perspective_sample [[user(loc6), sample_perspective]];
};
-vertex main1Output main1(
+vertex main_Output main_(
) {
FragmentInput out;
out.position = metal::float4(2.0, 4.0, 5.0, 6.0);
diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl
--- a/tests/out/msl/interpolate.msl
+++ b/tests/out/msl/interpolate.msl
@@ -36,11 +36,11 @@ vertex main1Output main1(
out.perspective_sample = 2744.0;
FragmentInput _e30 = out;
const auto _tmp = _e30;
- return main1Output { _tmp.position, _tmp.flat, _tmp.linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample };
+ return main_Output { _tmp.position, _tmp.flat, _tmp.linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample };
}
-struct main2Input {
+struct main_1Input {
metal::uint flat [[user(loc0), flat]];
float linear [[user(loc1), center_no_perspective]];
metal::float2 linear_centroid [[user(loc2), centroid_no_perspective]];
diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl
--- a/tests/out/msl/interpolate.msl
+++ b/tests/out/msl/interpolate.msl
@@ -49,10 +49,10 @@ struct main2Input {
float perspective_centroid [[user(loc5), centroid_perspective]];
float perspective_sample [[user(loc6), sample_perspective]];
};
-fragment void main2(
- main2Input varyings1 [[stage_in]]
+fragment void main_1(
+ main_1Input varyings_1 [[stage_in]]
, metal::float4 position [[position]]
) {
- const FragmentInput val = { position, varyings1.flat, varyings1.linear, varyings1.linear_centroid, varyings1.linear_sample, varyings1.perspective, varyings1.perspective_centroid, varyings1.perspective_sample };
+ const FragmentInput val = { position, varyings_1.flat, varyings_1.linear, varyings_1.linear_centroid, varyings_1.linear_sample, varyings_1.perspective, varyings_1.perspective_centroid, varyings_1.perspective_sample };
return;
}
diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl
--- a/tests/out/msl/operators.msl
+++ b/tests/out/msl/operators.msl
@@ -57,13 +57,13 @@ float constructors(
void modulo(
) {
- int a1 = 1 % 1;
- float b1 = metal::fmod(1.0, 1.0);
+ int a_1 = 1 % 1;
+ float b_1 = metal::fmod(1.0, 1.0);
metal::int3 c = metal::int3(1) % metal::int3(1);
metal::float3 d = metal::fmod(metal::float3(1.0), metal::float3(1.0));
}
-kernel void main1(
+kernel void main_(
) {
metal::float4 _e4 = builtins();
metal::float4 _e5 = splat();
diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl
--- a/tests/out/msl/quad-vert.msl
+++ b/tests/out/msl/quad-vert.msl
@@ -2,66 +2,58 @@
#include <metal_stdlib>
#include <simd/simd.h>
-struct type5 {
+struct type_5 {
float inner[1u];
};
struct gl_PerVertex {
metal::float4 gl_Position;
float gl_PointSize;
- type5 gl_ClipDistance;
- type5 gl_CullDistance;
+ type_5 gl_ClipDistance;
+ type_5 gl_CullDistance;
};
-struct type9 {
+struct type_9 {
metal::float2 member;
metal::float4 gl_Position;
- float gl_PointSize;
- type5 gl_ClipDistance;
- type5 gl_CullDistance;
};
-constant metal::float4 const_type3_ = {0.0, 0.0, 0.0, 1.0};
-constant type5 const_type5_ = {0.0};
-constant gl_PerVertex const_gl_PerVertex = {const_type3_, 1.0, const_type5_, const_type5_};
+constant metal::float4 const_type_3_ = {0.0, 0.0, 0.0, 1.0};
+constant type_5 const_type_5_ = {0.0};
+constant gl_PerVertex const_gl_PerVertex = {const_type_3_, 1.0, const_type_5_, const_type_5_};
-void main2(
+void main_1(
thread metal::float2& v_uv,
- thread metal::float2 const& a_uv1,
+ thread metal::float2 const& a_uv_1,
thread gl_PerVertex& perVertexStruct,
- thread metal::float2 const& a_pos1
+ thread metal::float2 const& a_pos_1
) {
- metal::float2 _e12 = a_uv1;
+ metal::float2 _e12 = a_uv_1;
v_uv = _e12;
- metal::float2 _e13 = a_pos1;
+ metal::float2 _e13 = a_pos_1;
perVertexStruct.gl_Position = metal::float4(_e13.x, _e13.y, 0.0, 1.0);
return;
}
-struct main1Input {
+struct main_Input {
metal::float2 a_uv [[attribute(1)]];
metal::float2 a_pos [[attribute(0)]];
};
-struct main1Output {
+struct main_Output {
metal::float2 member [[user(loc0), center_perspective]];
metal::float4 gl_Position [[position]];
- float gl_PointSize [[point_size]];
- float gl_ClipDistance [[clip_distance]] [1];
};
-vertex main1Output main1(
- main1Input varyings [[stage_in]]
+vertex main_Output main_(
+ main_Input varyings [[stage_in]]
) {
metal::float2 v_uv = {};
- metal::float2 a_uv1 = {};
+ metal::float2 a_uv_1 = {};
gl_PerVertex perVertexStruct = const_gl_PerVertex;
- metal::float2 a_pos1 = {};
+ metal::float2 a_pos_1 = {};
const auto a_uv = varyings.a_uv;
const auto a_pos = varyings.a_pos;
- a_uv1 = a_uv;
- a_pos1 = a_pos;
- main2(v_uv, a_uv1, perVertexStruct, a_pos1);
- metal::float2 _e10 = v_uv;
- metal::float4 _e11 = perVertexStruct.gl_Position;
- float _e12 = perVertexStruct.gl_PointSize;
- type5 _e13 = perVertexStruct.gl_ClipDistance;
- type5 _e14 = perVertexStruct.gl_CullDistance;
- const auto _tmp = type9 {_e10, _e11, _e12, _e13, _e14};
- return main1Output { _tmp.member, _tmp.gl_Position, _tmp.gl_PointSize, {_tmp.gl_ClipDistance.inner[0]} };
+ a_uv_1 = a_uv;
+ a_pos_1 = a_pos;
+ main_1(v_uv, a_uv_1, perVertexStruct, a_pos_1);
+ metal::float2 _e7 = v_uv;
+ metal::float4 _e8 = perVertexStruct.gl_Position;
+ const auto _tmp = type_9 {_e7, _e8};
+ return main_Output { _tmp.member, _tmp.gl_Position };
}
diff --git a/tests/out/msl/quad.msl b/tests/out/msl/quad.msl
--- a/tests/out/msl/quad.msl
+++ b/tests/out/msl/quad.msl
@@ -8,47 +8,47 @@ struct VertexOutput {
metal::float4 position;
};
-struct main1Input {
+struct main_Input {
metal::float2 pos [[attribute(0)]];
metal::float2 uv [[attribute(1)]];
};
-struct main1Output {
+struct main_Output {
metal::float2 uv [[user(loc0), center_perspective]];
metal::float4 position [[position]];
};
-vertex main1Output main1(
- main1Input varyings [[stage_in]]
+vertex main_Output main_(
+ main_Input varyings [[stage_in]]
) {
const auto pos = varyings.pos;
const auto uv = varyings.uv;
const auto _tmp = VertexOutput {uv, metal::float4(c_scale * pos, 0.0, 1.0)};
- return main1Output { _tmp.uv, _tmp.position };
+ return main_Output { _tmp.uv, _tmp.position };
}
-struct main2Input {
- metal::float2 uv1 [[user(loc0), center_perspective]];
+struct main_1Input {
+ metal::float2 uv_1 [[user(loc0), center_perspective]];
};
-struct main2Output {
- metal::float4 member1 [[color(0)]];
+struct main_1Output {
+ metal::float4 member_1 [[color(0)]];
};
-fragment main2Output main2(
- main2Input varyings1 [[stage_in]]
+fragment main_1Output main_1(
+ main_1Input varyings_1 [[stage_in]]
, metal::texture2d<float, metal::access::sample> u_texture [[user(fake0)]]
, metal::sampler u_sampler [[user(fake0)]]
) {
- const auto uv1 = varyings1.uv1;
- metal::float4 color = u_texture.sample(u_sampler, uv1);
+ const auto uv_1 = varyings_1.uv_1;
+ metal::float4 color = u_texture.sample(u_sampler, uv_1);
if (color.w == 0.0) {
metal::discard_fragment();
}
metal::float4 premultiplied = color.w * color;
- return main2Output { premultiplied };
+ return main_1Output { premultiplied };
}
struct fs_extraOutput {
- metal::float4 member2 [[color(0)]];
+ metal::float4 member_2 [[color(0)]];
};
fragment fs_extraOutput fs_extra(
) {
diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl
--- a/tests/out/msl/shadow.msl
+++ b/tests/out/msl/shadow.msl
@@ -15,9 +15,9 @@ struct Light {
metal::float4 pos;
metal::float4 color;
};
-typedef Light type3[1];
+typedef Light type_3[1];
struct Lights {
- type3 data;
+ type_3 data;
};
constant metal::float3 c_ambient = {0.05000000074505806, 0.05000000074505806, 0.05000000074505806};
diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl
--- a/tests/out/msl/skybox.msl
+++ b/tests/out/msl/skybox.msl
@@ -43,10 +43,10 @@ struct fs_mainInput {
metal::float3 uv [[user(loc0), center_perspective]];
};
struct fs_mainOutput {
- metal::float4 member1 [[color(0)]];
+ metal::float4 member_1 [[color(0)]];
};
fragment fs_mainOutput fs_main(
- fs_mainInput varyings1 [[stage_in]]
+ fs_mainInput varyings_1 [[stage_in]]
, metal::float4 position [[position]]
, metal::texturecube<float, metal::access::sample> r_texture [[texture(0)]]
) {
diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl
--- a/tests/out/msl/skybox.msl
+++ b/tests/out/msl/skybox.msl
@@ -58,7 +58,7 @@ fragment fs_mainOutput fs_main(
metal::min_filter::linear,
metal::coord::normalized
);
- const VertexOutput in = { position, varyings1.uv };
+ const VertexOutput in = { position, varyings_1.uv };
metal::float4 _e5 = r_texture.sample(r_sampler, in.uv);
return fs_mainOutput { _e5 };
}
diff --git a/tests/out/msl/texture-arg.msl b/tests/out/msl/texture-arg.msl
--- a/tests/out/msl/texture-arg.msl
+++ b/tests/out/msl/texture-arg.msl
@@ -11,13 +11,13 @@ metal::float4 test(
return _e7;
}
-struct main1Output {
+struct main_Output {
metal::float4 member [[color(0)]];
};
-fragment main1Output main1(
+fragment main_Output main_(
metal::texture2d<float, metal::access::sample> Texture [[user(fake0)]]
, metal::sampler Sampler [[user(fake0)]]
) {
metal::float4 _e2 = test(Texture, Sampler);
- return main1Output { _e2 };
+ return main_Output { _e2 };
}
diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm
--- a/tests/out/spv/access.spvasm
+++ b/tests/out/spv/access.spvasm
@@ -1,14 +1,14 @@
; SPIR-V
; Version: 1.1
; Generator: rspirv
-; Bound: 114
+; Bound: 115
OpCapability Shader
OpExtension "SPV_KHR_storage_buffer_storage_class"
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Vertex %47 "foo" %42 %45
-OpEntryPoint GLCompute %91 "atomics"
-OpExecutionMode %91 LocalSize 1 1 1
+OpEntryPoint GLCompute %92 "atomics"
+OpExecutionMode %92 LocalSize 1 1 1
OpSource GLSL 450
OpMemberName %26 0 "matrix"
OpMemberName %26 1 "atom"
diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm
--- a/tests/out/spv/access.spvasm
+++ b/tests/out/spv/access.spvasm
@@ -21,10 +21,10 @@ OpName %38 "foo"
OpName %39 "c"
OpName %42 "vi"
OpName %47 "foo"
-OpName %89 "tmp"
-OpName %91 "atomics"
+OpName %90 "tmp"
+OpName %92 "atomics"
OpDecorate %24 ArrayStride 8
-OpDecorate %25 ArrayStride 4
+OpDecorate %25 ArrayStride 8
OpDecorate %26 Block
OpMemberDecorate %26 0 Offset 0
OpMemberDecorate %26 0 ColMajor
diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm
--- a/tests/out/spv/access.spvasm
+++ b/tests/out/spv/access.spvasm
@@ -79,10 +79,10 @@ OpDecorate %45 BuiltIn Position
%57 = OpTypePointer StorageBuffer %22
%58 = OpTypePointer StorageBuffer %6
%61 = OpTypePointer StorageBuffer %25
-%81 = OpTypePointer Function %4
-%85 = OpTypeVector %4 4
-%93 = OpTypePointer StorageBuffer %4
-%96 = OpConstant %9 64
+%82 = OpTypePointer Function %4
+%86 = OpTypeVector %4 4
+%94 = OpTypePointer StorageBuffer %4
+%97 = OpConstant %9 64
%34 = OpFunction %6 None %35
%33 = OpFunctionParameter %27
%32 = OpLabel
diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm
--- a/tests/out/spv/access.spvasm
+++ b/tests/out/spv/access.spvasm
@@ -125,52 +125,54 @@ OpStore %73 %72
%76 = OpCompositeConstruct %24 %74 %75
%77 = OpAccessChain %54 %30 %10
OpStore %77 %76
-%78 = OpConvertFToS %4 %60
-%79 = OpCompositeConstruct %29 %65 %78 %18 %19 %17
-OpStore %39 %79
-%80 = OpIAdd %9 %44 %16
-%82 = OpAccessChain %81 %39 %80
-OpStore %82 %20
-%83 = OpAccessChain %81 %39 %44
-%84 = OpLoad %4 %83
-%86 = OpCompositeConstruct %85 %84 %84 %84 %84
-%87 = OpConvertSToF %22 %86
-%88 = OpMatrixTimesVector %22 %53 %87
-OpStore %45 %88
+%78 = OpAccessChain %28 %30 %8 %16
+OpStore %78 %12
+%79 = OpConvertFToS %4 %60
+%80 = OpCompositeConstruct %29 %65 %79 %18 %19 %17
+OpStore %39 %80
+%81 = OpIAdd %9 %44 %16
+%83 = OpAccessChain %82 %39 %81
+OpStore %83 %20
+%84 = OpAccessChain %82 %39 %44
+%85 = OpLoad %4 %84
+%87 = OpCompositeConstruct %86 %85 %85 %85 %85
+%88 = OpConvertSToF %22 %87
+%89 = OpMatrixTimesVector %22 %53 %88
+OpStore %45 %89
OpReturn
OpFunctionEnd
-%91 = OpFunction %2 None %48
-%90 = OpLabel
-%89 = OpVariable %81 Function
-OpBranch %92
-%92 = OpLabel
-%94 = OpAccessChain %93 %30 %16
-%95 = OpAtomicLoad %4 %94 %12 %96
-%98 = OpAccessChain %93 %30 %16
-%97 = OpAtomicIAdd %4 %98 %12 %96 %17
-OpStore %89 %97
-%100 = OpAccessChain %93 %30 %16
-%99 = OpAtomicISub %4 %100 %12 %96 %17
-OpStore %89 %99
-%102 = OpAccessChain %93 %30 %16
-%101 = OpAtomicAnd %4 %102 %12 %96 %17
-OpStore %89 %101
-%104 = OpAccessChain %93 %30 %16
-%103 = OpAtomicOr %4 %104 %12 %96 %17
-OpStore %89 %103
-%106 = OpAccessChain %93 %30 %16
-%105 = OpAtomicXor %4 %106 %12 %96 %17
-OpStore %89 %105
-%108 = OpAccessChain %93 %30 %16
-%107 = OpAtomicSMin %4 %108 %12 %96 %17
-OpStore %89 %107
-%110 = OpAccessChain %93 %30 %16
-%109 = OpAtomicSMax %4 %110 %12 %96 %17
-OpStore %89 %109
-%112 = OpAccessChain %93 %30 %16
-%111 = OpAtomicExchange %4 %112 %12 %96 %17
-OpStore %89 %111
-%113 = OpAccessChain %93 %30 %16
-OpAtomicStore %113 %12 %96 %95
+%92 = OpFunction %2 None %48
+%91 = OpLabel
+%90 = OpVariable %82 Function
+OpBranch %93
+%93 = OpLabel
+%95 = OpAccessChain %94 %30 %16
+%96 = OpAtomicLoad %4 %95 %12 %97
+%99 = OpAccessChain %94 %30 %16
+%98 = OpAtomicIAdd %4 %99 %12 %97 %17
+OpStore %90 %98
+%101 = OpAccessChain %94 %30 %16
+%100 = OpAtomicISub %4 %101 %12 %97 %17
+OpStore %90 %100
+%103 = OpAccessChain %94 %30 %16
+%102 = OpAtomicAnd %4 %103 %12 %97 %17
+OpStore %90 %102
+%105 = OpAccessChain %94 %30 %16
+%104 = OpAtomicOr %4 %105 %12 %97 %17
+OpStore %90 %104
+%107 = OpAccessChain %94 %30 %16
+%106 = OpAtomicXor %4 %107 %12 %97 %17
+OpStore %90 %106
+%109 = OpAccessChain %94 %30 %16
+%108 = OpAtomicSMin %4 %109 %12 %97 %17
+OpStore %90 %108
+%111 = OpAccessChain %94 %30 %16
+%110 = OpAtomicSMax %4 %111 %12 %97 %17
+OpStore %90 %110
+%113 = OpAccessChain %94 %30 %16
+%112 = OpAtomicExchange %4 %113 %12 %97 %17
+OpStore %90 %112
+%114 = OpAccessChain %94 %30 %16
+OpAtomicStore %114 %12 %97 %96
OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm
--- a/tests/out/spv/bounds-check-zero.spvasm
+++ b/tests/out/spv/bounds-check-zero.spvasm
@@ -14,7 +14,6 @@ OpMemberDecorate %9 1 Offset 48
OpMemberDecorate %9 2 Offset 64
OpMemberDecorate %9 2 ColMajor
OpMemberDecorate %9 2 MatrixStride 16
-OpDecorate %10 NonWritable
OpDecorate %10 DescriptorSet 0
OpDecorate %10 Binding 0
%2 = OpTypeVoid
diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
--- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
+++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
@@ -7,12 +7,12 @@ struct FragmentOutput {
[[location(0)]] o_Target: vec4<f32>;
};
-var<private> v_Uv1: vec2<f32>;
+var<private> v_Uv_1: vec2<f32>;
var<private> o_Target: vec4<f32>;
[[group(1), binding(0)]]
var<uniform> global: ColorMaterial_color;
-fn main1() {
+fn main_1() {
var color: vec4<f32>;
let e4: vec4<f32> = global.Color;
diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
--- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
+++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
@@ -24,8 +24,8 @@ fn main1() {
[[stage(fragment)]]
fn main([[location(0)]] v_Uv: vec2<f32>) -> FragmentOutput {
- v_Uv1 = v_Uv;
- main1();
+ v_Uv_1 = v_Uv;
+ main_1();
let e9: vec4<f32> = o_Target;
return FragmentOutput(e9);
}
diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
--- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
+++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
@@ -18,28 +18,28 @@ struct VertexOutput {
[[builtin(position)]] member: vec4<f32>;
};
-var<private> Vertex_Position1: vec3<f32>;
-var<private> Vertex_Normal1: vec3<f32>;
-var<private> Vertex_Uv1: vec2<f32>;
+var<private> Vertex_Position_1: vec3<f32>;
+var<private> Vertex_Normal_1: vec3<f32>;
+var<private> Vertex_Uv_1: vec2<f32>;
var<private> v_Uv: vec2<f32>;
[[group(0), binding(0)]]
var<uniform> global: Camera;
[[group(2), binding(0)]]
-var<uniform> global1: Transform;
+var<uniform> global_1: Transform;
[[group(2), binding(1)]]
-var<uniform> global2: Sprite_size;
+var<uniform> global_2: Sprite_size;
var<private> gl_Position: vec4<f32>;
-fn main1() {
+fn main_1() {
var position: vec3<f32>;
- let e10: vec2<f32> = Vertex_Uv1;
+ let e10: vec2<f32> = Vertex_Uv_1;
v_Uv = e10;
- let e11: vec3<f32> = Vertex_Position1;
- let e12: vec2<f32> = global2.size;
+ let e11: vec3<f32> = Vertex_Position_1;
+ let e12: vec2<f32> = global_2.size;
position = (e11 * vec3<f32>(e12, 1.0));
let e18: mat4x4<f32> = global.ViewProj;
- let e19: mat4x4<f32> = global1.Model;
+ let e19: mat4x4<f32> = global_1.Model;
let e21: vec3<f32> = position;
gl_Position = ((e18 * e19) * vec4<f32>(e21, 1.0));
return;
diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
--- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
+++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
@@ -47,10 +47,10 @@ fn main1() {
[[stage(vertex)]]
fn main([[location(0)]] Vertex_Position: vec3<f32>, [[location(1)]] Vertex_Normal: vec3<f32>, [[location(2)]] Vertex_Uv: vec2<f32>) -> VertexOutput {
- Vertex_Position1 = Vertex_Position;
- Vertex_Normal1 = Vertex_Normal;
- Vertex_Uv1 = Vertex_Uv;
- main1();
+ Vertex_Position_1 = Vertex_Position;
+ Vertex_Normal_1 = Vertex_Normal;
+ Vertex_Uv_1 = Vertex_Uv;
+ main_1();
let e21: vec2<f32> = v_Uv;
let e23: vec4<f32> = gl_Position;
return VertexOutput(e21, e23);
diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl
--- a/tests/out/wgsl/210-bevy-shader-vert.wgsl
+++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl
@@ -15,29 +15,29 @@ struct VertexOutput {
[[builtin(position)]] member: vec4<f32>;
};
-var<private> Vertex_Position1: vec3<f32>;
-var<private> Vertex_Normal1: vec3<f32>;
-var<private> Vertex_Uv1: vec2<f32>;
+var<private> Vertex_Position_1: vec3<f32>;
+var<private> Vertex_Normal_1: vec3<f32>;
+var<private> Vertex_Uv_1: vec2<f32>;
var<private> v_Position: vec3<f32>;
var<private> v_Normal: vec3<f32>;
var<private> v_Uv: vec2<f32>;
[[group(0), binding(0)]]
var<uniform> global: Camera;
[[group(2), binding(0)]]
-var<uniform> global1: Transform;
+var<uniform> global_1: Transform;
var<private> gl_Position: vec4<f32>;
-fn main1() {
- let e10: mat4x4<f32> = global1.Model;
- let e11: vec3<f32> = Vertex_Normal1;
+fn main_1() {
+ let e10: mat4x4<f32> = global_1.Model;
+ let e11: vec3<f32> = Vertex_Normal_1;
v_Normal = (e10 * vec4<f32>(e11, 1.0)).xyz;
- let e16: mat4x4<f32> = global1.Model;
- let e24: vec3<f32> = Vertex_Normal1;
+ let e16: mat4x4<f32> = global_1.Model;
+ let e24: vec3<f32> = Vertex_Normal_1;
v_Normal = (mat3x3<f32>(e16[0].xyz, e16[1].xyz, e16[2].xyz) * e24);
- let e26: mat4x4<f32> = global1.Model;
- let e27: vec3<f32> = Vertex_Position1;
+ let e26: mat4x4<f32> = global_1.Model;
+ let e27: vec3<f32> = Vertex_Position_1;
v_Position = (e26 * vec4<f32>(e27, 1.0)).xyz;
- let e32: vec2<f32> = Vertex_Uv1;
+ let e32: vec2<f32> = Vertex_Uv_1;
v_Uv = e32;
let e34: mat4x4<f32> = global.ViewProj;
let e35: vec3<f32> = v_Position;
diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl
--- a/tests/out/wgsl/210-bevy-shader-vert.wgsl
+++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl
@@ -47,10 +47,10 @@ fn main1() {
[[stage(vertex)]]
fn main([[location(0)]] Vertex_Position: vec3<f32>, [[location(1)]] Vertex_Normal: vec3<f32>, [[location(2)]] Vertex_Uv: vec2<f32>) -> VertexOutput {
- Vertex_Position1 = Vertex_Position;
- Vertex_Normal1 = Vertex_Normal;
- Vertex_Uv1 = Vertex_Uv;
- main1();
+ Vertex_Position_1 = Vertex_Position;
+ Vertex_Normal_1 = Vertex_Normal;
+ Vertex_Uv_1 = Vertex_Uv;
+ main_1();
let e23: vec3<f32> = v_Position;
let e25: vec3<f32> = v_Normal;
let e27: vec2<f32> = v_Uv;
diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl
--- a/tests/out/wgsl/246-collatz-comp.wgsl
+++ b/tests/out/wgsl/246-collatz-comp.wgsl
@@ -8,26 +8,26 @@ var<storage, read_write> global: PrimeIndices;
var<private> gl_GlobalInvocationID: vec3<u32>;
fn collatz_iterations(n: u32) -> u32 {
- var n1: u32;
+ var n_1: u32;
var i: u32 = 0u;
- n1 = n;
+ n_1 = n;
loop {
- let e7: u32 = n1;
+ let e7: u32 = n_1;
if (!((e7 != u32(1)))) {
break;
}
{
- let e14: u32 = n1;
+ let e14: u32 = n_1;
if (((f32(e14) % f32(2)) == f32(0))) {
{
- let e22: u32 = n1;
- n1 = (e22 / u32(2));
+ let e22: u32 = n_1;
+ n_1 = (e22 / u32(2));
}
} else {
{
- let e27: u32 = n1;
- n1 = ((u32(3) * e27) + u32(1));
+ let e27: u32 = n_1;
+ n_1 = ((u32(3) * e27) + u32(1));
}
}
let e33: u32 = i;
diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl
--- a/tests/out/wgsl/246-collatz-comp.wgsl
+++ b/tests/out/wgsl/246-collatz-comp.wgsl
@@ -38,7 +38,7 @@ fn collatz_iterations(n: u32) -> u32 {
return e36;
}
-fn main1() {
+fn main_1() {
var index: u32;
let e3: vec3<u32> = gl_GlobalInvocationID;
diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl
--- a/tests/out/wgsl/246-collatz-comp.wgsl
+++ b/tests/out/wgsl/246-collatz-comp.wgsl
@@ -55,6 +55,6 @@ fn main1() {
[[stage(compute), workgroup_size(1, 1, 1)]]
fn main([[builtin(global_invocation_id)]] param: vec3<u32>) {
gl_GlobalInvocationID = param;
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/277-casting-vert.wgsl b/tests/out/wgsl/277-casting-vert.wgsl
--- a/tests/out/wgsl/277-casting-vert.wgsl
+++ b/tests/out/wgsl/277-casting-vert.wgsl
@@ -1,10 +1,10 @@
-fn main1() {
+fn main_1() {
var a: f32 = 1.0;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl
--- a/tests/out/wgsl/280-matrix-cast-vert.wgsl
+++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var a: mat4x4<f32> = mat4x4<f32>(vec4<f32>(1.0, 0.0, 0.0, 0.0), vec4<f32>(0.0, 1.0, 0.0, 0.0), vec4<f32>(0.0, 0.0, 1.0, 0.0), vec4<f32>(0.0, 0.0, 0.0, 1.0));
let e1: f32 = f32(1);
diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl
--- a/tests/out/wgsl/280-matrix-cast-vert.wgsl
+++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl
@@ -6,6 +6,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/484-preprocessor-if-vert.wgsl b/tests/out/wgsl/484-preprocessor-if-vert.wgsl
--- a/tests/out/wgsl/484-preprocessor-if-vert.wgsl
+++ b/tests/out/wgsl/484-preprocessor-if-vert.wgsl
@@ -1,9 +1,9 @@
-fn main1() {
+fn main_1() {
return;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
--- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
+++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
@@ -15,18 +15,18 @@ struct VertexOutput {
[[group(0), binding(0)]]
var<uniform> global: Globals;
-var<push_constant> global1: VertexPushConstants;
-var<private> position1: vec2<f32>;
-var<private> color1: vec4<f32>;
+var<push_constant> global_1: VertexPushConstants;
+var<private> position_1: vec2<f32>;
+var<private> color_1: vec4<f32>;
var<private> frag_color: vec4<f32>;
var<private> gl_Position: vec4<f32>;
-fn main1() {
- let e7: vec4<f32> = color1;
+fn main_1() {
+ let e7: vec4<f32> = color_1;
frag_color = e7;
let e9: mat4x4<f32> = global.view_matrix;
- let e10: mat4x4<f32> = global1.world_matrix;
- let e12: vec2<f32> = position1;
+ let e10: mat4x4<f32> = global_1.world_matrix;
+ let e12: vec2<f32> = position_1;
gl_Position = ((e9 * e10) * vec4<f32>(e12, 0.0, 1.0));
let e18: vec4<f32> = gl_Position;
let e20: vec4<f32> = gl_Position;
diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
--- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
+++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
@@ -36,9 +36,9 @@ fn main1() {
[[stage(vertex)]]
fn main([[location(0)]] position: vec2<f32>, [[location(1)]] color: vec4<f32>) -> VertexOutput {
- position1 = position;
- color1 = color;
- main1();
+ position_1 = position;
+ color_1 = color;
+ main_1();
let e15: vec4<f32> = frag_color;
let e17: vec4<f32> = gl_Position;
return VertexOutput(e15, e17);
diff --git a/tests/out/wgsl/896-push-constant-vert.wgsl b/tests/out/wgsl/896-push-constant-vert.wgsl
--- a/tests/out/wgsl/896-push-constant-vert.wgsl
+++ b/tests/out/wgsl/896-push-constant-vert.wgsl
@@ -5,12 +5,12 @@ struct PushConstants {
var<push_constant> c: PushConstants;
-fn main1() {
+fn main_1() {
return;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/900-implicit-conversions-vert.wgsl b/tests/out/wgsl/900-implicit-conversions-vert.wgsl
--- a/tests/out/wgsl/900-implicit-conversions-vert.wgsl
+++ b/tests/out/wgsl/900-implicit-conversions-vert.wgsl
@@ -1,68 +1,68 @@
fn exact(a: f32) {
- var a1: f32;
+ var a_1: f32;
- a1 = a;
+ a_1 = a;
return;
}
-fn exact1(a2: i32) {
- var a3: i32;
+fn exact_1(a_2: i32) {
+ var a_3: i32;
- a3 = a2;
+ a_3 = a_2;
return;
}
-fn implicit(a4: f32) {
- var a5: f32;
+fn implicit(a_4: f32) {
+ var a_5: f32;
- a5 = a4;
+ a_5 = a_4;
return;
}
-fn implicit1(a6: i32) {
- var a7: i32;
+fn implicit_1(a_6: i32) {
+ var a_7: i32;
- a7 = a6;
+ a_7 = a_6;
return;
}
fn implicit_dims(v: f32) {
- var v1: f32;
+ var v_1: f32;
- v1 = v;
+ v_1 = v;
return;
}
-fn implicit_dims1(v2: vec2<f32>) {
- var v3: vec2<f32>;
+fn implicit_dims_1(v_2: vec2<f32>) {
+ var v_3: vec2<f32>;
- v3 = v2;
+ v_3 = v_2;
return;
}
-fn implicit_dims2(v4: vec3<f32>) {
- var v5: vec3<f32>;
+fn implicit_dims_2(v_4: vec3<f32>) {
+ var v_5: vec3<f32>;
- v5 = v4;
+ v_5 = v_4;
return;
}
-fn implicit_dims3(v6: vec4<f32>) {
- var v7: vec4<f32>;
+fn implicit_dims_3(v_6: vec4<f32>) {
+ var v_7: vec4<f32>;
- v7 = v6;
+ v_7 = v_6;
return;
}
-fn main1() {
- exact1(1);
+fn main_1() {
+ exact_1(1);
implicit(f32(1u));
- implicit_dims2(vec3<f32>(vec3<i32>(1)));
+ implicit_dims_2(vec3<f32>(vec3<i32>(1)));
return;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/901-lhs-field-select-vert.wgsl b/tests/out/wgsl/901-lhs-field-select-vert.wgsl
--- a/tests/out/wgsl/901-lhs-field-select-vert.wgsl
+++ b/tests/out/wgsl/901-lhs-field-select-vert.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var a: vec4<f32> = vec4<f32>(1.0, 1.0, 1.0, 1.0);
a.x = 2.0;
diff --git a/tests/out/wgsl/901-lhs-field-select-vert.wgsl b/tests/out/wgsl/901-lhs-field-select-vert.wgsl
--- a/tests/out/wgsl/901-lhs-field-select-vert.wgsl
+++ b/tests/out/wgsl/901-lhs-field-select-vert.wgsl
@@ -7,6 +7,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-vert.wgsl
--- a/tests/out/wgsl/931-constant-emitting-vert.wgsl
+++ b/tests/out/wgsl/931-constant-emitting-vert.wgsl
@@ -1,13 +1,13 @@
-fn function1() -> f32 {
+fn function_() -> f32 {
return 0.0;
}
-fn main1() {
+fn main_1() {
return;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl
--- a/tests/out/wgsl/932-for-loop-if-vert.wgsl
+++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var i: i32 = 0;
loop {
diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl
--- a/tests/out/wgsl/932-for-loop-if-vert.wgsl
+++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl
@@ -18,6 +18,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl
--- a/tests/out/wgsl/access.wgsl
+++ b/tests/out/wgsl/access.wgsl
@@ -3,33 +3,34 @@ struct Bar {
matrix: mat4x4<f32>;
atom: atomic<i32>;
arr: [[stride(8)]] array<vec2<u32>,2>;
- data: [[stride(4)]] array<i32>;
+ data: [[stride(8)]] array<i32>;
};
[[group(0), binding(0)]]
var<storage, read_write> bar: Bar;
-fn read_from_private(foo2: ptr<function, f32>) -> f32 {
- let e2: f32 = (*foo2);
+fn read_from_private(foo_2: ptr<function, f32>) -> f32 {
+ let e2: f32 = (*foo_2);
return e2;
}
[[stage(vertex)]]
fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4<f32> {
- var foo1: f32 = 0.0;
+ var foo_1: f32 = 0.0;
var c: array<i32,5>;
- let baz: f32 = foo1;
- foo1 = 1.0;
+ let baz: f32 = foo_1;
+ foo_1 = 1.0;
let matrix: mat4x4<f32> = bar.matrix;
let arr: array<vec2<u32>,2> = bar.arr;
let b: f32 = bar.matrix[3][0];
let a: i32 = bar.data[(arrayLength((&bar.data)) - 2u)];
- let pointer1: ptr<storage, i32, read_write> = (&bar.data[0]);
- let e25: f32 = read_from_private((&foo1));
+ let pointer_: ptr<storage, i32, read_write> = (&bar.data[0]);
+ let e25: f32 = read_from_private((&foo_1));
bar.matrix[1][2] = 1.0;
bar.matrix = mat4x4<f32>(vec4<f32>(0.0), vec4<f32>(1.0), vec4<f32>(2.0), vec4<f32>(3.0));
bar.arr = array<vec2<u32>,2>(vec2<u32>(0u), vec2<u32>(1u));
+ bar.data[1] = 1;
c = array<i32,5>(a, i32(b), 3, 4, 5);
c[(vi + 1u)] = 42;
let value: i32 = c[vi];
diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl
--- a/tests/out/wgsl/access.wgsl
+++ b/tests/out/wgsl/access.wgsl
@@ -40,7 +41,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4<f32> {
fn atomics() {
var tmp: i32;
- let value1: i32 = atomicLoad((&bar.atom));
+ let value_1: i32 = atomicLoad((&bar.atom));
let e6: i32 = atomicAdd((&bar.atom), 5);
tmp = e6;
let e9: i32 = atomicSub((&bar.atom), 5);
diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl
--- a/tests/out/wgsl/access.wgsl
+++ b/tests/out/wgsl/access.wgsl
@@ -57,6 +58,6 @@ fn atomics() {
tmp = e24;
let e27: i32 = atomicExchange((&bar.atom), 5);
tmp = e27;
- atomicStore((&bar.atom), value1);
+ atomicStore((&bar.atom), value_1);
return;
}
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -56,33 +56,33 @@ struct FragmentOutput {
[[location(0)]] o_Target: vec4<f32>;
};
-var<private> v_WorldPosition1: vec3<f32>;
-var<private> v_WorldNormal1: vec3<f32>;
-var<private> v_Uv1: vec2<f32>;
-var<private> v_WorldTangent1: vec4<f32>;
+var<private> v_WorldPosition_1: vec3<f32>;
+var<private> v_WorldNormal_1: vec3<f32>;
+var<private> v_Uv_1: vec2<f32>;
+var<private> v_WorldTangent_1: vec4<f32>;
var<private> o_Target: vec4<f32>;
[[group(0), binding(0)]]
var<uniform> global: CameraViewProj;
[[group(0), binding(1)]]
-var<uniform> global1: CameraPosition;
+var<uniform> global_1: CameraPosition;
[[group(1), binding(0)]]
-var<uniform> global2: Lights;
+var<uniform> global_2: Lights;
[[group(3), binding(0)]]
-var<uniform> global3: StandardMaterial_base_color;
+var<uniform> global_3: StandardMaterial_base_color;
[[group(3), binding(1)]]
var StandardMaterial_base_color_texture: texture_2d<f32>;
[[group(3), binding(2)]]
var StandardMaterial_base_color_texture_sampler: sampler;
[[group(3), binding(3)]]
-var<uniform> global4: StandardMaterial_roughness;
+var<uniform> global_4: StandardMaterial_roughness;
[[group(3), binding(4)]]
-var<uniform> global5: StandardMaterial_metallic;
+var<uniform> global_5: StandardMaterial_metallic;
[[group(3), binding(5)]]
var StandardMaterial_metallic_roughness_texture: texture_2d<f32>;
[[group(3), binding(6)]]
var StandardMaterial_metallic_roughness_texture_sampler: sampler;
[[group(3), binding(7)]]
-var<uniform> global6: StandardMaterial_reflectance;
+var<uniform> global_6: StandardMaterial_reflectance;
[[group(3), binding(8)]]
var StandardMaterial_normal_map: texture_2d<f32>;
[[group(3), binding(9)]]
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -92,7 +92,7 @@ var StandardMaterial_occlusion_texture: texture_2d<f32>;
[[group(3), binding(11)]]
var StandardMaterial_occlusion_texture_sampler: sampler;
[[group(3), binding(12)]]
-var<uniform> global7: StandardMaterial_emissive;
+var<uniform> global_7: StandardMaterial_emissive;
[[group(3), binding(13)]]
var StandardMaterial_emissive_texture: texture_2d<f32>;
[[group(3), binding(14)]]
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -100,30 +100,30 @@ var StandardMaterial_emissive_texture_sampler: sampler;
var<private> gl_FrontFacing: bool;
fn pow5_(x: f32) -> f32 {
- var x1: f32;
+ var x_1: f32;
var x2_: f32;
- x1 = x;
- let e42: f32 = x1;
- let e43: f32 = x1;
+ x_1 = x;
+ let e42: f32 = x_1;
+ let e43: f32 = x_1;
x2_ = (e42 * e43);
let e46: f32 = x2_;
let e47: f32 = x2_;
- let e49: f32 = x1;
+ let e49: f32 = x_1;
return ((e46 * e47) * e49);
}
fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 {
- var distanceSquare1: f32;
- var inverseRangeSquared1: f32;
+ var distanceSquare_1: f32;
+ var inverseRangeSquared_1: f32;
var factor: f32;
var smoothFactor: f32;
var attenuation: f32;
- distanceSquare1 = distanceSquare;
- inverseRangeSquared1 = inverseRangeSquared;
- let e44: f32 = distanceSquare1;
- let e45: f32 = inverseRangeSquared1;
+ distanceSquare_1 = distanceSquare;
+ inverseRangeSquared_1 = inverseRangeSquared;
+ let e44: f32 = distanceSquare_1;
+ let e45: f32 = inverseRangeSquared_1;
factor = (e44 * e45);
let e49: f32 = factor;
let e50: f32 = factor;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -134,27 +134,27 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32
let e65: f32 = smoothFactor;
attenuation = (e64 * e65);
let e68: f32 = attenuation;
- let e73: f32 = distanceSquare1;
- return ((e68 * 1.0) / max(e73, 0.00009999999747378752));
+ let e73: f32 = distanceSquare_1;
+ return ((e68 * 1.0) / max(e73, 0.0010000000474974513));
}
fn D_GGX(roughness: f32, NoH: f32, h: vec3<f32>) -> f32 {
- var roughness1: f32;
- var NoH1: f32;
+ var roughness_1: f32;
+ var NoH_1: f32;
var oneMinusNoHSquared: f32;
var a: f32;
var k: f32;
var d: f32;
- roughness1 = roughness;
- NoH1 = NoH;
- let e46: f32 = NoH1;
- let e47: f32 = NoH1;
+ roughness_1 = roughness;
+ NoH_1 = NoH;
+ let e46: f32 = NoH_1;
+ let e47: f32 = NoH_1;
oneMinusNoHSquared = (1.0 - (e46 * e47));
- let e51: f32 = NoH1;
- let e52: f32 = roughness1;
+ let e51: f32 = NoH_1;
+ let e52: f32 = roughness_1;
a = (e51 * e52);
- let e55: f32 = roughness1;
+ let e55: f32 = roughness_1;
let e56: f32 = oneMinusNoHSquared;
let e57: f32 = a;
let e58: f32 = a;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -166,43 +166,43 @@ fn D_GGX(roughness: f32, NoH: f32, h: vec3<f32>) -> f32 {
return e70;
}
-fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 {
- var roughness3: f32;
- var NoV1: f32;
- var NoL1: f32;
+fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 {
+ var roughness_3: f32;
+ var NoV_1: f32;
+ var NoL_1: f32;
var a2_: f32;
var lambdaV: f32;
var lambdaL: f32;
var v: f32;
- roughness3 = roughness2;
- NoV1 = NoV;
- NoL1 = NoL;
- let e46: f32 = roughness3;
- let e47: f32 = roughness3;
+ roughness_3 = roughness_2;
+ NoV_1 = NoV;
+ NoL_1 = NoL;
+ let e46: f32 = roughness_3;
+ let e47: f32 = roughness_3;
a2_ = (e46 * e47);
- let e50: f32 = NoL1;
- let e51: f32 = NoV1;
+ let e50: f32 = NoL_1;
+ let e51: f32 = NoV_1;
let e52: f32 = a2_;
- let e53: f32 = NoV1;
- let e56: f32 = NoV1;
+ let e53: f32 = NoV_1;
+ let e56: f32 = NoV_1;
let e58: f32 = a2_;
- let e60: f32 = NoV1;
+ let e60: f32 = NoV_1;
let e61: f32 = a2_;
- let e62: f32 = NoV1;
- let e65: f32 = NoV1;
+ let e62: f32 = NoV_1;
+ let e65: f32 = NoV_1;
let e67: f32 = a2_;
lambdaV = (e50 * sqrt((((e60 - (e61 * e62)) * e65) + e67)));
- let e72: f32 = NoV1;
- let e73: f32 = NoL1;
+ let e72: f32 = NoV_1;
+ let e73: f32 = NoL_1;
let e74: f32 = a2_;
- let e75: f32 = NoL1;
- let e78: f32 = NoL1;
+ let e75: f32 = NoL_1;
+ let e78: f32 = NoL_1;
let e80: f32 = a2_;
- let e82: f32 = NoL1;
+ let e82: f32 = NoL_1;
let e83: f32 = a2_;
- let e84: f32 = NoL1;
- let e87: f32 = NoL1;
+ let e84: f32 = NoL_1;
+ let e87: f32 = NoL_1;
let e89: f32 = a2_;
lambdaL = (e72 * sqrt((((e82 - (e83 * e84)) * e87) + e89)));
let e95: f32 = lambdaV;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -214,124 +214,124 @@ fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 {
fn F_Schlick(f0_: vec3<f32>, f90_: f32, VoH: f32) -> vec3<f32> {
var f90_1: f32;
- var VoH1: f32;
+ var VoH_1: f32;
f90_1 = f90_;
- VoH1 = VoH;
+ VoH_1 = VoH;
let e45: f32 = f90_1;
- let e49: f32 = VoH1;
- let e52: f32 = VoH1;
+ let e49: f32 = VoH_1;
+ let e52: f32 = VoH_1;
let e54: f32 = pow5_((1.0 - e52));
return (f0_ + ((vec3<f32>(e45) - f0_) * e54));
}
-fn F_Schlick1(f0_1: f32, f90_2: f32, VoH2: f32) -> f32 {
+fn F_Schlick_1(f0_1: f32, f90_2: f32, VoH_2: f32) -> f32 {
var f0_2: f32;
var f90_3: f32;
- var VoH3: f32;
+ var VoH_3: f32;
f0_2 = f0_1;
f90_3 = f90_2;
- VoH3 = VoH2;
+ VoH_3 = VoH_2;
let e46: f32 = f0_2;
let e47: f32 = f90_3;
let e48: f32 = f0_2;
- let e51: f32 = VoH3;
- let e54: f32 = VoH3;
+ let e51: f32 = VoH_3;
+ let e54: f32 = VoH_3;
let e56: f32 = pow5_((1.0 - e54));
return (e46 + ((e47 - e48) * e56));
}
fn fresnel(f0_3: vec3<f32>, LoH: f32) -> vec3<f32> {
var f0_4: vec3<f32>;
- var LoH1: f32;
+ var LoH_1: f32;
var f90_4: f32;
f0_4 = f0_3;
- LoH1 = LoH;
+ LoH_1 = LoH;
let e49: vec3<f32> = f0_4;
let e62: vec3<f32> = f0_4;
f90_4 = clamp(dot(e62, vec3<f32>((50.0 * 0.33000001311302185))), 0.0, 1.0);
let e75: vec3<f32> = f0_4;
let e76: f32 = f90_4;
- let e77: f32 = LoH1;
+ let e77: f32 = LoH_1;
let e78: vec3<f32> = F_Schlick(e75, e76, e77);
return e78;
}
-fn specular(f0_5: vec3<f32>, roughness4: f32, h1: vec3<f32>, NoV2: f32, NoL2: f32, NoH2: f32, LoH2: f32, specularIntensity: f32) -> vec3<f32> {
+fn specular(f0_5: vec3<f32>, roughness_4: f32, h_1: vec3<f32>, NoV_2: f32, NoL_2: f32, NoH_2: f32, LoH_2: f32, specularIntensity: f32) -> vec3<f32> {
var f0_6: vec3<f32>;
- var roughness5: f32;
- var NoV3: f32;
- var NoL3: f32;
- var NoH3: f32;
- var LoH3: f32;
- var specularIntensity1: f32;
+ var roughness_5: f32;
+ var NoV_3: f32;
+ var NoL_3: f32;
+ var NoH_3: f32;
+ var LoH_3: f32;
+ var specularIntensity_1: f32;
var D: f32;
var V: f32;
var F: vec3<f32>;
f0_6 = f0_5;
- roughness5 = roughness4;
- NoV3 = NoV2;
- NoL3 = NoL2;
- NoH3 = NoH2;
- LoH3 = LoH2;
- specularIntensity1 = specularIntensity;
- let e57: f32 = roughness5;
- let e58: f32 = NoH3;
- let e59: f32 = D_GGX(e57, e58, h1);
+ roughness_5 = roughness_4;
+ NoV_3 = NoV_2;
+ NoL_3 = NoL_2;
+ NoH_3 = NoH_2;
+ LoH_3 = LoH_2;
+ specularIntensity_1 = specularIntensity;
+ let e57: f32 = roughness_5;
+ let e58: f32 = NoH_3;
+ let e59: f32 = D_GGX(e57, e58, h_1);
D = e59;
- let e64: f32 = roughness5;
- let e65: f32 = NoV3;
- let e66: f32 = NoL3;
+ let e64: f32 = roughness_5;
+ let e65: f32 = NoV_3;
+ let e66: f32 = NoL_3;
let e67: f32 = V_SmithGGXCorrelated(e64, e65, e66);
V = e67;
let e71: vec3<f32> = f0_6;
- let e72: f32 = LoH3;
+ let e72: f32 = LoH_3;
let e73: vec3<f32> = fresnel(e71, e72);
F = e73;
- let e75: f32 = specularIntensity1;
+ let e75: f32 = specularIntensity_1;
let e76: f32 = D;
let e78: f32 = V;
let e80: vec3<f32> = F;
return (((e75 * e76) * e78) * e80);
}
-fn Fd_Burley(roughness6: f32, NoV4: f32, NoL4: f32, LoH4: f32) -> f32 {
- var roughness7: f32;
- var NoV5: f32;
- var NoL5: f32;
- var LoH5: f32;
+fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 {
+ var roughness_7: f32;
+ var NoV_5: f32;
+ var NoL_5: f32;
+ var LoH_5: f32;
var f90_5: f32;
var lightScatter: f32;
var viewScatter: f32;
- roughness7 = roughness6;
- NoV5 = NoV4;
- NoL5 = NoL4;
- LoH5 = LoH4;
- let e50: f32 = roughness7;
- let e52: f32 = LoH5;
- let e54: f32 = LoH5;
+ roughness_7 = roughness_6;
+ NoV_5 = NoV_4;
+ NoL_5 = NoL_4;
+ LoH_5 = LoH_4;
+ let e50: f32 = roughness_7;
+ let e52: f32 = LoH_5;
+ let e54: f32 = LoH_5;
f90_5 = (0.5 + (((2.0 * e50) * e52) * e54));
let e62: f32 = f90_5;
- let e63: f32 = NoL5;
- let e64: f32 = F_Schlick1(1.0, e62, e63);
+ let e63: f32 = NoL_5;
+ let e64: f32 = F_Schlick_1(1.0, e62, e63);
lightScatter = e64;
let e70: f32 = f90_5;
- let e71: f32 = NoV5;
- let e72: f32 = F_Schlick1(1.0, e70, e71);
+ let e71: f32 = NoV_5;
+ let e72: f32 = F_Schlick_1(1.0, e70, e71);
viewScatter = e72;
let e74: f32 = lightScatter;
let e75: f32 = viewScatter;
return ((e74 * e75) * (1.0 / 3.1415927410125732));
}
-fn EnvBRDFApprox(f0_7: vec3<f32>, perceptual_roughness: f32, NoV6: f32) -> vec3<f32> {
+fn EnvBRDFApprox(f0_7: vec3<f32>, perceptual_roughness: f32, NoV_6: f32) -> vec3<f32> {
var f0_8: vec3<f32>;
- var perceptual_roughness1: f32;
- var NoV7: f32;
+ var perceptual_roughness_1: f32;
+ var NoV_7: f32;
var c0_: vec4<f32> = vec4<f32>(-1.0, -0.027499999850988388, -0.5720000267028809, 0.02199999988079071);
var c1_: vec4<f32> = vec4<f32>(1.0, 0.042500000447034836, 1.0399999618530273, -0.03999999910593033);
var r: vec4<f32>;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -339,20 +339,20 @@ fn EnvBRDFApprox(f0_7: vec3<f32>, perceptual_roughness: f32, NoV6: f32) -> vec3<
var AB: vec2<f32>;
f0_8 = f0_7;
- perceptual_roughness1 = perceptual_roughness;
- NoV7 = NoV6;
- let e62: f32 = perceptual_roughness1;
+ perceptual_roughness_1 = perceptual_roughness;
+ NoV_7 = NoV_6;
+ let e62: f32 = perceptual_roughness_1;
let e64: vec4<f32> = c0_;
let e66: vec4<f32> = c1_;
r = ((vec4<f32>(e62) * e64) + e66);
let e69: vec4<f32> = r;
let e71: vec4<f32> = r;
- let e76: f32 = NoV7;
- let e80: f32 = NoV7;
+ let e76: f32 = NoV_7;
+ let e80: f32 = NoV_7;
let e83: vec4<f32> = r;
let e85: vec4<f32> = r;
- let e90: f32 = NoV7;
- let e94: f32 = NoV7;
+ let e90: f32 = NoV_7;
+ let e94: f32 = NoV_7;
let e98: vec4<f32> = r;
let e101: vec4<f32> = r;
a004_ = ((min((e83.x * e85.x), exp2((-(9.279999732971191) * e94))) * e98.x) + e101.y);
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -366,11 +366,11 @@ fn EnvBRDFApprox(f0_7: vec3<f32>, perceptual_roughness: f32, NoV6: f32) -> vec3<
}
fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 {
- var perceptualRoughness1: f32;
+ var perceptualRoughness_1: f32;
var clampedPerceptualRoughness: f32;
- perceptualRoughness1 = perceptualRoughness;
- let e45: f32 = perceptualRoughness1;
+ perceptualRoughness_1 = perceptualRoughness;
+ let e45: f32 = perceptualRoughness_1;
clampedPerceptualRoughness = clamp(e45, 0.08900000154972076, 1.0);
let e50: f32 = clampedPerceptualRoughness;
let e51: f32 = clampedPerceptualRoughness;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -378,152 +378,152 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 {
}
fn reinhard(color: vec3<f32>) -> vec3<f32> {
- var color1: vec3<f32>;
+ var color_1: vec3<f32>;
- color1 = color;
- let e42: vec3<f32> = color1;
- let e45: vec3<f32> = color1;
+ color_1 = color;
+ let e42: vec3<f32> = color_1;
+ let e45: vec3<f32> = color_1;
return (e42 / (vec3<f32>(1.0) + e45));
}
-fn reinhard_extended(color2: vec3<f32>, max_white: f32) -> vec3<f32> {
- var color3: vec3<f32>;
- var max_white1: f32;
+fn reinhard_extended(color_2: vec3<f32>, max_white: f32) -> vec3<f32> {
+ var color_3: vec3<f32>;
+ var max_white_1: f32;
var numerator: vec3<f32>;
- color3 = color2;
- max_white1 = max_white;
- let e44: vec3<f32> = color3;
- let e47: vec3<f32> = color3;
- let e48: f32 = max_white1;
- let e49: f32 = max_white1;
+ color_3 = color_2;
+ max_white_1 = max_white;
+ let e44: vec3<f32> = color_3;
+ let e47: vec3<f32> = color_3;
+ let e48: f32 = max_white_1;
+ let e49: f32 = max_white_1;
numerator = (e44 * (vec3<f32>(1.0) + (e47 / vec3<f32>((e48 * e49)))));
let e56: vec3<f32> = numerator;
- let e59: vec3<f32> = color3;
+ let e59: vec3<f32> = color_3;
return (e56 / (vec3<f32>(1.0) + e59));
}
-fn luminance(v1: vec3<f32>) -> f32 {
- var v2: vec3<f32>;
+fn luminance(v_1: vec3<f32>) -> f32 {
+ var v_2: vec3<f32>;
- v2 = v1;
- let e47: vec3<f32> = v2;
+ v_2 = v_1;
+ let e47: vec3<f32> = v_2;
return dot(e47, vec3<f32>(0.2125999927520752, 0.7152000069618225, 0.0722000002861023));
}
fn change_luminance(c_in: vec3<f32>, l_out: f32) -> vec3<f32> {
- var c_in1: vec3<f32>;
- var l_out1: f32;
+ var c_in_1: vec3<f32>;
+ var l_out_1: f32;
var l_in: f32;
- c_in1 = c_in;
- l_out1 = l_out;
- let e45: vec3<f32> = c_in1;
+ c_in_1 = c_in;
+ l_out_1 = l_out;
+ let e45: vec3<f32> = c_in_1;
let e46: f32 = luminance(e45);
l_in = e46;
- let e48: vec3<f32> = c_in1;
- let e49: f32 = l_out1;
+ let e48: vec3<f32> = c_in_1;
+ let e49: f32 = l_out_1;
let e50: f32 = l_in;
return (e48 * (e49 / e50));
}
-fn reinhard_luminance(color4: vec3<f32>) -> vec3<f32> {
- var color5: vec3<f32>;
+fn reinhard_luminance(color_4: vec3<f32>) -> vec3<f32> {
+ var color_5: vec3<f32>;
var l_old: f32;
var l_new: f32;
- color5 = color4;
- let e43: vec3<f32> = color5;
+ color_5 = color_4;
+ let e43: vec3<f32> = color_5;
let e44: f32 = luminance(e43);
l_old = e44;
let e46: f32 = l_old;
let e48: f32 = l_old;
l_new = (e46 / (1.0 + e48));
- let e54: vec3<f32> = color5;
+ let e54: vec3<f32> = color_5;
let e55: f32 = l_new;
let e56: vec3<f32> = change_luminance(e54, e55);
return e56;
}
-fn reinhard_extended_luminance(color6: vec3<f32>, max_white_l: f32) -> vec3<f32> {
- var color7: vec3<f32>;
- var max_white_l1: f32;
- var l_old1: f32;
- var numerator1: f32;
- var l_new1: f32;
+fn reinhard_extended_luminance(color_6: vec3<f32>, max_white_l: f32) -> vec3<f32> {
+ var color_7: vec3<f32>;
+ var max_white_l_1: f32;
+ var l_old_1: f32;
+ var numerator_1: f32;
+ var l_new_1: f32;
- color7 = color6;
- max_white_l1 = max_white_l;
- let e45: vec3<f32> = color7;
+ color_7 = color_6;
+ max_white_l_1 = max_white_l;
+ let e45: vec3<f32> = color_7;
let e46: f32 = luminance(e45);
- l_old1 = e46;
- let e48: f32 = l_old1;
- let e50: f32 = l_old1;
- let e51: f32 = max_white_l1;
- let e52: f32 = max_white_l1;
- numerator1 = (e48 * (1.0 + (e50 / (e51 * e52))));
- let e58: f32 = numerator1;
- let e60: f32 = l_old1;
- l_new1 = (e58 / (1.0 + e60));
- let e66: vec3<f32> = color7;
- let e67: f32 = l_new1;
+ l_old_1 = e46;
+ let e48: f32 = l_old_1;
+ let e50: f32 = l_old_1;
+ let e51: f32 = max_white_l_1;
+ let e52: f32 = max_white_l_1;
+ numerator_1 = (e48 * (1.0 + (e50 / (e51 * e52))));
+ let e58: f32 = numerator_1;
+ let e60: f32 = l_old_1;
+ l_new_1 = (e58 / (1.0 + e60));
+ let e66: vec3<f32> = color_7;
+ let e67: f32 = l_new_1;
let e68: vec3<f32> = change_luminance(e66, e67);
return e68;
}
-fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3<f32>, V1: vec3<f32>, R: vec3<f32>, F0_: vec3<f32>, diffuseColor: vec3<f32>) -> vec3<f32> {
- var light1: PointLight;
- var roughness9: f32;
- var NdotV1: f32;
- var N1: vec3<f32>;
- var V2: vec3<f32>;
- var R1: vec3<f32>;
+fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3<f32>, V_1: vec3<f32>, R: vec3<f32>, F0_: vec3<f32>, diffuseColor: vec3<f32>) -> vec3<f32> {
+ var light_1: PointLight;
+ var roughness_9: f32;
+ var NdotV_1: f32;
+ var N_1: vec3<f32>;
+ var V_2: vec3<f32>;
+ var R_1: vec3<f32>;
var F0_1: vec3<f32>;
- var diffuseColor1: vec3<f32>;
+ var diffuseColor_1: vec3<f32>;
var light_to_frag: vec3<f32>;
var distance_square: f32;
var rangeAttenuation: f32;
- var a1: f32;
+ var a_1: f32;
var radius: f32;
var centerToRay: vec3<f32>;
var closestPoint: vec3<f32>;
var LspecLengthInverse: f32;
var normalizationFactor: f32;
- var specularIntensity2: f32;
+ var specularIntensity_2: f32;
var L: vec3<f32>;
var H: vec3<f32>;
- var NoL6: f32;
- var NoH4: f32;
- var LoH6: f32;
- var specular1: vec3<f32>;
+ var NoL_6: f32;
+ var NoH_4: f32;
+ var LoH_6: f32;
+ var specular_1: vec3<f32>;
var diffuse: vec3<f32>;
- light1 = light;
- roughness9 = roughness8;
- NdotV1 = NdotV;
- N1 = N;
- V2 = V1;
- R1 = R;
+ light_1 = light;
+ roughness_9 = roughness_8;
+ NdotV_1 = NdotV;
+ N_1 = N;
+ V_2 = V_1;
+ R_1 = R;
F0_1 = F0_;
- diffuseColor1 = diffuseColor;
- let e56: PointLight = light1;
- let e59: vec3<f32> = v_WorldPosition1;
+ diffuseColor_1 = diffuseColor;
+ let e56: PointLight = light_1;
+ let e59: vec3<f32> = v_WorldPosition_1;
light_to_frag = (e56.pos.xyz - e59.xyz);
let e65: vec3<f32> = light_to_frag;
let e66: vec3<f32> = light_to_frag;
distance_square = dot(e65, e66);
- let e70: PointLight = light1;
+ let e70: PointLight = light_1;
let e73: f32 = distance_square;
- let e74: PointLight = light1;
+ let e74: PointLight = light_1;
let e77: f32 = getDistanceAttenuation(e73, e74.lightParams.x);
rangeAttenuation = e77;
- let e79: f32 = roughness9;
- a1 = e79;
- let e81: PointLight = light1;
+ let e79: f32 = roughness_9;
+ a_1 = e79;
+ let e81: PointLight = light_1;
radius = e81.lightParams.y;
let e87: vec3<f32> = light_to_frag;
- let e88: vec3<f32> = R1;
- let e90: vec3<f32> = R1;
+ let e88: vec3<f32> = R_1;
+ let e90: vec3<f32> = R_1;
let e92: vec3<f32> = light_to_frag;
centerToRay = ((dot(e87, e88) * e90) - e92);
let e95: vec3<f32> = light_to_frag;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -544,213 +544,213 @@ fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3<f32>, V1:
let e138: vec3<f32> = closestPoint;
let e139: vec3<f32> = closestPoint;
LspecLengthInverse = inverseSqrt(dot(e138, e139));
- let e143: f32 = a1;
- let e144: f32 = a1;
+ let e143: f32 = a_1;
+ let e144: f32 = a_1;
let e145: f32 = radius;
let e148: f32 = LspecLengthInverse;
- let e153: f32 = a1;
+ let e153: f32 = a_1;
let e154: f32 = radius;
let e157: f32 = LspecLengthInverse;
normalizationFactor = (e143 / clamp((e153 + ((e154 * 0.5) * e157)), 0.0, 1.0));
let e165: f32 = normalizationFactor;
let e166: f32 = normalizationFactor;
- specularIntensity2 = (e165 * e166);
+ specularIntensity_2 = (e165 * e166);
let e169: vec3<f32> = closestPoint;
let e170: f32 = LspecLengthInverse;
L = (e169 * e170);
let e173: vec3<f32> = L;
- let e174: vec3<f32> = V2;
+ let e174: vec3<f32> = V_2;
let e176: vec3<f32> = L;
- let e177: vec3<f32> = V2;
+ let e177: vec3<f32> = V_2;
H = normalize((e176 + e177));
- let e183: vec3<f32> = N1;
+ let e183: vec3<f32> = N_1;
let e184: vec3<f32> = L;
- let e190: vec3<f32> = N1;
+ let e190: vec3<f32> = N_1;
let e191: vec3<f32> = L;
- NoL6 = clamp(dot(e190, e191), 0.0, 1.0);
- let e199: vec3<f32> = N1;
+ NoL_6 = clamp(dot(e190, e191), 0.0, 1.0);
+ let e199: vec3<f32> = N_1;
let e200: vec3<f32> = H;
- let e206: vec3<f32> = N1;
+ let e206: vec3<f32> = N_1;
let e207: vec3<f32> = H;
- NoH4 = clamp(dot(e206, e207), 0.0, 1.0);
+ NoH_4 = clamp(dot(e206, e207), 0.0, 1.0);
let e215: vec3<f32> = L;
let e216: vec3<f32> = H;
let e222: vec3<f32> = L;
let e223: vec3<f32> = H;
- LoH6 = clamp(dot(e222, e223), 0.0, 1.0);
+ LoH_6 = clamp(dot(e222, e223), 0.0, 1.0);
let e237: vec3<f32> = F0_1;
- let e238: f32 = roughness9;
+ let e238: f32 = roughness_9;
let e239: vec3<f32> = H;
- let e240: f32 = NdotV1;
- let e241: f32 = NoL6;
- let e242: f32 = NoH4;
- let e243: f32 = LoH6;
- let e244: f32 = specularIntensity2;
+ let e240: f32 = NdotV_1;
+ let e241: f32 = NoL_6;
+ let e242: f32 = NoH_4;
+ let e243: f32 = LoH_6;
+ let e244: f32 = specularIntensity_2;
let e245: vec3<f32> = specular(e237, e238, e239, e240, e241, e242, e243, e244);
- specular1 = e245;
+ specular_1 = e245;
let e248: vec3<f32> = light_to_frag;
L = normalize(e248);
let e250: vec3<f32> = L;
- let e251: vec3<f32> = V2;
+ let e251: vec3<f32> = V_2;
let e253: vec3<f32> = L;
- let e254: vec3<f32> = V2;
+ let e254: vec3<f32> = V_2;
H = normalize((e253 + e254));
- let e259: vec3<f32> = N1;
+ let e259: vec3<f32> = N_1;
let e260: vec3<f32> = L;
- let e266: vec3<f32> = N1;
+ let e266: vec3<f32> = N_1;
let e267: vec3<f32> = L;
- NoL6 = clamp(dot(e266, e267), 0.0, 1.0);
- let e274: vec3<f32> = N1;
+ NoL_6 = clamp(dot(e266, e267), 0.0, 1.0);
+ let e274: vec3<f32> = N_1;
let e275: vec3<f32> = H;
- let e281: vec3<f32> = N1;
+ let e281: vec3<f32> = N_1;
let e282: vec3<f32> = H;
- NoH4 = clamp(dot(e281, e282), 0.0, 1.0);
+ NoH_4 = clamp(dot(e281, e282), 0.0, 1.0);
let e289: vec3<f32> = L;
let e290: vec3<f32> = H;
let e296: vec3<f32> = L;
let e297: vec3<f32> = H;
- LoH6 = clamp(dot(e296, e297), 0.0, 1.0);
- let e302: vec3<f32> = diffuseColor1;
- let e307: f32 = roughness9;
- let e308: f32 = NdotV1;
- let e309: f32 = NoL6;
- let e310: f32 = LoH6;
+ LoH_6 = clamp(dot(e296, e297), 0.0, 1.0);
+ let e302: vec3<f32> = diffuseColor_1;
+ let e307: f32 = roughness_9;
+ let e308: f32 = NdotV_1;
+ let e309: f32 = NoL_6;
+ let e310: f32 = LoH_6;
let e311: f32 = Fd_Burley(e307, e308, e309, e310);
diffuse = (e302 * e311);
let e314: vec3<f32> = diffuse;
- let e315: vec3<f32> = specular1;
- let e317: PointLight = light1;
+ let e315: vec3<f32> = specular_1;
+ let e317: PointLight = light_1;
let e321: f32 = rangeAttenuation;
- let e322: f32 = NoL6;
+ let e322: f32 = NoL_6;
return (((e314 + e315) * e317.color.xyz) * (e321 * e322));
}
-fn dir_light(light2: DirectionalLight, roughness10: f32, NdotV2: f32, normal: vec3<f32>, view: vec3<f32>, R2: vec3<f32>, F0_2: vec3<f32>, diffuseColor2: vec3<f32>) -> vec3<f32> {
- var light3: DirectionalLight;
- var roughness11: f32;
- var NdotV3: f32;
- var normal1: vec3<f32>;
- var view1: vec3<f32>;
- var R3: vec3<f32>;
+fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: vec3<f32>, view: vec3<f32>, R_2: vec3<f32>, F0_2: vec3<f32>, diffuseColor_2: vec3<f32>) -> vec3<f32> {
+ var light_3: DirectionalLight;
+ var roughness_11: f32;
+ var NdotV_3: f32;
+ var normal_1: vec3<f32>;
+ var view_1: vec3<f32>;
+ var R_3: vec3<f32>;
var F0_3: vec3<f32>;
- var diffuseColor3: vec3<f32>;
+ var diffuseColor_3: vec3<f32>;
var incident_light: vec3<f32>;
var half_vector: vec3<f32>;
- var NoL7: f32;
- var NoH5: f32;
- var LoH7: f32;
- var diffuse1: vec3<f32>;
- var specularIntensity3: f32 = 1.0;
- var specular2: vec3<f32>;
-
- light3 = light2;
- roughness11 = roughness10;
- NdotV3 = NdotV2;
- normal1 = normal;
- view1 = view;
- R3 = R2;
+ var NoL_7: f32;
+ var NoH_5: f32;
+ var LoH_7: f32;
+ var diffuse_1: vec3<f32>;
+ var specularIntensity_3: f32 = 1.0;
+ var specular_2: vec3<f32>;
+
+ light_3 = light_2;
+ roughness_11 = roughness_10;
+ NdotV_3 = NdotV_2;
+ normal_1 = normal;
+ view_1 = view;
+ R_3 = R_2;
F0_3 = F0_2;
- diffuseColor3 = diffuseColor2;
- let e56: DirectionalLight = light3;
+ diffuseColor_3 = diffuseColor_2;
+ let e56: DirectionalLight = light_3;
incident_light = e56.direction.xyz;
let e60: vec3<f32> = incident_light;
- let e61: vec3<f32> = view1;
+ let e61: vec3<f32> = view_1;
let e63: vec3<f32> = incident_light;
- let e64: vec3<f32> = view1;
+ let e64: vec3<f32> = view_1;
half_vector = normalize((e63 + e64));
- let e70: vec3<f32> = normal1;
+ let e70: vec3<f32> = normal_1;
let e71: vec3<f32> = incident_light;
- let e77: vec3<f32> = normal1;
+ let e77: vec3<f32> = normal_1;
let e78: vec3<f32> = incident_light;
- NoL7 = clamp(dot(e77, e78), 0.0, 1.0);
- let e86: vec3<f32> = normal1;
+ NoL_7 = clamp(dot(e77, e78), 0.0, 1.0);
+ let e86: vec3<f32> = normal_1;
let e87: vec3<f32> = half_vector;
- let e93: vec3<f32> = normal1;
+ let e93: vec3<f32> = normal_1;
let e94: vec3<f32> = half_vector;
- NoH5 = clamp(dot(e93, e94), 0.0, 1.0);
+ NoH_5 = clamp(dot(e93, e94), 0.0, 1.0);
let e102: vec3<f32> = incident_light;
let e103: vec3<f32> = half_vector;
let e109: vec3<f32> = incident_light;
let e110: vec3<f32> = half_vector;
- LoH7 = clamp(dot(e109, e110), 0.0, 1.0);
- let e116: vec3<f32> = diffuseColor3;
- let e121: f32 = roughness11;
- let e122: f32 = NdotV3;
- let e123: f32 = NoL7;
- let e124: f32 = LoH7;
+ LoH_7 = clamp(dot(e109, e110), 0.0, 1.0);
+ let e116: vec3<f32> = diffuseColor_3;
+ let e121: f32 = roughness_11;
+ let e122: f32 = NdotV_3;
+ let e123: f32 = NoL_7;
+ let e124: f32 = LoH_7;
let e125: f32 = Fd_Burley(e121, e122, e123, e124);
- diffuse1 = (e116 * e125);
+ diffuse_1 = (e116 * e125);
let e138: vec3<f32> = F0_3;
- let e139: f32 = roughness11;
+ let e139: f32 = roughness_11;
let e140: vec3<f32> = half_vector;
- let e141: f32 = NdotV3;
- let e142: f32 = NoL7;
- let e143: f32 = NoH5;
- let e144: f32 = LoH7;
- let e145: f32 = specularIntensity3;
+ let e141: f32 = NdotV_3;
+ let e142: f32 = NoL_7;
+ let e143: f32 = NoH_5;
+ let e144: f32 = LoH_7;
+ let e145: f32 = specularIntensity_3;
let e146: vec3<f32> = specular(e138, e139, e140, e141, e142, e143, e144, e145);
- specular2 = e146;
- let e148: vec3<f32> = specular2;
- let e149: vec3<f32> = diffuse1;
- let e151: DirectionalLight = light3;
- let e155: f32 = NoL7;
+ specular_2 = e146;
+ let e148: vec3<f32> = specular_2;
+ let e149: vec3<f32> = diffuse_1;
+ let e151: DirectionalLight = light_3;
+ let e155: f32 = NoL_7;
return (((e148 + e149) * e151.color.xyz) * e155);
}
-fn main1() {
+fn main_1() {
var output_color: vec4<f32>;
var metallic_roughness: vec4<f32>;
var metallic: f32;
- var perceptual_roughness2: f32;
- var roughness12: f32;
- var N2: vec3<f32>;
+ var perceptual_roughness_2: f32;
+ var roughness_12: f32;
+ var N_2: vec3<f32>;
var T: vec3<f32>;
var B: vec3<f32>;
var TBN: mat3x3<f32>;
var occlusion: f32;
var emissive: vec4<f32>;
- var V3: vec3<f32>;
- var NdotV4: f32;
+ var V_3: vec3<f32>;
+ var NdotV_4: f32;
var F0_4: vec3<f32>;
- var diffuseColor4: vec3<f32>;
- var R4: vec3<f32>;
+ var diffuseColor_4: vec3<f32>;
+ var R_4: vec3<f32>;
var light_accum: vec3<f32> = vec3<f32>(0.0, 0.0, 0.0);
var i: i32 = 0;
- var i1: i32 = 0;
+ var i_1: i32 = 0;
var diffuse_ambient: vec3<f32>;
var specular_ambient: vec3<f32>;
- let e40: vec4<f32> = global3.base_color;
+ let e40: vec4<f32> = global_3.base_color;
output_color = e40;
let e42: vec4<f32> = output_color;
- let e44: vec2<f32> = v_Uv1;
+ let e44: vec2<f32> = v_Uv_1;
let e45: vec4<f32> = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, e44);
output_color = (e42 * e45);
- let e48: vec2<f32> = v_Uv1;
+ let e48: vec2<f32> = v_Uv_1;
let e49: vec4<f32> = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, e48);
metallic_roughness = e49;
- let e51: f32 = global5.metallic;
+ let e51: f32 = global_5.metallic;
let e52: vec4<f32> = metallic_roughness;
metallic = (e51 * e52.z);
- let e56: f32 = global4.perceptual_roughness;
+ let e56: f32 = global_4.perceptual_roughness;
let e57: vec4<f32> = metallic_roughness;
- perceptual_roughness2 = (e56 * e57.y);
- let e62: f32 = perceptual_roughness2;
+ perceptual_roughness_2 = (e56 * e57.y);
+ let e62: f32 = perceptual_roughness_2;
let e63: f32 = perceptualRoughnessToRoughness(e62);
- roughness12 = e63;
- let e66: vec3<f32> = v_WorldNormal1;
- N2 = normalize(e66);
- let e69: vec4<f32> = v_WorldTangent1;
- let e71: vec4<f32> = v_WorldTangent1;
+ roughness_12 = e63;
+ let e66: vec3<f32> = v_WorldNormal_1;
+ N_2 = normalize(e66);
+ let e69: vec4<f32> = v_WorldTangent_1;
+ let e71: vec4<f32> = v_WorldTangent_1;
T = normalize(e71.xyz);
- let e77: vec3<f32> = N2;
+ let e77: vec3<f32> = N_2;
let e78: vec3<f32> = T;
- let e80: vec4<f32> = v_WorldTangent1;
+ let e80: vec4<f32> = v_WorldTangent_1;
B = (cross(e77, e78) * e80.w);
let e85: bool = gl_FrontFacing;
- let e86: vec3<f32> = N2;
- let e87: vec3<f32> = N2;
- N2 = select(-(e87), e86, e85);
+ let e86: vec3<f32> = N_2;
+ let e87: vec3<f32> = N_2;
+ N_2 = select(-(e87), e86, e85);
let e90: bool = gl_FrontFacing;
let e91: vec3<f32> = T;
let e92: vec3<f32> = T;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -761,53 +761,53 @@ fn main1() {
B = select(-(e97), e96, e95);
let e100: vec3<f32> = T;
let e101: vec3<f32> = B;
- let e102: vec3<f32> = N2;
+ let e102: vec3<f32> = N_2;
TBN = mat3x3<f32>(vec3<f32>(e100.x, e100.y, e100.z), vec3<f32>(e101.x, e101.y, e101.z), vec3<f32>(e102.x, e102.y, e102.z));
let e117: mat3x3<f32> = TBN;
- let e119: vec2<f32> = v_Uv1;
+ let e119: vec2<f32> = v_Uv_1;
let e120: vec4<f32> = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, e119);
- let e128: vec2<f32> = v_Uv1;
+ let e128: vec2<f32> = v_Uv_1;
let e129: vec4<f32> = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, e128);
- N2 = (e117 * normalize(((e129.xyz * 2.0) - vec3<f32>(1.0))));
- let e139: vec2<f32> = v_Uv1;
+ N_2 = (e117 * normalize(((e129.xyz * 2.0) - vec3<f32>(1.0))));
+ let e139: vec2<f32> = v_Uv_1;
let e140: vec4<f32> = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, e139);
occlusion = e140.x;
- let e143: vec4<f32> = global7.emissive;
+ let e143: vec4<f32> = global_7.emissive;
emissive = e143;
let e145: vec4<f32> = emissive;
let e147: vec4<f32> = emissive;
- let e150: vec2<f32> = v_Uv1;
+ let e150: vec2<f32> = v_Uv_1;
let e151: vec4<f32> = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, e150);
let e153: vec3<f32> = (e147.xyz * e151.xyz);
emissive.x = e153.x;
emissive.y = e153.y;
emissive.z = e153.z;
- let e160: vec4<f32> = global1.CameraPos;
- let e162: vec3<f32> = v_WorldPosition1;
- let e165: vec4<f32> = global1.CameraPos;
- let e167: vec3<f32> = v_WorldPosition1;
- V3 = normalize((e165.xyz - e167.xyz));
- let e174: vec3<f32> = N2;
- let e175: vec3<f32> = V3;
- let e180: vec3<f32> = N2;
- let e181: vec3<f32> = V3;
- NdotV4 = max(dot(e180, e181), 0.00009999999747378752);
- let e187: f32 = global6.reflectance;
- let e189: f32 = global6.reflectance;
+ let e160: vec4<f32> = global_1.CameraPos;
+ let e162: vec3<f32> = v_WorldPosition_1;
+ let e165: vec4<f32> = global_1.CameraPos;
+ let e167: vec3<f32> = v_WorldPosition_1;
+ V_3 = normalize((e165.xyz - e167.xyz));
+ let e174: vec3<f32> = N_2;
+ let e175: vec3<f32> = V_3;
+ let e180: vec3<f32> = N_2;
+ let e181: vec3<f32> = V_3;
+ NdotV_4 = max(dot(e180, e181), 0.0010000000474974513);
+ let e187: f32 = global_6.reflectance;
+ let e189: f32 = global_6.reflectance;
let e192: f32 = metallic;
let e196: vec4<f32> = output_color;
let e198: f32 = metallic;
F0_4 = (vec3<f32>((((0.1599999964237213 * e187) * e189) * (1.0 - e192))) + (e196.xyz * vec3<f32>(e198)));
let e203: vec4<f32> = output_color;
let e206: f32 = metallic;
- diffuseColor4 = (e203.xyz * vec3<f32>((1.0 - e206)));
- let e211: vec3<f32> = V3;
- let e214: vec3<f32> = V3;
- let e216: vec3<f32> = N2;
- R4 = reflect(-(e214), e216);
+ diffuseColor_4 = (e203.xyz * vec3<f32>((1.0 - e206)));
+ let e211: vec3<f32> = V_3;
+ let e214: vec3<f32> = V_3;
+ let e216: vec3<f32> = N_2;
+ R_4 = reflect(-(e214), e216);
loop {
let e224: i32 = i;
- let e225: vec4<u32> = global2.NumLights;
+ let e225: vec4<u32> = global_2.NumLights;
let e229: i32 = i;
if (!(((e224 < i32(e225.x)) && (e229 < 10)))) {
break;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -816,14 +816,14 @@ fn main1() {
let e236: vec3<f32> = light_accum;
let e237: i32 = i;
let e247: i32 = i;
- let e249: PointLight = global2.PointLights[e247];
- let e250: f32 = roughness12;
- let e251: f32 = NdotV4;
- let e252: vec3<f32> = N2;
- let e253: vec3<f32> = V3;
- let e254: vec3<f32> = R4;
+ let e249: PointLight = global_2.PointLights[e247];
+ let e250: f32 = roughness_12;
+ let e251: f32 = NdotV_4;
+ let e252: vec3<f32> = N_2;
+ let e253: vec3<f32> = V_3;
+ let e254: vec3<f32> = R_4;
let e255: vec3<f32> = F0_4;
- let e256: vec3<f32> = diffuseColor4;
+ let e256: vec3<f32> = diffuseColor_4;
let e257: vec3<f32> = point_light(e249, e250, e251, e252, e253, e254, e255, e256);
light_accum = (e236 + e257);
}
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -833,39 +833,39 @@ fn main1() {
}
}
loop {
- let e261: i32 = i1;
- let e262: vec4<u32> = global2.NumLights;
- let e266: i32 = i1;
+ let e261: i32 = i_1;
+ let e262: vec4<u32> = global_2.NumLights;
+ let e266: i32 = i_1;
if (!(((e261 < i32(e262.y)) && (e266 < 1)))) {
break;
}
{
let e273: vec3<f32> = light_accum;
- let e274: i32 = i1;
- let e284: i32 = i1;
- let e286: DirectionalLight = global2.DirectionalLights[e284];
- let e287: f32 = roughness12;
- let e288: f32 = NdotV4;
- let e289: vec3<f32> = N2;
- let e290: vec3<f32> = V3;
- let e291: vec3<f32> = R4;
+ let e274: i32 = i_1;
+ let e284: i32 = i_1;
+ let e286: DirectionalLight = global_2.DirectionalLights[e284];
+ let e287: f32 = roughness_12;
+ let e288: f32 = NdotV_4;
+ let e289: vec3<f32> = N_2;
+ let e290: vec3<f32> = V_3;
+ let e291: vec3<f32> = R_4;
let e292: vec3<f32> = F0_4;
- let e293: vec3<f32> = diffuseColor4;
+ let e293: vec3<f32> = diffuseColor_4;
let e294: vec3<f32> = dir_light(e286, e287, e288, e289, e290, e291, e292, e293);
light_accum = (e273 + e294);
}
continuing {
- let e270: i32 = i1;
- i1 = (e270 + 1);
+ let e270: i32 = i_1;
+ i_1 = (e270 + 1);
}
}
- let e299: vec3<f32> = diffuseColor4;
- let e301: f32 = NdotV4;
+ let e299: vec3<f32> = diffuseColor_4;
+ let e301: f32 = NdotV_4;
let e302: vec3<f32> = EnvBRDFApprox(e299, 1.0, e301);
diffuse_ambient = e302;
let e307: vec3<f32> = F0_4;
- let e308: f32 = perceptual_roughness2;
- let e309: f32 = NdotV4;
+ let e308: f32 = perceptual_roughness_2;
+ let e309: f32 = NdotV_4;
let e310: vec3<f32> = EnvBRDFApprox(e307, e308, e309);
specular_ambient = e310;
let e312: vec4<f32> = output_color;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -877,7 +877,7 @@ fn main1() {
let e323: vec4<f32> = output_color;
let e325: vec3<f32> = diffuse_ambient;
let e326: vec3<f32> = specular_ambient;
- let e328: vec4<f32> = global2.AmbientColor;
+ let e328: vec4<f32> = global_2.AmbientColor;
let e331: f32 = occlusion;
let e333: vec3<f32> = (e323.xyz + (((e325 + e326) * e328.xyz) * e331));
output_color.x = e333.x;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -905,12 +905,12 @@ fn main1() {
[[stage(fragment)]]
fn main([[location(0)]] v_WorldPosition: vec3<f32>, [[location(1)]] v_WorldNormal: vec3<f32>, [[location(2)]] v_Uv: vec2<f32>, [[location(3)]] v_WorldTangent: vec4<f32>, [[builtin(front_facing)]] param: bool) -> FragmentOutput {
- v_WorldPosition1 = v_WorldPosition;
- v_WorldNormal1 = v_WorldNormal;
- v_Uv1 = v_Uv;
- v_WorldTangent1 = v_WorldTangent;
+ v_WorldPosition_1 = v_WorldPosition;
+ v_WorldNormal_1 = v_WorldNormal;
+ v_Uv_1 = v_Uv;
+ v_WorldTangent_1 = v_WorldTangent;
gl_FrontFacing = param;
- main1();
+ main_1();
let e72: vec4<f32> = o_Target;
return FragmentOutput(e72);
}
diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl
--- a/tests/out/wgsl/bevy-pbr-vert.wgsl
+++ b/tests/out/wgsl/bevy-pbr-vert.wgsl
@@ -16,10 +16,10 @@ struct VertexOutput {
[[builtin(position)]] member: vec4<f32>;
};
-var<private> Vertex_Position1: vec3<f32>;
-var<private> Vertex_Normal1: vec3<f32>;
-var<private> Vertex_Uv1: vec2<f32>;
-var<private> Vertex_Tangent1: vec4<f32>;
+var<private> Vertex_Position_1: vec3<f32>;
+var<private> Vertex_Normal_1: vec3<f32>;
+var<private> Vertex_Uv_1: vec2<f32>;
+var<private> Vertex_Tangent_1: vec4<f32>;
var<private> v_WorldPosition: vec3<f32>;
var<private> v_WorldNormal: vec3<f32>;
var<private> v_Uv: vec2<f32>;
diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl
--- a/tests/out/wgsl/bevy-pbr-vert.wgsl
+++ b/tests/out/wgsl/bevy-pbr-vert.wgsl
@@ -27,25 +27,25 @@ var<private> v_Uv: vec2<f32>;
var<uniform> global: CameraViewProj;
var<private> v_WorldTangent: vec4<f32>;
[[group(2), binding(0)]]
-var<uniform> global1: Transform;
+var<uniform> global_1: Transform;
var<private> gl_Position: vec4<f32>;
-fn main1() {
+fn main_1() {
var world_position: vec4<f32>;
- let e12: mat4x4<f32> = global1.Model;
- let e13: vec3<f32> = Vertex_Position1;
+ let e12: mat4x4<f32> = global_1.Model;
+ let e13: vec3<f32> = Vertex_Position_1;
world_position = (e12 * vec4<f32>(e13, 1.0));
let e18: vec4<f32> = world_position;
v_WorldPosition = e18.xyz;
- let e20: mat4x4<f32> = global1.Model;
- let e28: vec3<f32> = Vertex_Normal1;
+ let e20: mat4x4<f32> = global_1.Model;
+ let e28: vec3<f32> = Vertex_Normal_1;
v_WorldNormal = (mat3x3<f32>(e20[0].xyz, e20[1].xyz, e20[2].xyz) * e28);
- let e30: vec2<f32> = Vertex_Uv1;
+ let e30: vec2<f32> = Vertex_Uv_1;
v_Uv = e30;
- let e31: mat4x4<f32> = global1.Model;
- let e39: vec4<f32> = Vertex_Tangent1;
- let e42: vec4<f32> = Vertex_Tangent1;
+ let e31: mat4x4<f32> = global_1.Model;
+ let e39: vec4<f32> = Vertex_Tangent_1;
+ let e42: vec4<f32> = Vertex_Tangent_1;
v_WorldTangent = vec4<f32>((mat3x3<f32>(e31[0].xyz, e31[1].xyz, e31[2].xyz) * e39.xyz), e42.w);
let e46: mat4x4<f32> = global.ViewProj;
let e47: vec4<f32> = world_position;
diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl
--- a/tests/out/wgsl/bevy-pbr-vert.wgsl
+++ b/tests/out/wgsl/bevy-pbr-vert.wgsl
@@ -55,11 +55,11 @@ fn main1() {
[[stage(vertex)]]
fn main([[location(0)]] Vertex_Position: vec3<f32>, [[location(1)]] Vertex_Normal: vec3<f32>, [[location(2)]] Vertex_Uv: vec2<f32>, [[location(3)]] Vertex_Tangent: vec4<f32>) -> VertexOutput {
- Vertex_Position1 = Vertex_Position;
- Vertex_Normal1 = Vertex_Normal;
- Vertex_Uv1 = Vertex_Uv;
- Vertex_Tangent1 = Vertex_Tangent;
- main1();
+ Vertex_Position_1 = Vertex_Position;
+ Vertex_Normal_1 = Vertex_Normal;
+ Vertex_Uv_1 = Vertex_Uv;
+ Vertex_Tangent_1 = Vertex_Tangent;
+ main_1();
let e29: vec3<f32> = v_WorldPosition;
let e31: vec3<f32> = v_WorldNormal;
let e33: vec2<f32> = v_Uv;
diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl
--- a/tests/out/wgsl/bits_glsl-frag.wgsl
+++ b/tests/out/wgsl/bits_glsl-frag.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var i: i32 = 0;
var i2_: vec2<i32> = vec2<i32>(0, 0);
var i3_: vec3<i32> = vec3<i32>(0, 0, 0);
diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl
--- a/tests/out/wgsl/bits_glsl-frag.wgsl
+++ b/tests/out/wgsl/bits_glsl-frag.wgsl
@@ -75,6 +75,6 @@ fn main1() {
[[stage(fragment)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl
--- a/tests/out/wgsl/bool-select-frag.wgsl
+++ b/tests/out/wgsl/bool-select-frag.wgsl
@@ -5,30 +5,30 @@ struct FragmentOutput {
var<private> o_color: vec4<f32>;
fn TevPerCompGT(a: f32, b: f32) -> f32 {
- var a1: f32;
- var b1: f32;
+ var a_1: f32;
+ var b_1: f32;
- a1 = a;
- b1 = b;
- let e5: f32 = a1;
- let e6: f32 = b1;
+ a_1 = a;
+ b_1 = b;
+ let e5: f32 = a_1;
+ let e6: f32 = b_1;
return select(0.0, 1.0, (e5 > e6));
}
-fn TevPerCompGT1(a2: vec3<f32>, b2: vec3<f32>) -> vec3<f32> {
- var a3: vec3<f32>;
- var b3: vec3<f32>;
+fn TevPerCompGT_1(a_2: vec3<f32>, b_2: vec3<f32>) -> vec3<f32> {
+ var a_3: vec3<f32>;
+ var b_3: vec3<f32>;
- a3 = a2;
- b3 = b2;
- let e7: vec3<f32> = a3;
- let e8: vec3<f32> = b3;
+ a_3 = a_2;
+ b_3 = b_2;
+ let e7: vec3<f32> = a_3;
+ let e8: vec3<f32> = b_3;
return select(vec3<f32>(0.0), vec3<f32>(1.0), (e7 > e8));
}
-fn main1() {
+fn main_1() {
let e1: vec4<f32> = o_color;
- let e11: vec3<f32> = TevPerCompGT1(vec3<f32>(3.0), vec3<f32>(5.0));
+ let e11: vec3<f32> = TevPerCompGT_1(vec3<f32>(3.0), vec3<f32>(5.0));
o_color.x = e11.x;
o_color.y = e11.y;
o_color.z = e11.z;
diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl
--- a/tests/out/wgsl/bool-select-frag.wgsl
+++ b/tests/out/wgsl/bool-select-frag.wgsl
@@ -39,7 +39,7 @@ fn main1() {
[[stage(fragment)]]
fn main() -> FragmentOutput {
- main1();
+ main_1();
let e3: vec4<f32> = o_color;
return FragmentOutput(e3);
}
diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl
--- a/tests/out/wgsl/clamp-splat-vert.wgsl
+++ b/tests/out/wgsl/clamp-splat-vert.wgsl
@@ -2,19 +2,19 @@ struct VertexOutput {
[[builtin(position)]] member: vec4<f32>;
};
-var<private> a_pos1: vec2<f32>;
+var<private> a_pos_1: vec2<f32>;
var<private> gl_Position: vec4<f32>;
-fn main1() {
- let e5: vec2<f32> = a_pos1;
+fn main_1() {
+ let e5: vec2<f32> = a_pos_1;
gl_Position = vec4<f32>(clamp(e5, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0, 1.0);
return;
}
[[stage(vertex)]]
fn main([[location(0)]] a_pos: vec2<f32>) -> VertexOutput {
- a_pos1 = a_pos;
- main1();
+ a_pos_1 = a_pos;
+ main_1();
let e5: vec4<f32> = gl_Position;
return VertexOutput(e5);
}
diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl
--- a/tests/out/wgsl/constant-array-size-vert.wgsl
+++ b/tests/out/wgsl/constant-array-size-vert.wgsl
@@ -6,7 +6,7 @@ struct Data {
[[group(1), binding(0)]]
var<uniform> global: Data;
-fn function1() -> vec4<f32> {
+fn function_() -> vec4<f32> {
var sum: vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 0.0);
var i: i32 = 0;
diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl
--- a/tests/out/wgsl/constant-array-size-vert.wgsl
+++ b/tests/out/wgsl/constant-array-size-vert.wgsl
@@ -30,12 +30,12 @@ fn function1() -> vec4<f32> {
return e20;
}
-fn main1() {
+fn main_1() {
return;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git /dev/null b/tests/out/wgsl/empty-global-name-frag.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/out/wgsl/empty-global-name-frag.wgsl
@@ -0,0 +1,21 @@
+[[block]]
+struct TextureData {
+ material: vec4<f32>;
+};
+
+[[group(1), binding(1)]]
+var<uniform> global: TextureData;
+
+fn main_1() {
+ var coords: vec2<f32>;
+
+ let e2: vec4<f32> = global.material;
+ coords = vec2<f32>(e2.xy);
+ return;
+}
+
+[[stage(fragment)]]
+fn main() {
+ main_1();
+ return;
+}
diff --git /dev/null b/tests/out/wgsl/empty-global-name.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/out/wgsl/empty-global-name.wgsl
@@ -0,0 +1,18 @@
+[[block]]
+struct type_1 {
+ member: i32;
+};
+
+[[group(0), binding(0)]]
+var<storage, read_write> unnamed: type_1;
+
+fn function_() {
+ let e8: i32 = unnamed.member;
+ unnamed.member = (e8 + 1);
+ return;
+}
+
+[[stage(compute), workgroup_size(64, 1, 1)]]
+fn main() {
+ function_();
+}
diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl
--- a/tests/out/wgsl/expressions-frag.wgsl
+++ b/tests/out/wgsl/expressions-frag.wgsl
@@ -6,172 +6,172 @@ var<private> global: f32;
var<private> o_color: vec4<f32>;
fn testBinOpVecFloat(a: vec4<f32>, b: f32) {
- var a1: vec4<f32>;
- var b1: f32;
+ var a_1: vec4<f32>;
+ var b_1: f32;
var v: vec4<f32>;
- a1 = a;
- b1 = b;
- let e5: vec4<f32> = a1;
+ a_1 = a;
+ b_1 = b;
+ let e5: vec4<f32> = a_1;
v = (e5 * 2.0);
- let e8: vec4<f32> = a1;
+ let e8: vec4<f32> = a_1;
v = (e8 / vec4<f32>(2.0));
- let e12: vec4<f32> = a1;
+ let e12: vec4<f32> = a_1;
v = (e12 + vec4<f32>(2.0));
- let e16: vec4<f32> = a1;
+ let e16: vec4<f32> = a_1;
v = (e16 - vec4<f32>(2.0));
return;
}
-fn testBinOpFloatVec(a2: vec4<f32>, b2: f32) {
- var a3: vec4<f32>;
- var b3: f32;
- var v1: vec4<f32>;
-
- a3 = a2;
- b3 = b2;
- let e5: vec4<f32> = a3;
- let e6: f32 = b3;
- v1 = (e5 * e6);
- let e8: vec4<f32> = a3;
- let e9: f32 = b3;
- v1 = (e8 / vec4<f32>(e9));
- let e12: vec4<f32> = a3;
- let e13: f32 = b3;
- v1 = (e12 + vec4<f32>(e13));
- let e16: vec4<f32> = a3;
- let e17: f32 = b3;
- v1 = (e16 - vec4<f32>(e17));
+fn testBinOpFloatVec(a_2: vec4<f32>, b_2: f32) {
+ var a_3: vec4<f32>;
+ var b_3: f32;
+ var v_1: vec4<f32>;
+
+ a_3 = a_2;
+ b_3 = b_2;
+ let e5: vec4<f32> = a_3;
+ let e6: f32 = b_3;
+ v_1 = (e5 * e6);
+ let e8: vec4<f32> = a_3;
+ let e9: f32 = b_3;
+ v_1 = (e8 / vec4<f32>(e9));
+ let e12: vec4<f32> = a_3;
+ let e13: f32 = b_3;
+ v_1 = (e12 + vec4<f32>(e13));
+ let e16: vec4<f32> = a_3;
+ let e17: f32 = b_3;
+ v_1 = (e16 - vec4<f32>(e17));
return;
}
-fn testBinOpIVecInt(a4: vec4<i32>, b4: i32) {
- var a5: vec4<i32>;
- var b5: i32;
- var v2: vec4<i32>;
-
- a5 = a4;
- b5 = b4;
- let e5: vec4<i32> = a5;
- let e6: i32 = b5;
- v2 = (e5 * e6);
- let e8: vec4<i32> = a5;
- let e9: i32 = b5;
- v2 = (e8 / vec4<i32>(e9));
- let e12: vec4<i32> = a5;
- let e13: i32 = b5;
- v2 = (e12 + vec4<i32>(e13));
- let e16: vec4<i32> = a5;
- let e17: i32 = b5;
- v2 = (e16 - vec4<i32>(e17));
- let e20: vec4<i32> = a5;
- let e21: i32 = b5;
- v2 = (e20 & vec4<i32>(e21));
- let e24: vec4<i32> = a5;
- let e25: i32 = b5;
- v2 = (e24 | vec4<i32>(e25));
- let e28: vec4<i32> = a5;
- let e29: i32 = b5;
- v2 = (e28 ^ vec4<i32>(e29));
- let e32: vec4<i32> = a5;
- let e33: i32 = b5;
- v2 = (e32 >> vec4<u32>(u32(e33)));
- let e37: vec4<i32> = a5;
- let e38: i32 = b5;
- v2 = (e37 << vec4<u32>(u32(e38)));
+fn testBinOpIVecInt(a_4: vec4<i32>, b_4: i32) {
+ var a_5: vec4<i32>;
+ var b_5: i32;
+ var v_2: vec4<i32>;
+
+ a_5 = a_4;
+ b_5 = b_4;
+ let e5: vec4<i32> = a_5;
+ let e6: i32 = b_5;
+ v_2 = (e5 * e6);
+ let e8: vec4<i32> = a_5;
+ let e9: i32 = b_5;
+ v_2 = (e8 / vec4<i32>(e9));
+ let e12: vec4<i32> = a_5;
+ let e13: i32 = b_5;
+ v_2 = (e12 + vec4<i32>(e13));
+ let e16: vec4<i32> = a_5;
+ let e17: i32 = b_5;
+ v_2 = (e16 - vec4<i32>(e17));
+ let e20: vec4<i32> = a_5;
+ let e21: i32 = b_5;
+ v_2 = (e20 & vec4<i32>(e21));
+ let e24: vec4<i32> = a_5;
+ let e25: i32 = b_5;
+ v_2 = (e24 | vec4<i32>(e25));
+ let e28: vec4<i32> = a_5;
+ let e29: i32 = b_5;
+ v_2 = (e28 ^ vec4<i32>(e29));
+ let e32: vec4<i32> = a_5;
+ let e33: i32 = b_5;
+ v_2 = (e32 >> vec4<u32>(u32(e33)));
+ let e37: vec4<i32> = a_5;
+ let e38: i32 = b_5;
+ v_2 = (e37 << vec4<u32>(u32(e38)));
return;
}
-fn testBinOpIntIVec(a6: i32, b6: vec4<i32>) {
- var a7: i32;
- var b7: vec4<i32>;
- var v3: vec4<i32>;
-
- a7 = a6;
- b7 = b6;
- let e5: i32 = a7;
- let e6: vec4<i32> = b7;
- v3 = (e5 * e6);
- let e8: i32 = a7;
- let e9: vec4<i32> = b7;
- v3 = (vec4<i32>(e8) + e9);
- let e12: i32 = a7;
- let e13: vec4<i32> = b7;
- v3 = (vec4<i32>(e12) - e13);
- let e16: i32 = a7;
- let e17: vec4<i32> = b7;
- v3 = (vec4<i32>(e16) & e17);
- let e20: i32 = a7;
- let e21: vec4<i32> = b7;
- v3 = (vec4<i32>(e20) | e21);
- let e24: i32 = a7;
- let e25: vec4<i32> = b7;
- v3 = (vec4<i32>(e24) ^ e25);
+fn testBinOpIntIVec(a_6: i32, b_6: vec4<i32>) {
+ var a_7: i32;
+ var b_7: vec4<i32>;
+ var v_3: vec4<i32>;
+
+ a_7 = a_6;
+ b_7 = b_6;
+ let e5: i32 = a_7;
+ let e6: vec4<i32> = b_7;
+ v_3 = (e5 * e6);
+ let e8: i32 = a_7;
+ let e9: vec4<i32> = b_7;
+ v_3 = (vec4<i32>(e8) + e9);
+ let e12: i32 = a_7;
+ let e13: vec4<i32> = b_7;
+ v_3 = (vec4<i32>(e12) - e13);
+ let e16: i32 = a_7;
+ let e17: vec4<i32> = b_7;
+ v_3 = (vec4<i32>(e16) & e17);
+ let e20: i32 = a_7;
+ let e21: vec4<i32> = b_7;
+ v_3 = (vec4<i32>(e20) | e21);
+ let e24: i32 = a_7;
+ let e25: vec4<i32> = b_7;
+ v_3 = (vec4<i32>(e24) ^ e25);
return;
}
-fn testBinOpUVecUint(a8: vec4<u32>, b8: u32) {
- var a9: vec4<u32>;
- var b9: u32;
- var v4: vec4<u32>;
-
- a9 = a8;
- b9 = b8;
- let e5: vec4<u32> = a9;
- let e6: u32 = b9;
- v4 = (e5 * e6);
- let e8: vec4<u32> = a9;
- let e9: u32 = b9;
- v4 = (e8 / vec4<u32>(e9));
- let e12: vec4<u32> = a9;
- let e13: u32 = b9;
- v4 = (e12 + vec4<u32>(e13));
- let e16: vec4<u32> = a9;
- let e17: u32 = b9;
- v4 = (e16 - vec4<u32>(e17));
- let e20: vec4<u32> = a9;
- let e21: u32 = b9;
- v4 = (e20 & vec4<u32>(e21));
- let e24: vec4<u32> = a9;
- let e25: u32 = b9;
- v4 = (e24 | vec4<u32>(e25));
- let e28: vec4<u32> = a9;
- let e29: u32 = b9;
- v4 = (e28 ^ vec4<u32>(e29));
- let e32: vec4<u32> = a9;
- let e33: u32 = b9;
- v4 = (e32 >> vec4<u32>(e33));
- let e36: vec4<u32> = a9;
- let e37: u32 = b9;
- v4 = (e36 << vec4<u32>(e37));
+fn testBinOpUVecUint(a_8: vec4<u32>, b_8: u32) {
+ var a_9: vec4<u32>;
+ var b_9: u32;
+ var v_4: vec4<u32>;
+
+ a_9 = a_8;
+ b_9 = b_8;
+ let e5: vec4<u32> = a_9;
+ let e6: u32 = b_9;
+ v_4 = (e5 * e6);
+ let e8: vec4<u32> = a_9;
+ let e9: u32 = b_9;
+ v_4 = (e8 / vec4<u32>(e9));
+ let e12: vec4<u32> = a_9;
+ let e13: u32 = b_9;
+ v_4 = (e12 + vec4<u32>(e13));
+ let e16: vec4<u32> = a_9;
+ let e17: u32 = b_9;
+ v_4 = (e16 - vec4<u32>(e17));
+ let e20: vec4<u32> = a_9;
+ let e21: u32 = b_9;
+ v_4 = (e20 & vec4<u32>(e21));
+ let e24: vec4<u32> = a_9;
+ let e25: u32 = b_9;
+ v_4 = (e24 | vec4<u32>(e25));
+ let e28: vec4<u32> = a_9;
+ let e29: u32 = b_9;
+ v_4 = (e28 ^ vec4<u32>(e29));
+ let e32: vec4<u32> = a_9;
+ let e33: u32 = b_9;
+ v_4 = (e32 >> vec4<u32>(e33));
+ let e36: vec4<u32> = a_9;
+ let e37: u32 = b_9;
+ v_4 = (e36 << vec4<u32>(e37));
return;
}
-fn testBinOpUintUVec(a10: u32, b10: vec4<u32>) {
- var a11: u32;
- var b11: vec4<u32>;
- var v5: vec4<u32>;
-
- a11 = a10;
- b11 = b10;
- let e5: u32 = a11;
- let e6: vec4<u32> = b11;
- v5 = (e5 * e6);
- let e8: u32 = a11;
- let e9: vec4<u32> = b11;
- v5 = (vec4<u32>(e8) + e9);
- let e12: u32 = a11;
- let e13: vec4<u32> = b11;
- v5 = (vec4<u32>(e12) - e13);
- let e16: u32 = a11;
- let e17: vec4<u32> = b11;
- v5 = (vec4<u32>(e16) & e17);
- let e20: u32 = a11;
- let e21: vec4<u32> = b11;
- v5 = (vec4<u32>(e20) | e21);
- let e24: u32 = a11;
- let e25: vec4<u32> = b11;
- v5 = (vec4<u32>(e24) ^ e25);
+fn testBinOpUintUVec(a_10: u32, b_10: vec4<u32>) {
+ var a_11: u32;
+ var b_11: vec4<u32>;
+ var v_5: vec4<u32>;
+
+ a_11 = a_10;
+ b_11 = b_10;
+ let e5: u32 = a_11;
+ let e6: vec4<u32> = b_11;
+ v_5 = (e5 * e6);
+ let e8: u32 = a_11;
+ let e9: vec4<u32> = b_11;
+ v_5 = (vec4<u32>(e8) + e9);
+ let e12: u32 = a_11;
+ let e13: vec4<u32> = b_11;
+ v_5 = (vec4<u32>(e12) - e13);
+ let e16: u32 = a_11;
+ let e17: vec4<u32> = b_11;
+ v_5 = (vec4<u32>(e16) & e17);
+ let e20: u32 = a_11;
+ let e21: vec4<u32> = b_11;
+ v_5 = (vec4<u32>(e20) | e21);
+ let e24: u32 = a_11;
+ let e25: vec4<u32> = b_11;
+ v_5 = (vec4<u32>(e24) ^ e25);
return;
}
diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl
--- a/tests/out/wgsl/expressions-frag.wgsl
+++ b/tests/out/wgsl/expressions-frag.wgsl
@@ -181,15 +181,15 @@ fn testStructConstructor() {
}
fn testArrayConstructor() {
- var tree1: array<f32,1u> = array<f32,1u>(0.0);
+ var tree_1: array<f32,1u> = array<f32,1u>(0.0);
}
-fn privatePointer(a12: ptr<function, f32>) {
+fn privatePointer(a_12: ptr<function, f32>) {
return;
}
-fn main1() {
+fn main_1() {
var local: f32;
let e3: f32 = global;
diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl
--- a/tests/out/wgsl/expressions-frag.wgsl
+++ b/tests/out/wgsl/expressions-frag.wgsl
@@ -208,6 +208,6 @@ fn main1() {
[[stage(fragment)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl
--- a/tests/out/wgsl/fma-frag.wgsl
+++ b/tests/out/wgsl/fma-frag.wgsl
@@ -7,27 +7,27 @@ struct Mat4x3_ {
var<private> o_color: vec4<f32>;
fn Fma(d: ptr<function, Mat4x3_>, m: Mat4x3_, s: f32) {
- var m1: Mat4x3_;
- var s1: f32;
+ var m_1: Mat4x3_;
+ var s_1: f32;
- m1 = m;
- s1 = s;
+ m_1 = m;
+ s_1 = s;
let e6: Mat4x3_ = (*d);
- let e8: Mat4x3_ = m1;
- let e10: f32 = s1;
+ let e8: Mat4x3_ = m_1;
+ let e10: f32 = s_1;
(*d).mx = (e6.mx + (e8.mx * e10));
let e14: Mat4x3_ = (*d);
- let e16: Mat4x3_ = m1;
- let e18: f32 = s1;
+ let e16: Mat4x3_ = m_1;
+ let e18: f32 = s_1;
(*d).my = (e14.my + (e16.my * e18));
let e22: Mat4x3_ = (*d);
- let e24: Mat4x3_ = m1;
- let e26: f32 = s1;
+ let e24: Mat4x3_ = m_1;
+ let e26: f32 = s_1;
(*d).mz = (e22.mz + (e24.mz * e26));
return;
}
-fn main1() {
+fn main_1() {
let e1: vec4<f32> = o_color;
let e4: vec4<f32> = vec4<f32>(1.0);
o_color.x = e4.x;
diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl
--- a/tests/out/wgsl/fma-frag.wgsl
+++ b/tests/out/wgsl/fma-frag.wgsl
@@ -39,6 +39,6 @@ fn main1() {
[[stage(fragment)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl
--- a/tests/out/wgsl/global-constant-array-vert.wgsl
+++ b/tests/out/wgsl/global-constant-array-vert.wgsl
@@ -1,6 +1,6 @@
var<private> i: u32;
-fn main1() {
+fn main_1() {
var local: array<f32,2u> = array<f32,2u>(1.0, 2.0);
let e2: u32 = i;
diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl
--- a/tests/out/wgsl/global-constant-array-vert.wgsl
+++ b/tests/out/wgsl/global-constant-array-vert.wgsl
@@ -8,6 +8,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl
--- a/tests/out/wgsl/image.wgsl
+++ b/tests/out/wgsl/image.wgsl
@@ -46,11 +46,11 @@ fn main([[builtin(local_invocation_id)]] local_id: vec3<u32>) {
}
[[stage(compute), workgroup_size(16, 1, 1)]]
-fn depth_load([[builtin(local_invocation_id)]] local_id1: vec3<u32>) {
- let dim1: vec2<i32> = textureDimensions(image_storage_src);
- let itc1: vec2<i32> = ((dim1 * vec2<i32>(local_id1.xy)) % vec2<i32>(10, 20));
- let val: f32 = textureLoad(image_depth_multisampled_src, itc1, i32(local_id1.z));
- textureStore(image_dst, itc1.x, vec4<u32>(u32(val)));
+fn depth_load([[builtin(local_invocation_id)]] local_id_1: vec3<u32>) {
+ let dim_1: vec2<i32> = textureDimensions(image_storage_src);
+ let itc_1: vec2<i32> = ((dim_1 * vec2<i32>(local_id_1.xy)) % vec2<i32>(10, 20));
+ let val: f32 = textureLoad(image_depth_multisampled_src, itc_1, i32(local_id_1.z));
+ textureStore(image_dst, itc_1.x, vec4<u32>(u32(val)));
return;
}
diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl
--- a/tests/out/wgsl/image.wgsl
+++ b/tests/out/wgsl/image.wgsl
@@ -81,8 +81,8 @@ fn levels_queries() -> [[builtin(position)]] vec4<f32> {
let num_layers_cube: i32 = textureNumLayers(image_cube_array);
let num_levels_3d: i32 = textureNumLevels(image_3d);
let num_samples_aa: i32 = textureNumSamples(image_aa);
- let sum1: i32 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array);
- return vec4<f32>(f32(sum1));
+ let sum_1: i32 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array);
+ return vec4<f32>(f32(sum_1));
}
[[stage(fragment)]]
diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl
--- a/tests/out/wgsl/image.wgsl
+++ b/tests/out/wgsl/image.wgsl
@@ -98,8 +98,8 @@ fn sample() -> [[location(0)]] vec4<f32> {
[[stage(fragment)]]
fn sample_comparison() -> [[location(0)]] f32 {
- let tc1: vec2<f32> = vec2<f32>(0.5);
- let s2d_depth: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, tc1, 0.5);
- let s2d_depth_level: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc1, 0.5);
+ let tc_1: vec2<f32> = vec2<f32>(0.5);
+ let s2d_depth: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5);
+ let s2d_depth_level: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc_1, 0.5);
return (s2d_depth + s2d_depth_level);
}
diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl
--- a/tests/out/wgsl/interface.wgsl
+++ b/tests/out/wgsl/interface.wgsl
@@ -20,8 +20,8 @@ fn vertex([[builtin(vertex_index)]] vertex_index: u32, [[builtin(instance_index)
[[stage(fragment)]]
fn fragment(in: VertexOutput, [[builtin(front_facing)]] front_facing: bool, [[builtin(sample_index)]] sample_index: u32, [[builtin(sample_mask)]] sample_mask: u32) -> FragmentOutput {
let mask: u32 = (sample_mask & (1u << sample_index));
- let color1: f32 = select(0.0, 1.0, front_facing);
- return FragmentOutput(in.varying, mask, color1);
+ let color_1: f32 = select(0.0, 1.0, front_facing);
+ return FragmentOutput(in.varying, mask, color_1);
}
[[stage(compute), workgroup_size(1, 1, 1)]]
diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl
--- a/tests/out/wgsl/interpolate.wgsl
+++ b/tests/out/wgsl/interpolate.wgsl
@@ -26,6 +26,6 @@ fn main() -> FragmentInput {
}
[[stage(fragment)]]
-fn main1(val: FragmentInput) {
+fn main_1(val: FragmentInput) {
return;
}
diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
--- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
+++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
@@ -1,6 +1,6 @@
var<private> a: f32;
-fn main1() {
+fn main_1() {
var b: f32;
var c: f32;
var d: f32;
diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
--- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
+++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
@@ -16,5 +16,5 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
}
diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl
--- a/tests/out/wgsl/long-form-matrix-vert.wgsl
+++ b/tests/out/wgsl/long-form-matrix-vert.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var splat: mat2x2<f32> = mat2x2<f32>(vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0));
var normal: mat2x2<f32> = mat2x2<f32>(vec2<f32>(1.0, 1.0), vec2<f32>(2.0, 2.0));
var a: mat2x2<f32> = mat2x2<f32>(vec2<f32>(1.0, 2.0), vec2<f32>(3.0, 4.0));
diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl
--- a/tests/out/wgsl/long-form-matrix-vert.wgsl
+++ b/tests/out/wgsl/long-form-matrix-vert.wgsl
@@ -25,6 +25,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl
--- a/tests/out/wgsl/math-functions-vert.wgsl
+++ b/tests/out/wgsl/math-functions-vert.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var a: vec4<f32> = vec4<f32>(1.0, 1.0, 1.0, 1.0);
var b: vec4<f32> = vec4<f32>(2.0, 2.0, 2.0, 2.0);
var m: mat4x4<f32>;
diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl
--- a/tests/out/wgsl/math-functions-vert.wgsl
+++ b/tests/out/wgsl/math-functions-vert.wgsl
@@ -149,6 +149,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl
--- a/tests/out/wgsl/operators.wgsl
+++ b/tests/out/wgsl/operators.wgsl
@@ -47,8 +47,8 @@ fn constructors() -> f32 {
}
fn modulo() {
- let a1: i32 = (1 % 1);
- let b1: f32 = (1.0 % 1.0);
+ let a_1: i32 = (1 % 1);
+ let b_1: f32 = (1.0 % 1.0);
let c: vec3<i32> = (vec3<i32>(1) % vec3<i32>(1));
let d: vec3<f32> = (vec3<f32>(1.0) % vec3<f32>(1.0));
}
diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl
--- a/tests/out/wgsl/pointers.wgsl
+++ b/tests/out/wgsl/pointers.wgsl
@@ -1,6 +1,6 @@
[[block]]
struct DynamicArray {
- array1: [[stride(4)]] array<u32>;
+ array_: [[stride(4)]] array<u32>;
};
fn f() {
diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl
--- a/tests/out/wgsl/pointers.wgsl
+++ b/tests/out/wgsl/pointers.wgsl
@@ -11,9 +11,9 @@ fn f() {
return;
}
-fn index_dynamic_array(p: ptr<workgroup, DynamicArray>, i: i32, v1: u32) -> u32 {
- let old: u32 = (*p).array1[i];
- (*p).array1[i] = v1;
+fn index_dynamic_array(p: ptr<workgroup, DynamicArray>, i: i32, v_1: u32) -> u32 {
+ let old: u32 = (*p).array_[i];
+ (*p).array_[i] = v_1;
return old;
}
diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl
--- a/tests/out/wgsl/prepostfix-frag.wgsl
+++ b/tests/out/wgsl/prepostfix-frag.wgsl
@@ -1,10 +1,10 @@
-fn main1() {
+fn main_1() {
var scalar_target: i32;
var scalar: i32 = 1;
var vec_target: vec2<u32>;
- var vec1: vec2<u32> = vec2<u32>(1u, 1u);
+ var vec_: vec2<u32> = vec2<u32>(1u, 1u);
var mat_target: mat4x3<f32>;
- var mat1: mat4x3<f32> = mat4x3<f32>(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(0.0, 0.0, 1.0), vec3<f32>(0.0, 0.0, 0.0));
+ var mat_: mat4x3<f32> = mat4x3<f32>(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(0.0, 0.0, 1.0), vec3<f32>(0.0, 0.0, 0.0));
let e3: i32 = scalar;
scalar = (e3 + 1);
diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl
--- a/tests/out/wgsl/prepostfix-frag.wgsl
+++ b/tests/out/wgsl/prepostfix-frag.wgsl
@@ -13,28 +13,28 @@ fn main1() {
let e8: i32 = (e6 - 1);
scalar = e8;
scalar_target = e8;
- let e14: vec2<u32> = vec1;
- vec1 = (e14 - vec2<u32>(1u));
+ let e14: vec2<u32> = vec_;
+ vec_ = (e14 - vec2<u32>(1u));
vec_target = e14;
- let e18: vec2<u32> = vec1;
+ let e18: vec2<u32> = vec_;
let e21: vec2<u32> = (e18 + vec2<u32>(1u));
- vec1 = e21;
+ vec_ = e21;
vec_target = e21;
let e24: f32 = f32(1);
- let e32: mat4x3<f32> = mat1;
+ let e32: mat4x3<f32> = mat_;
let e34: vec3<f32> = vec3<f32>(1.0);
- mat1 = (e32 + mat4x3<f32>(e34, e34, e34, e34));
+ mat_ = (e32 + mat4x3<f32>(e34, e34, e34, e34));
mat_target = e32;
- let e37: mat4x3<f32> = mat1;
+ let e37: mat4x3<f32> = mat_;
let e39: vec3<f32> = vec3<f32>(1.0);
let e41: mat4x3<f32> = (e37 - mat4x3<f32>(e39, e39, e39, e39));
- mat1 = e41;
+ mat_ = e41;
mat_target = e41;
return;
}
[[stage(fragment)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl
--- a/tests/out/wgsl/quad-vert.wgsl
+++ b/tests/out/wgsl/quad-vert.wgsl
@@ -9,24 +9,24 @@ struct VertexOutput {
};
var<private> v_uv: vec2<f32>;
-var<private> a_uv1: vec2<f32>;
+var<private> a_uv_1: vec2<f32>;
var<private> perVertexStruct: gl_PerVertex = gl_PerVertex(vec4<f32>(0.0, 0.0, 0.0, 1.0), );
-var<private> a_pos1: vec2<f32>;
+var<private> a_pos_1: vec2<f32>;
-fn main1() {
- let e12: vec2<f32> = a_uv1;
+fn main_1() {
+ let e12: vec2<f32> = a_uv_1;
v_uv = e12;
- let e13: vec2<f32> = a_pos1;
+ let e13: vec2<f32> = a_pos_1;
perVertexStruct.gl_Position = vec4<f32>(e13.x, e13.y, 0.0, 1.0);
return;
}
[[stage(vertex)]]
fn main([[location(1)]] a_uv: vec2<f32>, [[location(0)]] a_pos: vec2<f32>) -> VertexOutput {
- a_uv1 = a_uv;
- a_pos1 = a_pos;
- main1();
- let e10: vec2<f32> = v_uv;
- let e11: vec4<f32> = perVertexStruct.gl_Position;
- return VertexOutput(e10, e11);
+ a_uv_1 = a_uv;
+ a_pos_1 = a_pos;
+ main_1();
+ let e7: vec2<f32> = v_uv;
+ let e8: vec4<f32> = perVertexStruct.gl_Position;
+ return VertexOutput(e7, e8);
}
diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl
--- a/tests/out/wgsl/quad.wgsl
+++ b/tests/out/wgsl/quad.wgsl
@@ -16,8 +16,8 @@ fn main([[location(0)]] pos: vec2<f32>, [[location(1)]] uv: vec2<f32>) -> Vertex
}
[[stage(fragment)]]
-fn main1([[location(0)]] uv1: vec2<f32>) -> [[location(0)]] vec4<f32> {
- let color: vec4<f32> = textureSample(u_texture, u_sampler, uv1);
+fn main_1([[location(0)]] uv_1: vec2<f32>) -> [[location(0)]] vec4<f32> {
+ let color: vec4<f32> = textureSample(u_texture, u_sampler, uv_1);
if ((color.w == 0.0)) {
discard;
}
diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl
--- a/tests/out/wgsl/quad_glsl-frag.wgsl
+++ b/tests/out/wgsl/quad_glsl-frag.wgsl
@@ -2,18 +2,18 @@ struct FragmentOutput {
[[location(0)]] o_color: vec4<f32>;
};
-var<private> v_uv1: vec2<f32>;
+var<private> v_uv_1: vec2<f32>;
var<private> o_color: vec4<f32>;
-fn main1() {
+fn main_1() {
o_color = vec4<f32>(1.0, 1.0, 1.0, 1.0);
return;
}
[[stage(fragment)]]
fn main([[location(0)]] v_uv: vec2<f32>) -> FragmentOutput {
- v_uv1 = v_uv;
- main1();
+ v_uv_1 = v_uv;
+ main_1();
let e7: vec4<f32> = o_color;
return FragmentOutput(e7);
}
diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl
--- a/tests/out/wgsl/quad_glsl-vert.wgsl
+++ b/tests/out/wgsl/quad_glsl-vert.wgsl
@@ -3,24 +3,24 @@ struct VertexOutput {
[[builtin(position)]] member: vec4<f32>;
};
-var<private> a_pos1: vec2<f32>;
-var<private> a_uv1: vec2<f32>;
+var<private> a_pos_1: vec2<f32>;
+var<private> a_uv_1: vec2<f32>;
var<private> v_uv: vec2<f32>;
var<private> gl_Position: vec4<f32>;
-fn main1() {
- let e4: vec2<f32> = a_uv1;
+fn main_1() {
+ let e4: vec2<f32> = a_uv_1;
v_uv = e4;
- let e6: vec2<f32> = a_pos1;
+ let e6: vec2<f32> = a_pos_1;
gl_Position = vec4<f32>((1.2000000476837158 * e6), 0.0, 1.0);
return;
}
[[stage(vertex)]]
fn main([[location(0)]] a_pos: vec2<f32>, [[location(1)]] a_uv: vec2<f32>) -> VertexOutput {
- a_pos1 = a_pos;
- a_uv1 = a_uv;
- main1();
+ a_pos_1 = a_pos;
+ a_uv_1 = a_uv;
+ main_1();
let e14: vec2<f32> = v_uv;
let e16: vec4<f32> = gl_Position;
return VertexOutput(e14, e16);
diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl
--- a/tests/out/wgsl/samplers-frag.wgsl
+++ b/tests/out/wgsl/samplers-frag.wgsl
@@ -26,331 +26,331 @@ var texCubeArrayShadow: texture_depth_cube_array;
var tex3DShadow: texture_3d<f32>;
[[group(1), binding(17)]]
var sampShadow: sampler_comparison;
-var<private> texcoord1: vec4<f32>;
+var<private> texcoord_1: vec4<f32>;
fn testTex1D(coord: f32) {
- var coord1: f32;
+ var coord_1: f32;
var c: vec4<f32>;
- coord1 = coord;
- let e18: f32 = coord1;
+ coord_1 = coord;
+ let e18: f32 = coord_1;
let e19: vec4<f32> = textureSample(tex1D, samp, e18);
c = e19;
- let e22: f32 = coord1;
+ let e22: f32 = coord_1;
let e24: vec4<f32> = textureSampleBias(tex1D, samp, e22, 2.0);
c = e24;
- let e28: f32 = coord1;
+ let e28: f32 = coord_1;
let e31: vec4<f32> = textureSampleGrad(tex1D, samp, e28, 4.0, 4.0);
c = e31;
- let e36: f32 = coord1;
+ let e36: f32 = coord_1;
let e40: vec4<f32> = textureSampleGrad(tex1D, samp, e36, 4.0, 4.0, 5);
c = e40;
- let e43: f32 = coord1;
+ let e43: f32 = coord_1;
let e45: vec4<f32> = textureSampleLevel(tex1D, samp, e43, 3.0);
c = e45;
- let e49: f32 = coord1;
+ let e49: f32 = coord_1;
let e52: vec4<f32> = textureSampleLevel(tex1D, samp, e49, 3.0, 5);
c = e52;
- let e55: f32 = coord1;
+ let e55: f32 = coord_1;
let e57: vec4<f32> = textureSample(tex1D, samp, e55, 5);
c = e57;
- let e61: f32 = coord1;
+ let e61: f32 = coord_1;
let e64: vec4<f32> = textureSampleBias(tex1D, samp, e61, 2.0, 5);
c = e64;
- let e65: f32 = coord1;
- let e68: f32 = coord1;
+ let e65: f32 = coord_1;
+ let e68: f32 = coord_1;
let e70: vec2<f32> = vec2<f32>(e68, 6.0);
let e74: vec4<f32> = textureSample(tex1D, samp, (e70.x / e70.y));
c = e74;
- let e75: f32 = coord1;
- let e80: f32 = coord1;
+ let e75: f32 = coord_1;
+ let e80: f32 = coord_1;
let e84: vec4<f32> = vec4<f32>(e80, 0.0, 0.0, 6.0);
let e90: vec4<f32> = textureSample(tex1D, samp, (e84.xyz / vec3<f32>(e84.w)).x);
c = e90;
- let e91: f32 = coord1;
- let e95: f32 = coord1;
+ let e91: f32 = coord_1;
+ let e95: f32 = coord_1;
let e97: vec2<f32> = vec2<f32>(e95, 6.0);
let e102: vec4<f32> = textureSampleBias(tex1D, samp, (e97.x / e97.y), 2.0);
c = e102;
- let e103: f32 = coord1;
- let e109: f32 = coord1;
+ let e103: f32 = coord_1;
+ let e109: f32 = coord_1;
let e113: vec4<f32> = vec4<f32>(e109, 0.0, 0.0, 6.0);
let e120: vec4<f32> = textureSampleBias(tex1D, samp, (e113.xyz / vec3<f32>(e113.w)).x, 2.0);
c = e120;
- let e121: f32 = coord1;
- let e126: f32 = coord1;
+ let e121: f32 = coord_1;
+ let e126: f32 = coord_1;
let e128: vec2<f32> = vec2<f32>(e126, 6.0);
let e134: vec4<f32> = textureSampleGrad(tex1D, samp, (e128.x / e128.y), 4.0, 4.0);
c = e134;
- let e135: f32 = coord1;
- let e142: f32 = coord1;
+ let e135: f32 = coord_1;
+ let e142: f32 = coord_1;
let e146: vec4<f32> = vec4<f32>(e142, 0.0, 0.0, 6.0);
let e154: vec4<f32> = textureSampleGrad(tex1D, samp, (e146.xyz / vec3<f32>(e146.w)).x, 4.0, 4.0);
c = e154;
- let e155: f32 = coord1;
- let e161: f32 = coord1;
+ let e155: f32 = coord_1;
+ let e161: f32 = coord_1;
let e163: vec2<f32> = vec2<f32>(e161, 6.0);
let e170: vec4<f32> = textureSampleGrad(tex1D, samp, (e163.x / e163.y), 4.0, 4.0, 5);
c = e170;
- let e171: f32 = coord1;
- let e179: f32 = coord1;
+ let e171: f32 = coord_1;
+ let e179: f32 = coord_1;
let e183: vec4<f32> = vec4<f32>(e179, 0.0, 0.0, 6.0);
let e192: vec4<f32> = textureSampleGrad(tex1D, samp, (e183.xyz / vec3<f32>(e183.w)).x, 4.0, 4.0, 5);
c = e192;
- let e193: f32 = coord1;
- let e197: f32 = coord1;
+ let e193: f32 = coord_1;
+ let e197: f32 = coord_1;
let e199: vec2<f32> = vec2<f32>(e197, 6.0);
let e204: vec4<f32> = textureSampleLevel(tex1D, samp, (e199.x / e199.y), 3.0);
c = e204;
- let e205: f32 = coord1;
- let e211: f32 = coord1;
+ let e205: f32 = coord_1;
+ let e211: f32 = coord_1;
let e215: vec4<f32> = vec4<f32>(e211, 0.0, 0.0, 6.0);
let e222: vec4<f32> = textureSampleLevel(tex1D, samp, (e215.xyz / vec3<f32>(e215.w)).x, 3.0);
c = e222;
- let e223: f32 = coord1;
- let e228: f32 = coord1;
+ let e223: f32 = coord_1;
+ let e228: f32 = coord_1;
let e230: vec2<f32> = vec2<f32>(e228, 6.0);
let e236: vec4<f32> = textureSampleLevel(tex1D, samp, (e230.x / e230.y), 3.0, 5);
c = e236;
- let e237: f32 = coord1;
- let e244: f32 = coord1;
+ let e237: f32 = coord_1;
+ let e244: f32 = coord_1;
let e248: vec4<f32> = vec4<f32>(e244, 0.0, 0.0, 6.0);
let e256: vec4<f32> = textureSampleLevel(tex1D, samp, (e248.xyz / vec3<f32>(e248.w)).x, 3.0, 5);
c = e256;
- let e257: f32 = coord1;
- let e261: f32 = coord1;
+ let e257: f32 = coord_1;
+ let e261: f32 = coord_1;
let e263: vec2<f32> = vec2<f32>(e261, 6.0);
let e268: vec4<f32> = textureSample(tex1D, samp, (e263.x / e263.y), 5);
c = e268;
- let e269: f32 = coord1;
- let e275: f32 = coord1;
+ let e269: f32 = coord_1;
+ let e275: f32 = coord_1;
let e279: vec4<f32> = vec4<f32>(e275, 0.0, 0.0, 6.0);
let e286: vec4<f32> = textureSample(tex1D, samp, (e279.xyz / vec3<f32>(e279.w)).x, 5);
c = e286;
- let e287: f32 = coord1;
- let e292: f32 = coord1;
+ let e287: f32 = coord_1;
+ let e292: f32 = coord_1;
let e294: vec2<f32> = vec2<f32>(e292, 6.0);
let e300: vec4<f32> = textureSampleBias(tex1D, samp, (e294.x / e294.y), 2.0, 5);
c = e300;
- let e301: f32 = coord1;
- let e308: f32 = coord1;
+ let e301: f32 = coord_1;
+ let e308: f32 = coord_1;
let e312: vec4<f32> = vec4<f32>(e308, 0.0, 0.0, 6.0);
let e320: vec4<f32> = textureSampleBias(tex1D, samp, (e312.xyz / vec3<f32>(e312.w)).x, 2.0, 5);
c = e320;
return;
}
-fn testTex1DArray(coord2: vec2<f32>) {
- var coord3: vec2<f32>;
- var c1: vec4<f32>;
+fn testTex1DArray(coord_2: vec2<f32>) {
+ var coord_3: vec2<f32>;
+ var c_1: vec4<f32>;
- coord3 = coord2;
- let e18: vec2<f32> = coord3;
+ coord_3 = coord_2;
+ let e18: vec2<f32> = coord_3;
let e22: vec4<f32> = textureSample(tex1DArray, samp, e18.x, i32(e18.y));
- c1 = e22;
- let e25: vec2<f32> = coord3;
+ c_1 = e22;
+ let e25: vec2<f32> = coord_3;
let e30: vec4<f32> = textureSampleBias(tex1DArray, samp, e25.x, i32(e25.y), 2.0);
- c1 = e30;
- let e34: vec2<f32> = coord3;
+ c_1 = e30;
+ let e34: vec2<f32> = coord_3;
let e40: vec4<f32> = textureSampleGrad(tex1DArray, samp, e34.x, i32(e34.y), 4.0, 4.0);
- c1 = e40;
- let e45: vec2<f32> = coord3;
+ c_1 = e40;
+ let e45: vec2<f32> = coord_3;
let e52: vec4<f32> = textureSampleGrad(tex1DArray, samp, e45.x, i32(e45.y), 4.0, 4.0, 5);
- c1 = e52;
- let e55: vec2<f32> = coord3;
+ c_1 = e52;
+ let e55: vec2<f32> = coord_3;
let e60: vec4<f32> = textureSampleLevel(tex1DArray, samp, e55.x, i32(e55.y), 3.0);
- c1 = e60;
- let e64: vec2<f32> = coord3;
+ c_1 = e60;
+ let e64: vec2<f32> = coord_3;
let e70: vec4<f32> = textureSampleLevel(tex1DArray, samp, e64.x, i32(e64.y), 3.0, 5);
- c1 = e70;
- let e73: vec2<f32> = coord3;
+ c_1 = e70;
+ let e73: vec2<f32> = coord_3;
let e78: vec4<f32> = textureSample(tex1DArray, samp, e73.x, i32(e73.y), 5);
- c1 = e78;
- let e82: vec2<f32> = coord3;
+ c_1 = e78;
+ let e82: vec2<f32> = coord_3;
let e88: vec4<f32> = textureSampleBias(tex1DArray, samp, e82.x, i32(e82.y), 2.0, 5);
- c1 = e88;
+ c_1 = e88;
return;
}
-fn testTex2D(coord4: vec2<f32>) {
- var coord5: vec2<f32>;
- var c2: vec4<f32>;
+fn testTex2D(coord_4: vec2<f32>) {
+ var coord_5: vec2<f32>;
+ var c_2: vec4<f32>;
- coord5 = coord4;
- let e18: vec2<f32> = coord5;
+ coord_5 = coord_4;
+ let e18: vec2<f32> = coord_5;
let e19: vec4<f32> = textureSample(tex2D, samp, e18);
- c2 = e19;
- let e22: vec2<f32> = coord5;
+ c_2 = e19;
+ let e22: vec2<f32> = coord_5;
let e24: vec4<f32> = textureSampleBias(tex2D, samp, e22, 2.0);
- c2 = e24;
- let e30: vec2<f32> = coord5;
+ c_2 = e24;
+ let e30: vec2<f32> = coord_5;
let e35: vec4<f32> = textureSampleGrad(tex2D, samp, e30, vec2<f32>(4.0), vec2<f32>(4.0));
- c2 = e35;
- let e43: vec2<f32> = coord5;
+ c_2 = e35;
+ let e43: vec2<f32> = coord_5;
let e50: vec4<f32> = textureSampleGrad(tex2D, samp, e43, vec2<f32>(4.0), vec2<f32>(4.0), vec2<i32>(5, 5));
- c2 = e50;
- let e53: vec2<f32> = coord5;
+ c_2 = e50;
+ let e53: vec2<f32> = coord_5;
let e55: vec4<f32> = textureSampleLevel(tex2D, samp, e53, 3.0);
- c2 = e55;
- let e60: vec2<f32> = coord5;
+ c_2 = e55;
+ let e60: vec2<f32> = coord_5;
let e64: vec4<f32> = textureSampleLevel(tex2D, samp, e60, 3.0, vec2<i32>(5, 5));
- c2 = e64;
- let e68: vec2<f32> = coord5;
+ c_2 = e64;
+ let e68: vec2<f32> = coord_5;
let e71: vec4<f32> = textureSample(tex2D, samp, e68, vec2<i32>(5, 5));
- c2 = e71;
- let e76: vec2<f32> = coord5;
+ c_2 = e71;
+ let e76: vec2<f32> = coord_5;
let e80: vec4<f32> = textureSampleBias(tex2D, samp, e76, 2.0, vec2<i32>(5, 5));
- c2 = e80;
- let e81: vec2<f32> = coord5;
- let e84: vec2<f32> = coord5;
+ c_2 = e80;
+ let e81: vec2<f32> = coord_5;
+ let e84: vec2<f32> = coord_5;
let e86: vec3<f32> = vec3<f32>(e84, 6.0);
let e91: vec4<f32> = textureSample(tex2D, samp, (e86.xy / vec2<f32>(e86.z)));
- c2 = e91;
- let e92: vec2<f32> = coord5;
- let e96: vec2<f32> = coord5;
+ c_2 = e91;
+ let e92: vec2<f32> = coord_5;
+ let e96: vec2<f32> = coord_5;
let e99: vec4<f32> = vec4<f32>(e96, 0.0, 6.0);
let e105: vec4<f32> = textureSample(tex2D, samp, (e99.xyz / vec3<f32>(e99.w)).xy);
- c2 = e105;
- let e106: vec2<f32> = coord5;
- let e110: vec2<f32> = coord5;
+ c_2 = e105;
+ let e106: vec2<f32> = coord_5;
+ let e110: vec2<f32> = coord_5;
let e112: vec3<f32> = vec3<f32>(e110, 6.0);
let e118: vec4<f32> = textureSampleBias(tex2D, samp, (e112.xy / vec2<f32>(e112.z)), 2.0);
- c2 = e118;
- let e119: vec2<f32> = coord5;
- let e124: vec2<f32> = coord5;
+ c_2 = e118;
+ let e119: vec2<f32> = coord_5;
+ let e124: vec2<f32> = coord_5;
let e127: vec4<f32> = vec4<f32>(e124, 0.0, 6.0);
let e134: vec4<f32> = textureSampleBias(tex2D, samp, (e127.xyz / vec3<f32>(e127.w)).xy, 2.0);
- c2 = e134;
- let e135: vec2<f32> = coord5;
- let e142: vec2<f32> = coord5;
+ c_2 = e134;
+ let e135: vec2<f32> = coord_5;
+ let e142: vec2<f32> = coord_5;
let e144: vec3<f32> = vec3<f32>(e142, 6.0);
let e153: vec4<f32> = textureSampleGrad(tex2D, samp, (e144.xy / vec2<f32>(e144.z)), vec2<f32>(4.0), vec2<f32>(4.0));
- c2 = e153;
- let e154: vec2<f32> = coord5;
- let e162: vec2<f32> = coord5;
+ c_2 = e153;
+ let e154: vec2<f32> = coord_5;
+ let e162: vec2<f32> = coord_5;
let e165: vec4<f32> = vec4<f32>(e162, 0.0, 6.0);
let e175: vec4<f32> = textureSampleGrad(tex2D, samp, (e165.xyz / vec3<f32>(e165.w)).xy, vec2<f32>(4.0), vec2<f32>(4.0));
- c2 = e175;
- let e176: vec2<f32> = coord5;
- let e185: vec2<f32> = coord5;
+ c_2 = e175;
+ let e176: vec2<f32> = coord_5;
+ let e185: vec2<f32> = coord_5;
let e187: vec3<f32> = vec3<f32>(e185, 6.0);
let e198: vec4<f32> = textureSampleGrad(tex2D, samp, (e187.xy / vec2<f32>(e187.z)), vec2<f32>(4.0), vec2<f32>(4.0), vec2<i32>(5, 5));
- c2 = e198;
- let e199: vec2<f32> = coord5;
- let e209: vec2<f32> = coord5;
+ c_2 = e198;
+ let e199: vec2<f32> = coord_5;
+ let e209: vec2<f32> = coord_5;
let e212: vec4<f32> = vec4<f32>(e209, 0.0, 6.0);
let e224: vec4<f32> = textureSampleGrad(tex2D, samp, (e212.xyz / vec3<f32>(e212.w)).xy, vec2<f32>(4.0), vec2<f32>(4.0), vec2<i32>(5, 5));
- c2 = e224;
- let e225: vec2<f32> = coord5;
- let e229: vec2<f32> = coord5;
+ c_2 = e224;
+ let e225: vec2<f32> = coord_5;
+ let e229: vec2<f32> = coord_5;
let e231: vec3<f32> = vec3<f32>(e229, 6.0);
let e237: vec4<f32> = textureSampleLevel(tex2D, samp, (e231.xy / vec2<f32>(e231.z)), 3.0);
- c2 = e237;
- let e238: vec2<f32> = coord5;
- let e243: vec2<f32> = coord5;
+ c_2 = e237;
+ let e238: vec2<f32> = coord_5;
+ let e243: vec2<f32> = coord_5;
let e246: vec4<f32> = vec4<f32>(e243, 0.0, 6.0);
let e253: vec4<f32> = textureSampleLevel(tex2D, samp, (e246.xyz / vec3<f32>(e246.w)).xy, 3.0);
- c2 = e253;
- let e254: vec2<f32> = coord5;
- let e260: vec2<f32> = coord5;
+ c_2 = e253;
+ let e254: vec2<f32> = coord_5;
+ let e260: vec2<f32> = coord_5;
let e262: vec3<f32> = vec3<f32>(e260, 6.0);
let e270: vec4<f32> = textureSampleLevel(tex2D, samp, (e262.xy / vec2<f32>(e262.z)), 3.0, vec2<i32>(5, 5));
- c2 = e270;
- let e271: vec2<f32> = coord5;
- let e278: vec2<f32> = coord5;
+ c_2 = e270;
+ let e271: vec2<f32> = coord_5;
+ let e278: vec2<f32> = coord_5;
let e281: vec4<f32> = vec4<f32>(e278, 0.0, 6.0);
let e290: vec4<f32> = textureSampleLevel(tex2D, samp, (e281.xyz / vec3<f32>(e281.w)).xy, 3.0, vec2<i32>(5, 5));
- c2 = e290;
- let e291: vec2<f32> = coord5;
- let e296: vec2<f32> = coord5;
+ c_2 = e290;
+ let e291: vec2<f32> = coord_5;
+ let e296: vec2<f32> = coord_5;
let e298: vec3<f32> = vec3<f32>(e296, 6.0);
let e305: vec4<f32> = textureSample(tex2D, samp, (e298.xy / vec2<f32>(e298.z)), vec2<i32>(5, 5));
- c2 = e305;
- let e306: vec2<f32> = coord5;
- let e312: vec2<f32> = coord5;
+ c_2 = e305;
+ let e306: vec2<f32> = coord_5;
+ let e312: vec2<f32> = coord_5;
let e315: vec4<f32> = vec4<f32>(e312, 0.0, 6.0);
let e323: vec4<f32> = textureSample(tex2D, samp, (e315.xyz / vec3<f32>(e315.w)).xy, vec2<i32>(5, 5));
- c2 = e323;
- let e324: vec2<f32> = coord5;
- let e330: vec2<f32> = coord5;
+ c_2 = e323;
+ let e324: vec2<f32> = coord_5;
+ let e330: vec2<f32> = coord_5;
let e332: vec3<f32> = vec3<f32>(e330, 6.0);
let e340: vec4<f32> = textureSampleBias(tex2D, samp, (e332.xy / vec2<f32>(e332.z)), 2.0, vec2<i32>(5, 5));
- c2 = e340;
- let e341: vec2<f32> = coord5;
- let e348: vec2<f32> = coord5;
+ c_2 = e340;
+ let e341: vec2<f32> = coord_5;
+ let e348: vec2<f32> = coord_5;
let e351: vec4<f32> = vec4<f32>(e348, 0.0, 6.0);
let e360: vec4<f32> = textureSampleBias(tex2D, samp, (e351.xyz / vec3<f32>(e351.w)).xy, 2.0, vec2<i32>(5, 5));
- c2 = e360;
+ c_2 = e360;
return;
}
-fn testTex2DShadow(coord6: vec2<f32>) {
- var coord7: vec2<f32>;
+fn testTex2DShadow(coord_6: vec2<f32>) {
+ var coord_7: vec2<f32>;
var d: f32;
- coord7 = coord6;
- let e17: vec2<f32> = coord7;
- let e20: vec2<f32> = coord7;
+ coord_7 = coord_6;
+ let e17: vec2<f32> = coord_7;
+ let e20: vec2<f32> = coord_7;
let e22: vec3<f32> = vec3<f32>(e20, 1.0);
let e25: f32 = textureSampleCompare(tex2DShadow, sampShadow, e22.xy, e22.z);
d = e25;
- let e26: vec2<f32> = coord7;
- let e33: vec2<f32> = coord7;
+ let e26: vec2<f32> = coord_7;
+ let e33: vec2<f32> = coord_7;
let e35: vec3<f32> = vec3<f32>(e33, 1.0);
let e42: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e35.xy, e35.z);
d = e42;
- let e43: vec2<f32> = coord7;
- let e52: vec2<f32> = coord7;
+ let e43: vec2<f32> = coord_7;
+ let e52: vec2<f32> = coord_7;
let e54: vec3<f32> = vec3<f32>(e52, 1.0);
let e63: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e54.xy, e54.z, vec2<i32>(5, 5));
d = e63;
- let e64: vec2<f32> = coord7;
- let e68: vec2<f32> = coord7;
+ let e64: vec2<f32> = coord_7;
+ let e68: vec2<f32> = coord_7;
let e70: vec3<f32> = vec3<f32>(e68, 1.0);
let e74: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e70.xy, e70.z);
d = e74;
- let e75: vec2<f32> = coord7;
- let e81: vec2<f32> = coord7;
+ let e75: vec2<f32> = coord_7;
+ let e81: vec2<f32> = coord_7;
let e83: vec3<f32> = vec3<f32>(e81, 1.0);
let e89: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e83.xy, e83.z, vec2<i32>(5, 5));
d = e89;
- let e90: vec2<f32> = coord7;
- let e95: vec2<f32> = coord7;
+ let e90: vec2<f32> = coord_7;
+ let e95: vec2<f32> = coord_7;
let e97: vec3<f32> = vec3<f32>(e95, 1.0);
let e102: f32 = textureSampleCompare(tex2DShadow, sampShadow, e97.xy, e97.z, vec2<i32>(5, 5));
d = e102;
- let e103: vec2<f32> = coord7;
- let e107: vec2<f32> = coord7;
+ let e103: vec2<f32> = coord_7;
+ let e107: vec2<f32> = coord_7;
let e110: vec4<f32> = vec4<f32>(e107, 1.0, 6.0);
let e114: vec3<f32> = (e110.xyz / vec3<f32>(e110.w));
let e117: f32 = textureSampleCompare(tex2DShadow, sampShadow, e114.xy, e114.z);
d = e117;
- let e118: vec2<f32> = coord7;
- let e126: vec2<f32> = coord7;
+ let e118: vec2<f32> = coord_7;
+ let e126: vec2<f32> = coord_7;
let e129: vec4<f32> = vec4<f32>(e126, 1.0, 6.0);
let e137: vec3<f32> = (e129.xyz / vec3<f32>(e129.w));
let e140: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e137.xy, e137.z);
d = e140;
- let e141: vec2<f32> = coord7;
- let e151: vec2<f32> = coord7;
+ let e141: vec2<f32> = coord_7;
+ let e151: vec2<f32> = coord_7;
let e154: vec4<f32> = vec4<f32>(e151, 1.0, 6.0);
let e164: vec3<f32> = (e154.xyz / vec3<f32>(e154.w));
let e167: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e164.xy, e164.z, vec2<i32>(5, 5));
d = e167;
- let e168: vec2<f32> = coord7;
- let e173: vec2<f32> = coord7;
+ let e168: vec2<f32> = coord_7;
+ let e173: vec2<f32> = coord_7;
let e176: vec4<f32> = vec4<f32>(e173, 1.0, 6.0);
let e181: vec3<f32> = (e176.xyz / vec3<f32>(e176.w));
let e184: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e181.xy, e181.z);
d = e184;
- let e185: vec2<f32> = coord7;
- let e192: vec2<f32> = coord7;
+ let e185: vec2<f32> = coord_7;
+ let e192: vec2<f32> = coord_7;
let e195: vec4<f32> = vec4<f32>(e192, 1.0, 6.0);
let e202: vec3<f32> = (e195.xyz / vec3<f32>(e195.w));
let e205: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e202.xy, e202.z, vec2<i32>(5, 5));
d = e205;
- let e206: vec2<f32> = coord7;
- let e212: vec2<f32> = coord7;
+ let e206: vec2<f32> = coord_7;
+ let e212: vec2<f32> = coord_7;
let e215: vec4<f32> = vec4<f32>(e212, 1.0, 6.0);
let e221: vec3<f32> = (e215.xyz / vec3<f32>(e215.w));
let e224: f32 = textureSampleCompare(tex2DShadow, sampShadow, e221.xy, e221.z, vec2<i32>(5, 5));
diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl
--- a/tests/out/wgsl/samplers-frag.wgsl
+++ b/tests/out/wgsl/samplers-frag.wgsl
@@ -358,217 +358,217 @@ fn testTex2DShadow(coord6: vec2<f32>) {
return;
}
-fn testTex2DArray(coord8: vec3<f32>) {
- var coord9: vec3<f32>;
- var c3: vec4<f32>;
+fn testTex2DArray(coord_8: vec3<f32>) {
+ var coord_9: vec3<f32>;
+ var c_3: vec4<f32>;
- coord9 = coord8;
- let e18: vec3<f32> = coord9;
+ coord_9 = coord_8;
+ let e18: vec3<f32> = coord_9;
let e22: vec4<f32> = textureSample(tex2DArray, samp, e18.xy, i32(e18.z));
- c3 = e22;
- let e25: vec3<f32> = coord9;
+ c_3 = e22;
+ let e25: vec3<f32> = coord_9;
let e30: vec4<f32> = textureSampleBias(tex2DArray, samp, e25.xy, i32(e25.z), 2.0);
- c3 = e30;
- let e36: vec3<f32> = coord9;
+ c_3 = e30;
+ let e36: vec3<f32> = coord_9;
let e44: vec4<f32> = textureSampleGrad(tex2DArray, samp, e36.xy, i32(e36.z), vec2<f32>(4.0), vec2<f32>(4.0));
- c3 = e44;
- let e52: vec3<f32> = coord9;
+ c_3 = e44;
+ let e52: vec3<f32> = coord_9;
let e62: vec4<f32> = textureSampleGrad(tex2DArray, samp, e52.xy, i32(e52.z), vec2<f32>(4.0), vec2<f32>(4.0), vec2<i32>(5, 5));
- c3 = e62;
- let e65: vec3<f32> = coord9;
+ c_3 = e62;
+ let e65: vec3<f32> = coord_9;
let e70: vec4<f32> = textureSampleLevel(tex2DArray, samp, e65.xy, i32(e65.z), 3.0);
- c3 = e70;
- let e75: vec3<f32> = coord9;
+ c_3 = e70;
+ let e75: vec3<f32> = coord_9;
let e82: vec4<f32> = textureSampleLevel(tex2DArray, samp, e75.xy, i32(e75.z), 3.0, vec2<i32>(5, 5));
- c3 = e82;
- let e86: vec3<f32> = coord9;
+ c_3 = e82;
+ let e86: vec3<f32> = coord_9;
let e92: vec4<f32> = textureSample(tex2DArray, samp, e86.xy, i32(e86.z), vec2<i32>(5, 5));
- c3 = e92;
- let e97: vec3<f32> = coord9;
+ c_3 = e92;
+ let e97: vec3<f32> = coord_9;
let e104: vec4<f32> = textureSampleBias(tex2DArray, samp, e97.xy, i32(e97.z), 2.0, vec2<i32>(5, 5));
- c3 = e104;
+ c_3 = e104;
return;
}
-fn testTex2DArrayShadow(coord10: vec3<f32>) {
- var coord11: vec3<f32>;
- var d1: f32;
+fn testTex2DArrayShadow(coord_10: vec3<f32>) {
+ var coord_11: vec3<f32>;
+ var d_1: f32;
- coord11 = coord10;
- let e17: vec3<f32> = coord11;
- let e20: vec3<f32> = coord11;
+ coord_11 = coord_10;
+ let e17: vec3<f32> = coord_11;
+ let e20: vec3<f32> = coord_11;
let e22: vec4<f32> = vec4<f32>(e20, 1.0);
let e27: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, e22.xy, i32(e22.z), e22.w);
- d1 = e27;
- let e28: vec3<f32> = coord11;
- let e35: vec3<f32> = coord11;
+ d_1 = e27;
+ let e28: vec3<f32> = coord_11;
+ let e35: vec3<f32> = coord_11;
let e37: vec4<f32> = vec4<f32>(e35, 1.0);
let e46: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e37.xy, i32(e37.z), e37.w);
- d1 = e46;
- let e47: vec3<f32> = coord11;
- let e56: vec3<f32> = coord11;
+ d_1 = e46;
+ let e47: vec3<f32> = coord_11;
+ let e56: vec3<f32> = coord_11;
let e58: vec4<f32> = vec4<f32>(e56, 1.0);
let e69: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e58.xy, i32(e58.z), e58.w, vec2<i32>(5, 5));
- d1 = e69;
- let e70: vec3<f32> = coord11;
- let e74: vec3<f32> = coord11;
+ d_1 = e69;
+ let e70: vec3<f32> = coord_11;
+ let e74: vec3<f32> = coord_11;
let e76: vec4<f32> = vec4<f32>(e74, 1.0);
let e82: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e76.xy, i32(e76.z), e76.w);
- d1 = e82;
- let e83: vec3<f32> = coord11;
- let e89: vec3<f32> = coord11;
+ d_1 = e82;
+ let e83: vec3<f32> = coord_11;
+ let e89: vec3<f32> = coord_11;
let e91: vec4<f32> = vec4<f32>(e89, 1.0);
let e99: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e91.xy, i32(e91.z), e91.w, vec2<i32>(5, 5));
- d1 = e99;
- let e100: vec3<f32> = coord11;
- let e105: vec3<f32> = coord11;
+ d_1 = e99;
+ let e100: vec3<f32> = coord_11;
+ let e105: vec3<f32> = coord_11;
let e107: vec4<f32> = vec4<f32>(e105, 1.0);
let e114: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, e107.xy, i32(e107.z), e107.w, vec2<i32>(5, 5));
- d1 = e114;
+ d_1 = e114;
return;
}
-fn testTexCube(coord12: vec3<f32>) {
- var coord13: vec3<f32>;
- var c4: vec4<f32>;
+fn testTexCube(coord_12: vec3<f32>) {
+ var coord_13: vec3<f32>;
+ var c_4: vec4<f32>;
- coord13 = coord12;
- let e18: vec3<f32> = coord13;
+ coord_13 = coord_12;
+ let e18: vec3<f32> = coord_13;
let e19: vec4<f32> = textureSample(texCube, samp, e18);
- c4 = e19;
- let e22: vec3<f32> = coord13;
+ c_4 = e19;
+ let e22: vec3<f32> = coord_13;
let e24: vec4<f32> = textureSampleBias(texCube, samp, e22, 2.0);
- c4 = e24;
- let e30: vec3<f32> = coord13;
+ c_4 = e24;
+ let e30: vec3<f32> = coord_13;
let e35: vec4<f32> = textureSampleGrad(texCube, samp, e30, vec3<f32>(4.0), vec3<f32>(4.0));
- c4 = e35;
- let e38: vec3<f32> = coord13;
+ c_4 = e35;
+ let e38: vec3<f32> = coord_13;
let e40: vec4<f32> = textureSampleLevel(texCube, samp, e38, 3.0);
- c4 = e40;
- let e45: vec3<f32> = coord13;
+ c_4 = e40;
+ let e45: vec3<f32> = coord_13;
let e49: vec4<f32> = textureSampleLevel(texCube, samp, e45, 3.0, vec3<i32>(5, 5, 5));
- c4 = e49;
- let e53: vec3<f32> = coord13;
+ c_4 = e49;
+ let e53: vec3<f32> = coord_13;
let e56: vec4<f32> = textureSample(texCube, samp, e53, vec3<i32>(5, 5, 5));
- c4 = e56;
- let e61: vec3<f32> = coord13;
+ c_4 = e56;
+ let e61: vec3<f32> = coord_13;
let e65: vec4<f32> = textureSampleBias(texCube, samp, e61, 2.0, vec3<i32>(5, 5, 5));
- c4 = e65;
+ c_4 = e65;
return;
}
-fn testTexCubeShadow(coord14: vec3<f32>) {
- var coord15: vec3<f32>;
- var d2: f32;
+fn testTexCubeShadow(coord_14: vec3<f32>) {
+ var coord_15: vec3<f32>;
+ var d_2: f32;
- coord15 = coord14;
- let e17: vec3<f32> = coord15;
- let e20: vec3<f32> = coord15;
+ coord_15 = coord_14;
+ let e17: vec3<f32> = coord_15;
+ let e20: vec3<f32> = coord_15;
let e22: vec4<f32> = vec4<f32>(e20, 1.0);
let e25: f32 = textureSampleCompare(texCubeShadow, sampShadow, e22.xyz, e22.w);
- d2 = e25;
- let e26: vec3<f32> = coord15;
- let e33: vec3<f32> = coord15;
+ d_2 = e25;
+ let e26: vec3<f32> = coord_15;
+ let e33: vec3<f32> = coord_15;
let e35: vec4<f32> = vec4<f32>(e33, 1.0);
let e42: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e35.xyz, e35.w);
- d2 = e42;
- let e43: vec3<f32> = coord15;
- let e47: vec3<f32> = coord15;
+ d_2 = e42;
+ let e43: vec3<f32> = coord_15;
+ let e47: vec3<f32> = coord_15;
let e49: vec4<f32> = vec4<f32>(e47, 1.0);
let e53: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e49.xyz, e49.w);
- d2 = e53;
- let e54: vec3<f32> = coord15;
- let e60: vec3<f32> = coord15;
+ d_2 = e53;
+ let e54: vec3<f32> = coord_15;
+ let e60: vec3<f32> = coord_15;
let e62: vec4<f32> = vec4<f32>(e60, 1.0);
let e68: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e62.xyz, e62.w, vec3<i32>(5, 5, 5));
- d2 = e68;
- let e69: vec3<f32> = coord15;
- let e74: vec3<f32> = coord15;
+ d_2 = e68;
+ let e69: vec3<f32> = coord_15;
+ let e74: vec3<f32> = coord_15;
let e76: vec4<f32> = vec4<f32>(e74, 1.0);
let e81: f32 = textureSampleCompare(texCubeShadow, sampShadow, e76.xyz, e76.w, vec3<i32>(5, 5, 5));
- d2 = e81;
+ d_2 = e81;
return;
}
-fn testTexCubeArray(coord16: vec4<f32>) {
- var coord17: vec4<f32>;
- var c5: vec4<f32>;
+fn testTexCubeArray(coord_16: vec4<f32>) {
+ var coord_17: vec4<f32>;
+ var c_5: vec4<f32>;
- coord17 = coord16;
- let e18: vec4<f32> = coord17;
+ coord_17 = coord_16;
+ let e18: vec4<f32> = coord_17;
let e22: vec4<f32> = textureSample(texCubeArray, samp, e18.xyz, i32(e18.w));
- c5 = e22;
- let e25: vec4<f32> = coord17;
+ c_5 = e22;
+ let e25: vec4<f32> = coord_17;
let e30: vec4<f32> = textureSampleBias(texCubeArray, samp, e25.xyz, i32(e25.w), 2.0);
- c5 = e30;
- let e36: vec4<f32> = coord17;
+ c_5 = e30;
+ let e36: vec4<f32> = coord_17;
let e44: vec4<f32> = textureSampleGrad(texCubeArray, samp, e36.xyz, i32(e36.w), vec3<f32>(4.0), vec3<f32>(4.0));
- c5 = e44;
- let e47: vec4<f32> = coord17;
+ c_5 = e44;
+ let e47: vec4<f32> = coord_17;
let e52: vec4<f32> = textureSampleLevel(texCubeArray, samp, e47.xyz, i32(e47.w), 3.0);
- c5 = e52;
- let e57: vec4<f32> = coord17;
+ c_5 = e52;
+ let e57: vec4<f32> = coord_17;
let e64: vec4<f32> = textureSampleLevel(texCubeArray, samp, e57.xyz, i32(e57.w), 3.0, vec3<i32>(5, 5, 5));
- c5 = e64;
- let e68: vec4<f32> = coord17;
+ c_5 = e64;
+ let e68: vec4<f32> = coord_17;
let e74: vec4<f32> = textureSample(texCubeArray, samp, e68.xyz, i32(e68.w), vec3<i32>(5, 5, 5));
- c5 = e74;
- let e79: vec4<f32> = coord17;
+ c_5 = e74;
+ let e79: vec4<f32> = coord_17;
let e86: vec4<f32> = textureSampleBias(texCubeArray, samp, e79.xyz, i32(e79.w), 2.0, vec3<i32>(5, 5, 5));
- c5 = e86;
+ c_5 = e86;
return;
}
-fn testTexCubeArrayShadow(coord18: vec4<f32>) {
- var coord19: vec4<f32>;
- var d3: f32;
+fn testTexCubeArrayShadow(coord_18: vec4<f32>) {
+ var coord_19: vec4<f32>;
+ var d_3: f32;
- coord19 = coord18;
- let e19: vec4<f32> = coord19;
+ coord_19 = coord_18;
+ let e19: vec4<f32> = coord_19;
let e24: f32 = textureSampleCompare(texCubeArrayShadow, sampShadow, e19.xyz, i32(e19.w), 1.0);
- d3 = e24;
+ d_3 = e24;
return;
}
-fn testTex3D(coord20: vec3<f32>) {
- var coord21: vec3<f32>;
- var c6: vec4<f32>;
+fn testTex3D(coord_20: vec3<f32>) {
+ var coord_21: vec3<f32>;
+ var c_6: vec4<f32>;
- coord21 = coord20;
- let e18: vec3<f32> = coord21;
+ coord_21 = coord_20;
+ let e18: vec3<f32> = coord_21;
let e19: vec4<f32> = textureSample(tex3D, samp, e18);
- c6 = e19;
- let e22: vec3<f32> = coord21;
+ c_6 = e19;
+ let e22: vec3<f32> = coord_21;
let e24: vec4<f32> = textureSampleBias(tex3D, samp, e22, 2.0);
- c6 = e24;
- let e30: vec3<f32> = coord21;
+ c_6 = e24;
+ let e30: vec3<f32> = coord_21;
let e35: vec4<f32> = textureSampleGrad(tex3D, samp, e30, vec3<f32>(4.0), vec3<f32>(4.0));
- c6 = e35;
- let e43: vec3<f32> = coord21;
+ c_6 = e35;
+ let e43: vec3<f32> = coord_21;
let e50: vec4<f32> = textureSampleGrad(tex3D, samp, e43, vec3<f32>(4.0), vec3<f32>(4.0), vec3<i32>(5, 5, 5));
- c6 = e50;
- let e53: vec3<f32> = coord21;
+ c_6 = e50;
+ let e53: vec3<f32> = coord_21;
let e55: vec4<f32> = textureSampleLevel(tex3D, samp, e53, 3.0);
- c6 = e55;
- let e60: vec3<f32> = coord21;
+ c_6 = e55;
+ let e60: vec3<f32> = coord_21;
let e64: vec4<f32> = textureSampleLevel(tex3D, samp, e60, 3.0, vec3<i32>(5, 5, 5));
- c6 = e64;
- let e68: vec3<f32> = coord21;
+ c_6 = e64;
+ let e68: vec3<f32> = coord_21;
let e71: vec4<f32> = textureSample(tex3D, samp, e68, vec3<i32>(5, 5, 5));
- c6 = e71;
- let e76: vec3<f32> = coord21;
+ c_6 = e71;
+ let e76: vec3<f32> = coord_21;
let e80: vec4<f32> = textureSampleBias(tex3D, samp, e76, 2.0, vec3<i32>(5, 5, 5));
- c6 = e80;
+ c_6 = e80;
return;
}
-fn main1() {
+fn main_1() {
return;
}
[[stage(fragment)]]
fn main([[location(0)]] texcoord: vec4<f32>) {
- texcoord1 = texcoord;
- main1();
+ texcoord_1 = texcoord;
+ main_1();
return;
}
diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl
--- a/tests/out/wgsl/swizzle_write-frag.wgsl
+++ b/tests/out/wgsl/swizzle_write-frag.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var x: vec3<f32> = vec3<f32>(2.0, 2.0, 2.0);
let e3: vec3<f32> = x;
diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl
--- a/tests/out/wgsl/swizzle_write-frag.wgsl
+++ b/tests/out/wgsl/swizzle_write-frag.wgsl
@@ -15,6 +15,6 @@ fn main1() {
[[stage(fragment)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -987,3 +987,45 @@ fn select() {
if name.starts_with("select_")
}
}
+
+#[test]
+fn wrong_access_mode() {
+ // The assignments to `global.i` should be forbidden, because they are in
+ // variables whose access mode is `read`, not `read_write`.
+ check_validation_error! {
+ "
+ [[block]]
+ struct Globals {
+ i: i32;
+ };
+
+ [[group(0), binding(0)]]
+ var<storage> globals: Globals;
+
+ fn store(v: i32) {
+ globals.i = v;
+ }
+ ",
+ "
+ [[block]]
+ struct Globals {
+ i: i32;
+ };
+
+ [[group(0), binding(0)]]
+ var<uniform> globals: Globals;
+
+ fn store(v: i32) {
+ globals.i = v;
+ }
+ ":
+ Err(
+ naga::valid::ValidationError::Function {
+ name,
+ error: naga::valid::FunctionError::InvalidStorePointer(_),
+ ..
+ },
+ )
+ if name == "store"
+ }
+}
|
Naga validation doesn't reject stores to read-only variables
[EDIT: I originally misidentified which rule was being broken here. The lead para has been changed.]
Naga fails to reject assignments to variables in the `storage` storage class declared with a default access mode. WGSL says that the default for such variables should be `read`, not `read_write`. For example, the following WGSL input is not rejected:
```
[[block]]
struct Globals {
i: i32;
};
[[group(0), binding(0)]]
var<storage> globals: Globals;
fn store(v: i32) {
globals.i = v;
}
```
|
2021-12-02T08:36:02Z
|
0.7
|
2021-12-02T03:07:28Z
|
33c1daeceef9268a9502df0720d69c9aa9b464da
|
[
"proc::namer::test",
"wrong_access_mode"
] |
[
"back::msl::test_error_size",
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::spv::test::parse",
"front::glsl::parser_tests::version",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::expressions",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_decimal_floats",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_hex_floats",
"front::glsl::parser_tests::function_overloading",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_switch",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_query",
"proc::test_matrix_size",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_type_inference",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_spv_inverse_hyperbolic_trig_functions",
"convert_spv_quad_vert",
"convert_spv_shadow",
"convert_glsl_folder",
"convert_wgsl",
"cube_array",
"storage1d",
"sampler1d",
"geometry",
"sample_rate_shading",
"storage_image_formats",
"image_queries",
"function_without_identifier",
"bad_texture_sample_type",
"bad_for_initializer",
"invalid_float",
"inconsistent_binding",
"invalid_integer",
"invalid_texture_sample_type",
"bad_type_cast",
"dead_code",
"bad_texture",
"invalid_structs",
"let_type_mismatch",
"invalid_arrays",
"invalid_local_vars",
"invalid_runtime_sized_arrays",
"invalid_functions",
"local_var_missing_type",
"invalid_access",
"struct_member_zero_size",
"local_var_type_mismatch",
"unknown_access",
"struct_member_zero_align",
"unknown_built_in",
"unknown_conservative_depth",
"negative_index",
"unknown_attribute",
"pointer_type_equivalence",
"unknown_shader_stage",
"unknown_scalar_type",
"unknown_local_function",
"unknown_ident",
"unknown_identifier",
"missing_bindings",
"zero_array_stride",
"postfix_pointers",
"unknown_type",
"select",
"unknown_storage_format",
"valid_access",
"unknown_storage_class",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,549
|
gfx-rs__naga-1549
|
[
"1546"
] |
7fd172515dd6348fd9b35b81366686c62e41d69c
|
diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs
--- a/src/back/wgsl/mod.rs
+++ b/src/back/wgsl/mod.rs
@@ -1,4 +1,3 @@
-mod keywords;
mod writer;
use thiserror::Error;
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -72,8 +72,12 @@ impl<W: Write> Writer<W> {
fn reset(&mut self, module: &Module) {
self.names.clear();
- self.namer
- .reset(module, super::keywords::RESERVED, &[], &mut self.names);
+ self.namer.reset(
+ module,
+ crate::keywords::wgsl::RESERVED,
+ &[],
+ &mut self.names,
+ );
self.named_expressions.clear();
self.ep_results.clear();
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -169,6 +169,7 @@ pub enum Error<'a> {
Pointer(&'static str, Span),
NotPointer(Span),
NotReference(&'static str, Span),
+ ReservedKeyword(Span),
Other,
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -431,6 +432,11 @@ impl<'a> Error<'a> {
labels: vec![(span.clone(), "expression is a pointer".into())],
notes: vec![],
},
+ Error::ReservedKeyword(ref name_span) => ParseError {
+ message: format!("Name `{}` is a reserved keyword", &source[name_span.clone()]),
+ labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())],
+ notes: vec![],
+ },
Error::Other => ParseError {
message: "other error".to_string(),
labels: vec![],
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2079,15 +2085,18 @@ impl Parser {
// Only set span if it's a named constant. Otherwise, the enclosing Expression should have
// the span.
- let span = NagaSpan::from(self.pop_scope(lexer));
+ let span = self.pop_scope(lexer);
let handle = if let Some(name) = register_name {
+ if crate::keywords::wgsl::RESERVED.contains(&name) {
+ return Err(Error::ReservedKeyword(span));
+ }
const_arena.append(
crate::Constant {
name: Some(name.to_string()),
specialization: None,
inner,
},
- span,
+ NagaSpan::from(span),
)
} else {
const_arena.fetch_or_append(
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2701,15 +2710,17 @@ impl Parser {
}
let bind_span = self.pop_scope(lexer);
-
- let name = match lexer.next() {
- (Token::Word(word), _) => word,
+ let (name, span) = match lexer.next() {
+ (Token::Word(word), span) => (word, span),
(Token::Paren('}'), _) => {
let span = Layouter::round_up(alignment, offset);
return Ok((members, span));
}
other => return Err(Error::Unexpected(other, ExpectedToken::FieldName)),
};
+ if crate::keywords::wgsl::RESERVED.contains(&name) {
+ return Err(Error::ReservedKeyword(span));
+ }
lexer.expect(Token::Separator(':'))?;
let (ty, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?;
lexer.expect(Token::Separator(';'))?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3245,6 +3256,9 @@ impl Parser {
let _ = lexer.next();
emitter.start(context.expressions);
let (name, name_span) = lexer.next_ident_with_span()?;
+ if crate::keywords::wgsl::RESERVED.contains(&name) {
+ return Err(Error::ReservedKeyword(name_span));
+ }
let given_ty = if lexer.skip(Token::Separator(':')) {
let (ty, _access) = self.parse_type_decl(
lexer,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3300,6 +3314,9 @@ impl Parser {
}
let (name, name_span) = lexer.next_ident_with_span()?;
+ if crate::keywords::wgsl::RESERVED.contains(&name) {
+ return Err(Error::ReservedKeyword(name_span));
+ }
let given_ty = if lexer.skip(Token::Separator(':')) {
let (ty, _access) = self.parse_type_decl(
lexer,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3810,7 +3827,10 @@ impl Parser {
self.push_scope(Scope::FunctionDecl, lexer);
// read function name
let mut lookup_ident = FastHashMap::default();
- let fun_name = lexer.next_ident()?;
+ let (fun_name, span) = lexer.next_ident_with_span()?;
+ if crate::keywords::wgsl::RESERVED.contains(&fun_name) {
+ return Err(Error::ReservedKeyword(span));
+ }
// populate initial expressions
let mut expressions = Arena::new();
for (&name, expression) in lookup_global_expression.iter() {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3845,6 +3865,9 @@ impl Parser {
let mut binding = self.parse_varying_binding(lexer)?;
let (param_name, param_name_span, param_type, _access) =
self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?;
+ if crate::keywords::wgsl::RESERVED.contains(¶m_name) {
+ return Err(Error::ReservedKeyword(param_name_span));
+ }
let param_index = arguments.len() as u32;
let expression = expressions.append(
crate::Expression::FunctionArgument(param_index),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4016,7 +4039,10 @@ impl Parser {
match lexer.next() {
(Token::Separator(';'), _) => {}
(Token::Word("struct"), _) => {
- let name = lexer.next_ident()?;
+ let (name, span) = lexer.next_ident_with_span()?;
+ if crate::keywords::wgsl::RESERVED.contains(&name) {
+ return Err(Error::ReservedKeyword(span));
+ }
let (members, span) =
self.parse_struct_body(lexer, &mut module.types, &mut module.constants)?;
let type_span = NagaSpan::from(lexer.span_from(start));
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4048,6 +4074,9 @@ impl Parser {
}
(Token::Word("let"), _) => {
let (name, name_span) = lexer.next_ident_with_span()?;
+ if crate::keywords::wgsl::RESERVED.contains(&name) {
+ return Err(Error::ReservedKeyword(name_span));
+ }
let given_ty = if lexer.skip(Token::Separator(':')) {
let (ty, _access) = self.parse_type_decl(
lexer,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4093,6 +4122,9 @@ impl Parser {
(Token::Word("var"), _) => {
let pvar =
self.parse_variable_decl(lexer, &mut module.types, &mut module.constants)?;
+ if crate::keywords::wgsl::RESERVED.contains(&pvar.name) {
+ return Err(Error::ReservedKeyword(pvar.name_span));
+ }
let var_handle = module.global_variables.append(
crate::GlobalVariable {
name: Some(pvar.name.to_owned()),
diff --git /dev/null b/src/keywords/mod.rs
new file mode 100644
--- /dev/null
+++ b/src/keywords/mod.rs
@@ -0,0 +1,2 @@
+#[cfg(any(feature = "wgsl-in", feature = "wgsl-out"))]
+pub mod wgsl;
diff --git a/src/back/wgsl/keywords.rs b/src/keywords/wgsl.rs
--- a/src/back/wgsl/keywords.rs
+++ b/src/keywords/wgsl.rs
@@ -1,134 +1,134 @@
-// https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary
-pub const RESERVED: &[&str] = &[
- // type-defining keywords
- "array",
- "atomic",
- "bool",
- "float32",
- "int32",
- "mat2x2",
- "mat2x3",
- "mat2x4",
- "mat3x2",
- "mat3x3",
- "mat3x4",
- "mat4x2",
- "mat4x3",
- "mat4x4",
- "pointer",
- "sampler",
- "sampler_comparison",
- "struct",
- "texture_1d",
- "texture_2d",
- "texture_2d_array",
- "texture_3d",
- "texture_cube",
- "texture_cube_array",
- "texture_multisampled_2d",
- "texture_storage_1d",
- "texture_storage_2d",
- "texture_storage_2d_array",
- "texture_storage_3d",
- "texture_depth_2d",
- "texture_depth_2d_array",
- "texture_depth_cube",
- "texture_depth_cube_array",
- "texture_depth_multisampled_2d",
- "uint32",
- "vec2",
- "vec3",
- "vec4",
- // other keywords
- "bitcast",
- "block",
- "break",
- "case",
- "continue",
- "continuing",
- "default",
- "discard",
- "else",
- "else_if",
- "enable",
- "fallthrough",
- "false",
- "fn",
- "for",
- "function",
- "if",
- "let",
- "loop",
- "private",
- "read",
- "read_write",
- "return",
- "storage",
- "switch",
- "true",
- "type",
- "uniform",
- "var",
- "workgroup",
- "write",
- // image format keywords
- "r8unorm",
- "r8snorm",
- "r8uint",
- "r8sint",
- "r16uint",
- "r16sint",
- "r16float",
- "rg8unorm",
- "rg8snorm",
- "rg8uint",
- "rg8sint",
- "r32uint",
- "r32sint",
- "r32float",
- "rg16uint",
- "rg16sint",
- "rg16float",
- "rgba8unorm",
- "rgba8unorm_srgb",
- "rgba8snorm",
- "rgba8uint",
- "rgba8sint",
- "bgra8unorm",
- "bgra8unorm_srgb",
- "rgb10a2unorm",
- "rg11b10float",
- "rg32uint",
- "rg32sint",
- "rg32float",
- "rgba16uint",
- "rgba16sint",
- "rgba16float",
- "rgba32uint",
- "rgba32sint",
- "rgba32float",
- // reserved keywords
- "asm",
- "bf16",
- "const",
- "do",
- "enum",
- "f16",
- "f64",
- "handle",
- "i8",
- "i16",
- "i64",
- "mat",
- "premerge",
- "regardless",
- "typedef",
- "u8",
- "u16",
- "u64",
- "unless",
- "using",
- "vec",
- "void",
- "while",
-];
+// https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary
+pub const RESERVED: &[&str] = &[
+ // type-defining keywords
+ "array",
+ "atomic",
+ "bool",
+ "float32",
+ "int32",
+ "mat2x2",
+ "mat2x3",
+ "mat2x4",
+ "mat3x2",
+ "mat3x3",
+ "mat3x4",
+ "mat4x2",
+ "mat4x3",
+ "mat4x4",
+ "pointer",
+ "sampler",
+ "sampler_comparison",
+ "struct",
+ "texture_1d",
+ "texture_2d",
+ "texture_2d_array",
+ "texture_3d",
+ "texture_cube",
+ "texture_cube_array",
+ "texture_multisampled_2d",
+ "texture_storage_1d",
+ "texture_storage_2d",
+ "texture_storage_2d_array",
+ "texture_storage_3d",
+ "texture_depth_2d",
+ "texture_depth_2d_array",
+ "texture_depth_cube",
+ "texture_depth_cube_array",
+ "texture_depth_multisampled_2d",
+ "uint32",
+ "vec2",
+ "vec3",
+ "vec4",
+ // other keywords
+ "bitcast",
+ "block",
+ "break",
+ "case",
+ "continue",
+ "continuing",
+ "default",
+ "discard",
+ "else",
+ "else_if",
+ "enable",
+ "fallthrough",
+ "false",
+ "fn",
+ "for",
+ "function",
+ "if",
+ "let",
+ "loop",
+ "private",
+ "read",
+ "read_write",
+ "return",
+ "storage",
+ "switch",
+ "true",
+ "type",
+ "uniform",
+ "var",
+ "workgroup",
+ "write",
+ // image format keywords
+ "r8unorm",
+ "r8snorm",
+ "r8uint",
+ "r8sint",
+ "r16uint",
+ "r16sint",
+ "r16float",
+ "rg8unorm",
+ "rg8snorm",
+ "rg8uint",
+ "rg8sint",
+ "r32uint",
+ "r32sint",
+ "r32float",
+ "rg16uint",
+ "rg16sint",
+ "rg16float",
+ "rgba8unorm",
+ "rgba8unorm_srgb",
+ "rgba8snorm",
+ "rgba8uint",
+ "rgba8sint",
+ "bgra8unorm",
+ "bgra8unorm_srgb",
+ "rgb10a2unorm",
+ "rg11b10float",
+ "rg32uint",
+ "rg32sint",
+ "rg32float",
+ "rgba16uint",
+ "rgba16sint",
+ "rgba16float",
+ "rgba32uint",
+ "rgba32sint",
+ "rgba32float",
+ // reserved keywords
+ "asm",
+ "bf16",
+ "const",
+ "do",
+ "enum",
+ "f16",
+ "f64",
+ "handle",
+ "i8",
+ "i16",
+ "i64",
+ "mat",
+ "premerge",
+ "regardless",
+ "typedef",
+ "u8",
+ "u16",
+ "u64",
+ "unless",
+ "using",
+ "vec",
+ "void",
+ "while",
+];
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -209,6 +209,7 @@ mod arena;
pub mod back;
mod block;
pub mod front;
+pub mod keywords;
pub mod proc;
mod span;
pub mod valid;
|
diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl
--- a/tests/in/access.wgsl
+++ b/tests/in/access.wgsl
@@ -30,7 +30,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4<f32> {
let a = bar.data[arrayLength(&bar.data) - 2u];
// test pointer types
- let pointer: ptr<storage, i32, read_write> = &bar.data[0];
+ let data_pointer: ptr<storage, i32, read_write> = &bar.data[0];
let foo_value = read_from_private(&foo);
// test storage stores
diff --git a/tests/in/pointers.wgsl b/tests/in/pointers.wgsl
--- a/tests/in/pointers.wgsl
+++ b/tests/in/pointers.wgsl
@@ -6,7 +6,7 @@ fn f() {
[[block]]
struct DynamicArray {
- array: array<u32>;
+ arr: array<u32>;
};
[[group(0), binding(0)]]
diff --git a/tests/in/pointers.wgsl b/tests/in/pointers.wgsl
--- a/tests/in/pointers.wgsl
+++ b/tests/in/pointers.wgsl
@@ -15,12 +15,12 @@ var<storage, read_write> dynamic_array: DynamicArray;
fn index_unsized(i: i32, v: u32) {
let p: ptr<storage, DynamicArray, read_write> = &dynamic_array;
- let val = (*p).array[i];
- (*p).array[i] = val + v;
+ let val = (*p).arr[i];
+ (*p).arr[i] = val + v;
}
fn index_dynamic_array(i: i32, v: u32) {
- let p: ptr<storage, array<u32>, read_write> = &dynamic_array.array;
+ let p: ptr<storage, array<u32>, read_write> = &dynamic_array.arr;
let val = (*p)[i];
(*p)[i] = val + v;
diff --git a/tests/out/spv/pointers.spvasm b/tests/out/spv/pointers.spvasm
--- a/tests/out/spv/pointers.spvasm
+++ b/tests/out/spv/pointers.spvasm
@@ -8,7 +8,7 @@ OpExtension "SPV_KHR_storage_buffer_storage_class"
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpSource GLSL 450
-OpMemberName %8 0 "array"
+OpMemberName %8 0 "arr"
OpName %8 "DynamicArray"
OpName %11 "dynamic_array"
OpName %12 "v"
diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl
--- a/tests/out/wgsl/access.wgsl
+++ b/tests/out/wgsl/access.wgsl
@@ -25,7 +25,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4<f32> {
let arr: array<vec2<u32>,2> = bar.arr;
let b: f32 = bar.matrix[3][0];
let a: i32 = bar.data[(arrayLength((&bar.data)) - 2u)];
- let pointer_: ptr<storage, i32, read_write> = (&bar.data[0]);
+ let data_pointer: ptr<storage, i32, read_write> = (&bar.data[0]);
let e25: f32 = read_from_private((&foo_1));
bar.matrix[1][2] = 1.0;
bar.matrix = mat4x4<f32>(vec4<f32>(0.0), vec4<f32>(1.0), vec4<f32>(2.0), vec4<f32>(3.0));
diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl
--- a/tests/out/wgsl/pointers.wgsl
+++ b/tests/out/wgsl/pointers.wgsl
@@ -1,6 +1,6 @@
[[block]]
struct DynamicArray {
- array_: [[stride(4)]] array<u32>;
+ arr: [[stride(4)]] array<u32>;
};
[[group(0), binding(0)]]
diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl
--- a/tests/out/wgsl/pointers.wgsl
+++ b/tests/out/wgsl/pointers.wgsl
@@ -15,13 +15,13 @@ fn f() {
}
fn index_unsized(i: i32, v_1: u32) {
- let val: u32 = dynamic_array.array_[i];
- dynamic_array.array_[i] = (val + v_1);
+ let val: u32 = dynamic_array.arr[i];
+ dynamic_array.arr[i] = (val + v_1);
return;
}
fn index_dynamic_array(i_1: i32, v_2: u32) {
- let p: ptr<storage, array<u32>, read_write> = (&dynamic_array.array_);
+ let p: ptr<storage, array<u32>, read_write> = (&dynamic_array.arr);
let val_1: u32 = (*p)[i_1];
(*p)[i_1] = (val_1 + v_2);
return;
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -114,18 +114,18 @@ fn negative_index() {
fn bad_texture() {
check(
r#"
- [[group(0), binding(0)]] var sampler : sampler;
+ [[group(0), binding(0)]] var sampler1 : sampler;
[[stage(fragment)]]
fn main() -> [[location(0)]] vec4<f32> {
let a = 3;
- return textureSample(a, sampler, vec2<f32>(0.0));
+ return textureSample(a, sampler1, vec2<f32>(0.0));
}
"#,
r#"error: expected an image, but found 'a' which is not an image
┌─ wgsl:7:38
│
-7 │ return textureSample(a, sampler, vec2<f32>(0.0));
+7 │ return textureSample(a, sampler1, vec2<f32>(0.0));
│ ^ not an image
"#,
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -154,12 +154,12 @@ fn bad_type_cast() {
fn bad_texture_sample_type() {
check(
r#"
- [[group(0), binding(0)]] var sampler : sampler;
+ [[group(0), binding(0)]] var sampler1 : sampler;
[[group(0), binding(1)]] var texture : texture_2d<bool>;
[[stage(fragment)]]
fn main() -> [[location(0)]] vec4<f32> {
- return textureSample(texture, sampler, vec2<f32>(0.0));
+ return textureSample(texture, sampler1, vec2<f32>(0.0));
}
"#,
r#"error: texture sample type must be one of f32, i32 or u32, but found bool
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -327,13 +327,13 @@ fn unknown_type() {
fn unknown_storage_format() {
check(
r#"
- let storage: texture_storage_1d<rgba>;
+ let storage1: texture_storage_1d<rgba>;
"#,
r#"error: unknown storage format: 'rgba'
- ┌─ wgsl:2:45
+ ┌─ wgsl:2:46
│
-2 │ let storage: texture_storage_1d<rgba>;
- │ ^^^^ unknown storage format
+2 │ let storage1: texture_storage_1d<rgba>;
+ │ ^^^^ unknown storage format
"#,
);
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -531,6 +531,114 @@ fn postfix_pointers() {
);
}
+#[test]
+fn reserved_keyword() {
+ // global var
+ check(
+ r#"
+ var bool: bool = true;
+ "#,
+ r###"error: Name ` bool: bool = true;` is a reserved keyword
+ ┌─ wgsl:2:16
+ │
+2 │ var bool: bool = true;
+ │ ^^^^^^^^^^^^^^^^^^^ definition of ` bool: bool = true;`
+
+"###,
+ );
+
+ // global constant
+ check(
+ r#"
+ let break: bool = true;
+ fn foo() {
+ var foo = break;
+ }
+ "#,
+ r###"error: Name `break` is a reserved keyword
+ ┌─ wgsl:2:17
+ │
+2 │ let break: bool = true;
+ │ ^^^^^ definition of `break`
+
+"###,
+ );
+
+ // local let
+ check(
+ r#"
+ fn foo() {
+ let atomic: f32 = 1.0;
+ }
+ "#,
+ r###"error: Name `atomic` is a reserved keyword
+ ┌─ wgsl:3:21
+ │
+3 │ let atomic: f32 = 1.0;
+ │ ^^^^^^ definition of `atomic`
+
+"###,
+ );
+
+ // local var
+ check(
+ r#"
+ fn foo() {
+ var sampler: f32 = 1.0;
+ }
+ "#,
+ r###"error: Name `sampler` is a reserved keyword
+ ┌─ wgsl:3:21
+ │
+3 │ var sampler: f32 = 1.0;
+ │ ^^^^^^^ definition of `sampler`
+
+"###,
+ );
+
+ // fn name
+ check(
+ r#"
+ fn break() {}
+ "#,
+ r###"error: Name `break` is a reserved keyword
+ ┌─ wgsl:2:16
+ │
+2 │ fn break() {}
+ │ ^^^^^ definition of `break`
+
+"###,
+ );
+
+ // struct
+ check(
+ r#"
+ struct array {};
+ "#,
+ r###"error: Name `array` is a reserved keyword
+ ┌─ wgsl:2:20
+ │
+2 │ struct array {};
+ │ ^^^^^ definition of `array`
+
+"###,
+ );
+
+ // struct member
+ check(
+ r#"
+ struct Foo { sampler: f32; };
+ "#,
+ r###"error: Name `sampler` is a reserved keyword
+ ┌─ wgsl:2:26
+ │
+2 │ struct Foo { sampler: f32; };
+ │ ^^^^^^^ definition of `sampler`
+
+"###,
+ );
+}
+
macro_rules! check_validation_error {
// We want to support an optional guard expression after the pattern, so
// that we can check values we can't match against, like strings.
|
[wgsl-in] naga should not accept keywords as identifiers
The code `let sampler = 0;` is accepted by naga, but according to the spec, an identifier [must not have the same spelling as a keyword or as a reserved word](https://gpuweb.github.io/gpuweb/wgsl/#identifiers), and `sampler` [is a keyword](https://gpuweb.github.io/gpuweb/wgsl/#keyword-summary).
|
2021-11-24T21:29:25Z
|
0.7
|
2021-11-24T21:41:31Z
|
33c1daeceef9268a9502df0720d69c9aa9b464da
|
[
"reserved_keyword"
] |
[
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::expressions",
"front::spv::test::parse",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_decimal_floats",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_hex_floats",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_decimal_ints",
"front::glsl::parser_tests::control_flow",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_postfix",
"front::glsl::parser_tests::declarations",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_switch",
"proc::namer::test",
"proc::test_matrix_size",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::functions",
"convert_spv_inverse_hyperbolic_trig_functions",
"convert_spv_empty_global_name",
"convert_spv_quad_vert",
"convert_spv_shadow",
"convert_wgsl",
"convert_glsl_folder",
"sampler1d",
"cube_array",
"storage1d",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"bad_texture_sample_type",
"inconsistent_binding",
"invalid_float",
"invalid_integer",
"invalid_texture_sample_type",
"bad_type_cast",
"bad_texture",
"dead_code",
"invalid_structs",
"last_case_falltrough",
"let_type_mismatch",
"invalid_runtime_sized_arrays",
"local_var_missing_type",
"invalid_access",
"invalid_arrays",
"invalid_local_vars",
"missing_default_case",
"struct_member_zero_size",
"invalid_functions",
"local_var_type_mismatch",
"missing_bindings",
"unknown_attribute",
"struct_member_zero_align",
"unknown_access",
"negative_index",
"pointer_type_equivalence",
"unknown_built_in",
"unknown_conservative_depth",
"unknown_shader_stage",
"unknown_storage_format",
"unknown_storage_class",
"unknown_local_function",
"unknown_type",
"unknown_identifier",
"unknown_scalar_type",
"unknown_ident",
"postfix_pointers",
"zero_array_stride",
"wrong_access_mode",
"select",
"valid_access",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,534
|
gfx-rs__naga-1534
|
[
"1533"
] |
1dcde48d09245b81cc08b15b13a14281f75f7a0e
|
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -184,6 +184,21 @@ impl super::TypeInner {
}
}
+impl super::StorageClass {
+ pub fn access(self) -> crate::StorageAccess {
+ use crate::StorageAccess as Sa;
+ match self {
+ crate::StorageClass::Function
+ | crate::StorageClass::Private
+ | crate::StorageClass::WorkGroup => Sa::LOAD | Sa::STORE,
+ crate::StorageClass::Uniform => Sa::LOAD,
+ crate::StorageClass::Storage { access } => access,
+ crate::StorageClass::Handle => Sa::LOAD,
+ crate::StorageClass::PushConstant => Sa::LOAD,
+ }
+ }
+}
+
impl super::MathFunction {
pub fn argument_count(&self) -> usize {
match *self {
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -606,10 +606,12 @@ impl super::Validator {
}
_ => {}
}
- let good = match *context
+
+ let pointer_ty = context
.resolve_pointer_type(pointer)
- .map_err(|e| e.with_span())?
- {
+ .map_err(|e| e.with_span())?;
+
+ let good = match *pointer_ty {
Ti::Pointer { base, class: _ } => match context.types[base].inner {
Ti::Atomic { kind, width } => *value_ty == Ti::Scalar { kind, width },
ref other => value_ty == other,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -634,6 +636,16 @@ impl super::Validator {
.with_handle(pointer, context.expressions)
.with_handle(value, context.expressions));
}
+
+ if let Some(class) = pointer_ty.pointer_class() {
+ if !class.access().contains(crate::StorageAccess::STORE) {
+ return Err(FunctionError::InvalidStorePointer(pointer)
+ .with_span_static(
+ context.expressions.get_span(pointer),
+ "writing to this location is not permitted",
+ ));
+ }
+ }
}
S::ImageStore {
image,
|
diff --git a/tests/in/bounds-check-zero.wgsl b/tests/in/bounds-check-zero.wgsl
--- a/tests/in/bounds-check-zero.wgsl
+++ b/tests/in/bounds-check-zero.wgsl
@@ -7,7 +7,7 @@ struct Globals {
m: mat3x4<f32>;
};
-[[group(0), binding(0)]] var<storage> globals: Globals;
+[[group(0), binding(0)]] var<storage, read_write> globals: Globals;
fn index_array(i: i32) -> f32 {
return globals.a[i];
diff --git a/tests/out/spv/bounds-check-zero.spvasm b/tests/out/spv/bounds-check-zero.spvasm
--- a/tests/out/spv/bounds-check-zero.spvasm
+++ b/tests/out/spv/bounds-check-zero.spvasm
@@ -14,7 +14,6 @@ OpMemberDecorate %9 1 Offset 48
OpMemberDecorate %9 2 Offset 64
OpMemberDecorate %9 2 ColMajor
OpMemberDecorate %9 2 MatrixStride 16
-OpDecorate %10 NonWritable
OpDecorate %10 DescriptorSet 0
OpDecorate %10 Binding 0
%2 = OpTypeVoid
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -1029,3 +1029,45 @@ fn missing_default_case() {
)
}
}
+
+#[test]
+fn wrong_access_mode() {
+ // The assignments to `global.i` should be forbidden, because they are in
+ // variables whose access mode is `read`, not `read_write`.
+ check_validation_error! {
+ "
+ [[block]]
+ struct Globals {
+ i: i32;
+ };
+
+ [[group(0), binding(0)]]
+ var<storage> globals: Globals;
+
+ fn store(v: i32) {
+ globals.i = v;
+ }
+ ",
+ "
+ [[block]]
+ struct Globals {
+ i: i32;
+ };
+
+ [[group(0), binding(0)]]
+ var<uniform> globals: Globals;
+
+ fn store(v: i32) {
+ globals.i = v;
+ }
+ ":
+ Err(
+ naga::valid::ValidationError::Function {
+ name,
+ error: naga::valid::FunctionError::InvalidStorePointer(_),
+ ..
+ },
+ )
+ if name == "store"
+ }
+}
|
Naga validation doesn't reject stores to read-only variables
[EDIT: I originally misidentified which rule was being broken here. The lead para has been changed.]
Naga fails to reject assignments to variables in the `storage` storage class declared with a default access mode. WGSL says that the default for such variables should be `read`, not `read_write`. For example, the following WGSL input is not rejected:
```
[[block]]
struct Globals {
i: i32;
};
[[group(0), binding(0)]]
var<storage> globals: Globals;
fn store(v: i32) {
globals.i = v;
}
```
|
2021-11-16T14:47:52Z
|
0.7
|
2021-12-02T03:20:01Z
|
33c1daeceef9268a9502df0720d69c9aa9b464da
|
[
"wrong_access_mode"
] |
[
"back::msl::test_error_size",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"back::msl::writer::test_stack_size",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::swizzles",
"front::spv::test::parse",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_decimal_floats",
"front::wgsl::tests::parse_hex_ints",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_hex_floats",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_pointers",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::declarations",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::namer::test",
"proc::test_matrix_size",
"front::wgsl::tests::parse_types",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_struct",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_spv_inverse_hyperbolic_trig_functions",
"convert_spv_quad_vert",
"convert_spv_shadow",
"convert_spv_empty_global_name",
"convert_glsl_folder",
"convert_wgsl",
"sampler1d",
"storage1d",
"cube_array",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"inconsistent_binding",
"bad_texture_sample_type",
"invalid_float",
"invalid_integer",
"bad_type_cast",
"invalid_structs",
"let_type_mismatch",
"last_case_falltrough",
"local_var_missing_type",
"invalid_local_vars",
"bad_texture",
"invalid_texture_sample_type",
"dead_code",
"invalid_arrays",
"invalid_functions",
"invalid_runtime_sized_arrays",
"invalid_access",
"struct_member_zero_size",
"struct_member_zero_align",
"local_var_type_mismatch",
"unknown_attribute",
"unknown_conservative_depth",
"negative_index",
"unknown_access",
"unknown_built_in",
"missing_default_case",
"missing_bindings",
"unknown_ident",
"unknown_shader_stage",
"unknown_storage_format",
"unknown_storage_class",
"pointer_type_equivalence",
"unknown_scalar_type",
"unknown_type",
"unknown_identifier",
"postfix_pointers",
"zero_array_stride",
"unknown_local_function",
"select",
"valid_access",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,510
|
gfx-rs__naga-1510
|
[
"1508"
] |
28c45321e53c3dac8a613e2402d0e336d886ad49
|
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -2,6 +2,7 @@ use crate::{arena::Handle, FastHashMap, FastHashSet};
use std::borrow::Cow;
pub type EntryPointIndex = u16;
+const SEPARATOR: char = '_';
#[derive(Debug, Eq, Hash, PartialEq)]
pub enum NameKey {
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -30,23 +31,35 @@ pub struct Namer {
impl Namer {
/// Return a form of `string` suitable for use as the base of an identifier.
///
- /// Retain only alphanumeric and `_` characters. Drop leading digits. Avoid
- /// prefixes in [`Namer::reserved_prefixes`].
+ /// - Drop leading digits.
+ /// - Retain only alphanumeric and `_` characters.
+ /// - Avoid prefixes in [`Namer::reserved_prefixes`].
+ ///
+ /// The return value is a valid identifier prefix in all of Naga's output languages,
+ /// and it never ends with a `SEPARATOR` character.
+ /// It is used as a key into the unique table.
fn sanitize<'s>(&self, string: &'s str) -> Cow<'s, str> {
- let string = string.trim_start_matches(|c: char| c.is_numeric() || c == '_');
+ let string = string
+ .trim_start_matches(|c: char| c.is_numeric())
+ .trim_end_matches(SEPARATOR);
- let base = if string
- .chars()
- .all(|c: char| c.is_ascii_alphanumeric() || c == '_')
+ let base = if !string.is_empty()
+ && string
+ .chars()
+ .all(|c: char| c.is_ascii_alphanumeric() || c == '_')
{
Cow::Borrowed(string)
} else {
- Cow::Owned(
- string
- .chars()
- .filter(|&c| c.is_ascii_alphanumeric() || c == '_')
- .collect::<String>(),
- )
+ let mut filtered = string
+ .chars()
+ .filter(|&c| c.is_ascii_alphanumeric() || c == '_')
+ .collect::<String>();
+ let stripped_len = filtered.trim_end_matches(SEPARATOR).len();
+ filtered.truncate(stripped_len);
+ if filtered.is_empty() {
+ filtered.push_str("unnamed");
+ }
+ Cow::Owned(filtered)
};
for prefix in &self.reserved_prefixes {
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -69,14 +82,10 @@ impl Namer {
/// Guarantee uniqueness by applying a numeric suffix when necessary. If `label_raw`
/// itself ends with digits, separate them from the suffix with an underscore.
pub fn call(&mut self, label_raw: &str) -> String {
- use std::fmt::Write; // for write!-ing to Strings
+ use std::fmt::Write as _; // for write!-ing to Strings
let base = self.sanitize(label_raw);
- let separator = if base.ends_with(char::is_numeric) {
- "_"
- } else {
- ""
- };
+ debug_assert!(!base.is_empty() && !base.ends_with(SEPARATOR));
// This would seem to be a natural place to use `HashMap::entry`. However, `entry`
// requires an owned key, and we'd like to avoid heap-allocating strings we're
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -88,28 +97,18 @@ impl Namer {
*count += 1;
// Add the suffix. This may fit in base's existing allocation.
let mut suffixed = base.into_owned();
- write!(&mut suffixed, "{}{}", separator, *count).unwrap();
+ write!(&mut suffixed, "{}{}", SEPARATOR, *count).unwrap();
suffixed
}
None => {
- let mut count = 0;
- let mut suffixed = Cow::Borrowed(base.as_ref());
- while self.keywords.contains(suffixed.as_ref()) {
- count += 1;
- // Try to reuse suffixed's allocation.
- let mut buf = suffixed.into_owned();
- buf.clear();
- write!(&mut buf, "{}{}{}", base, separator, count).unwrap();
- suffixed = Cow::Owned(buf);
+ let mut suffixed = base.to_string();
+ if base.ends_with(char::is_numeric) || self.keywords.contains(base.as_ref()) {
+ suffixed.push(SEPARATOR);
}
- // Produce our return value, which must be an owned string. This allocates
- // only if we haven't already done so earlier.
- let suffixed = suffixed.into_owned();
-
+ debug_assert!(!self.keywords.contains(&suffixed));
// `self.unique` wants to own its keys. This allocates only if we haven't
// already done so earlier.
- self.unique.insert(base.into_owned(), count);
-
+ self.unique.insert(base.into_owned(), 0);
suffixed
}
}
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -117,13 +116,7 @@ impl Namer {
pub fn call_or(&mut self, label: &Option<String>, fallback: &str) -> String {
self.call(match *label {
- Some(ref name) => {
- if name.trim().is_empty() {
- fallback
- } else {
- name
- }
- }
+ Some(ref name) => name,
None => fallback,
})
}
|
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -258,3 +251,11 @@ impl Namer {
}
}
}
+
+#[test]
+fn test() {
+ let mut namer = Namer::default();
+ assert_eq!(namer.call("x"), "x");
+ assert_eq!(namer.call("x"), "x_1");
+ assert_eq!(namer.call("x1"), "x1_");
+}
diff --git a/tests/out/glsl/access.atomics.Compute.glsl b/tests/out/glsl/access.atomics.Compute.glsl
--- a/tests/out/glsl/access.atomics.Compute.glsl
+++ b/tests/out/glsl/access.atomics.Compute.glsl
@@ -13,8 +13,8 @@ layout(std430) buffer Bar_block_0Cs {
} _group_0_binding_0;
-float read_from_private(inout float foo2) {
- float _e2 = foo2;
+float read_from_private(inout float foo_2) {
+ float _e2 = foo_2;
return _e2;
}
diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl
--- a/tests/out/glsl/access.foo.Vertex.glsl
+++ b/tests/out/glsl/access.foo.Vertex.glsl
@@ -11,22 +11,22 @@ layout(std430) buffer Bar_block_0Vs {
} _group_0_binding_0;
-float read_from_private(inout float foo2) {
- float _e2 = foo2;
+float read_from_private(inout float foo_2) {
+ float _e2 = foo_2;
return _e2;
}
void main() {
uint vi = uint(gl_VertexID);
- float foo1 = 0.0;
+ float foo_1 = 0.0;
int c[5];
- float baz = foo1;
- foo1 = 1.0;
+ float baz = foo_1;
+ foo_1 = 1.0;
mat4x4 matrix = _group_0_binding_0.matrix;
uvec2 arr[2] = _group_0_binding_0.arr;
float b = _group_0_binding_0.matrix[3][0];
int a = _group_0_binding_0.data[(uint(_group_0_binding_0.data.length()) - 2u)];
- float _e25 = read_from_private(foo1);
+ float _e25 = read_from_private(foo_1);
_group_0_binding_0.matrix[1][2] = 1.0;
_group_0_binding_0.matrix = mat4x4(vec4(0.0), vec4(1.0), vec4(2.0), vec4(3.0));
_group_0_binding_0.arr = uvec2[2](uvec2(0u), uvec2(1u));
diff --git a/tests/out/glsl/bits.main.Compute.glsl b/tests/out/glsl/bits.main.Compute.glsl
--- a/tests/out/glsl/bits.main.Compute.glsl
+++ b/tests/out/glsl/bits.main.Compute.glsl
@@ -8,83 +8,83 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
void main() {
int i = 0;
- ivec2 i2 = ivec2(0, 0);
- ivec3 i3 = ivec3(0, 0, 0);
- ivec4 i4 = ivec4(0, 0, 0, 0);
+ ivec2 i2_ = ivec2(0, 0);
+ ivec3 i3_ = ivec3(0, 0, 0);
+ ivec4 i4_ = ivec4(0, 0, 0, 0);
uint u = 0u;
- uvec2 u2 = uvec2(0u, 0u);
- uvec3 u3 = uvec3(0u, 0u, 0u);
- uvec4 u4 = uvec4(0u, 0u, 0u, 0u);
- vec2 f2 = vec2(0.0, 0.0);
- vec4 f4 = vec4(0.0, 0.0, 0.0, 0.0);
- i2 = ivec2(0);
- i3 = ivec3(0);
- i4 = ivec4(0);
- u2 = uvec2(0u);
- u3 = uvec3(0u);
- u4 = uvec4(0u);
- f2 = vec2(0.0);
- f4 = vec4(0.0);
- vec4 _e28 = f4;
+ uvec2 u2_ = uvec2(0u, 0u);
+ uvec3 u3_ = uvec3(0u, 0u, 0u);
+ uvec4 u4_ = uvec4(0u, 0u, 0u, 0u);
+ vec2 f2_ = vec2(0.0, 0.0);
+ vec4 f4_ = vec4(0.0, 0.0, 0.0, 0.0);
+ i2_ = ivec2(0);
+ i3_ = ivec3(0);
+ i4_ = ivec4(0);
+ u2_ = uvec2(0u);
+ u3_ = uvec3(0u);
+ u4_ = uvec4(0u);
+ f2_ = vec2(0.0);
+ f4_ = vec4(0.0);
+ vec4 _e28 = f4_;
u = packSnorm4x8(_e28);
- vec4 _e30 = f4;
+ vec4 _e30 = f4_;
u = packUnorm4x8(_e30);
- vec2 _e32 = f2;
+ vec2 _e32 = f2_;
u = packSnorm2x16(_e32);
- vec2 _e34 = f2;
+ vec2 _e34 = f2_;
u = packUnorm2x16(_e34);
- vec2 _e36 = f2;
+ vec2 _e36 = f2_;
u = packHalf2x16(_e36);
uint _e38 = u;
- f4 = unpackSnorm4x8(_e38);
+ f4_ = unpackSnorm4x8(_e38);
uint _e40 = u;
- f4 = unpackUnorm4x8(_e40);
+ f4_ = unpackUnorm4x8(_e40);
uint _e42 = u;
- f2 = unpackSnorm2x16(_e42);
+ f2_ = unpackSnorm2x16(_e42);
uint _e44 = u;
- f2 = unpackUnorm2x16(_e44);
+ f2_ = unpackUnorm2x16(_e44);
uint _e46 = u;
- f2 = unpackHalf2x16(_e46);
+ f2_ = unpackHalf2x16(_e46);
int _e48 = i;
int _e49 = i;
i = bitfieldInsert(_e48, _e49, int(5u), int(10u));
- ivec2 _e53 = i2;
- ivec2 _e54 = i2;
- i2 = bitfieldInsert(_e53, _e54, int(5u), int(10u));
- ivec3 _e58 = i3;
- ivec3 _e59 = i3;
- i3 = bitfieldInsert(_e58, _e59, int(5u), int(10u));
- ivec4 _e63 = i4;
- ivec4 _e64 = i4;
- i4 = bitfieldInsert(_e63, _e64, int(5u), int(10u));
+ ivec2 _e53 = i2_;
+ ivec2 _e54 = i2_;
+ i2_ = bitfieldInsert(_e53, _e54, int(5u), int(10u));
+ ivec3 _e58 = i3_;
+ ivec3 _e59 = i3_;
+ i3_ = bitfieldInsert(_e58, _e59, int(5u), int(10u));
+ ivec4 _e63 = i4_;
+ ivec4 _e64 = i4_;
+ i4_ = bitfieldInsert(_e63, _e64, int(5u), int(10u));
uint _e68 = u;
uint _e69 = u;
u = bitfieldInsert(_e68, _e69, int(5u), int(10u));
- uvec2 _e73 = u2;
- uvec2 _e74 = u2;
- u2 = bitfieldInsert(_e73, _e74, int(5u), int(10u));
- uvec3 _e78 = u3;
- uvec3 _e79 = u3;
- u3 = bitfieldInsert(_e78, _e79, int(5u), int(10u));
- uvec4 _e83 = u4;
- uvec4 _e84 = u4;
- u4 = bitfieldInsert(_e83, _e84, int(5u), int(10u));
+ uvec2 _e73 = u2_;
+ uvec2 _e74 = u2_;
+ u2_ = bitfieldInsert(_e73, _e74, int(5u), int(10u));
+ uvec3 _e78 = u3_;
+ uvec3 _e79 = u3_;
+ u3_ = bitfieldInsert(_e78, _e79, int(5u), int(10u));
+ uvec4 _e83 = u4_;
+ uvec4 _e84 = u4_;
+ u4_ = bitfieldInsert(_e83, _e84, int(5u), int(10u));
int _e88 = i;
i = bitfieldExtract(_e88, int(5u), int(10u));
- ivec2 _e92 = i2;
- i2 = bitfieldExtract(_e92, int(5u), int(10u));
- ivec3 _e96 = i3;
- i3 = bitfieldExtract(_e96, int(5u), int(10u));
- ivec4 _e100 = i4;
- i4 = bitfieldExtract(_e100, int(5u), int(10u));
+ ivec2 _e92 = i2_;
+ i2_ = bitfieldExtract(_e92, int(5u), int(10u));
+ ivec3 _e96 = i3_;
+ i3_ = bitfieldExtract(_e96, int(5u), int(10u));
+ ivec4 _e100 = i4_;
+ i4_ = bitfieldExtract(_e100, int(5u), int(10u));
uint _e104 = u;
u = bitfieldExtract(_e104, int(5u), int(10u));
- uvec2 _e108 = u2;
- u2 = bitfieldExtract(_e108, int(5u), int(10u));
- uvec3 _e112 = u3;
- u3 = bitfieldExtract(_e112, int(5u), int(10u));
- uvec4 _e116 = u4;
- u4 = bitfieldExtract(_e116, int(5u), int(10u));
+ uvec2 _e108 = u2_;
+ u2_ = bitfieldExtract(_e108, int(5u), int(10u));
+ uvec3 _e112 = u3_;
+ u3_ = bitfieldExtract(_e112, int(5u), int(10u));
+ uvec4 _e116 = u4_;
+ u4_ = bitfieldExtract(_e116, int(5u), int(10u));
return;
}
diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl
--- a/tests/out/glsl/image.main.Compute.glsl
+++ b/tests/out/glsl/image.main.Compute.glsl
@@ -21,11 +21,11 @@ void main() {
uvec3 local_id = gl_LocalInvocationID;
ivec2 dim = imageSize(_group_0_binding_1).xy;
ivec2 itc = ((dim * ivec2(local_id.xy)) % ivec2(10, 20));
- uvec4 value1 = texelFetch(_group_0_binding_0, itc, int(local_id.z));
- uvec4 value2 = texelFetch(_group_0_binding_3, itc, int(local_id.z));
- uvec4 value4 = imageLoad(_group_0_binding_1, itc);
- uvec4 value5 = texelFetch(_group_0_binding_5, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1));
- imageStore(_group_0_binding_2, ivec2(itc.x, 0.0), (((value1 + value2) + value4) + value5));
+ uvec4 value1_ = texelFetch(_group_0_binding_0, itc, int(local_id.z));
+ uvec4 value2_ = texelFetch(_group_0_binding_3, itc, int(local_id.z));
+ uvec4 value4_ = imageLoad(_group_0_binding_1, itc);
+ uvec4 value5_ = texelFetch(_group_0_binding_5, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1));
+ imageStore(_group_0_binding_2, ivec2(itc.x, 0.0), (((value1_ + value2_) + value4_) + value5_));
return;
}
diff --git a/tests/out/glsl/interpolate.main.Fragment.glsl b/tests/out/glsl/interpolate.main.Fragment.glsl
--- a/tests/out/glsl/interpolate.main.Fragment.glsl
+++ b/tests/out/glsl/interpolate.main.Fragment.glsl
@@ -1,7 +1,7 @@
#version 400 core
struct FragmentInput {
vec4 position;
- uint flat1;
+ uint flat_;
float linear;
vec2 linear_centroid;
vec3 linear_sample;
diff --git a/tests/out/glsl/interpolate.main.Vertex.glsl b/tests/out/glsl/interpolate.main.Vertex.glsl
--- a/tests/out/glsl/interpolate.main.Vertex.glsl
+++ b/tests/out/glsl/interpolate.main.Vertex.glsl
@@ -1,7 +1,7 @@
#version 400 core
struct FragmentInput {
vec4 position;
- uint flat1;
+ uint flat_;
float linear;
vec2 linear_centroid;
vec3 linear_sample;
diff --git a/tests/out/glsl/interpolate.main.Vertex.glsl b/tests/out/glsl/interpolate.main.Vertex.glsl
--- a/tests/out/glsl/interpolate.main.Vertex.glsl
+++ b/tests/out/glsl/interpolate.main.Vertex.glsl
@@ -19,18 +19,18 @@ smooth centroid out float _vs2fs_location5;
smooth sample out float _vs2fs_location6;
void main() {
- FragmentInput out1;
- out1.position = vec4(2.0, 4.0, 5.0, 6.0);
- out1.flat1 = 8u;
- out1.linear = 27.0;
- out1.linear_centroid = vec2(64.0, 125.0);
- out1.linear_sample = vec3(216.0, 343.0, 512.0);
- out1.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0);
- out1.perspective_centroid = 2197.0;
- out1.perspective_sample = 2744.0;
- FragmentInput _e30 = out1;
+ FragmentInput out_;
+ out_.position = vec4(2.0, 4.0, 5.0, 6.0);
+ out_.flat_ = 8u;
+ out_.linear = 27.0;
+ out_.linear_centroid = vec2(64.0, 125.0);
+ out_.linear_sample = vec3(216.0, 343.0, 512.0);
+ out_.perspective = vec4(729.0, 1000.0, 1331.0, 1728.0);
+ out_.perspective_centroid = 2197.0;
+ out_.perspective_sample = 2744.0;
+ FragmentInput _e30 = out_;
gl_Position = _e30.position;
- _vs2fs_location0 = _e30.flat1;
+ _vs2fs_location0 = _e30.flat_;
_vs2fs_location1 = _e30.linear;
_vs2fs_location2 = _e30.linear_centroid;
_vs2fs_location3 = _e30.linear_sample;
diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl
--- a/tests/out/glsl/operators.main.Compute.glsl
+++ b/tests/out/glsl/operators.main.Compute.glsl
@@ -12,15 +12,15 @@ struct Foo {
vec4 builtins() {
- int s1 = (true ? 1 : 0);
- vec4 s2 = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0));
- vec4 s3 = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), bvec4(false, false, false, false));
- vec4 m1 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5));
- vec4 m2 = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612);
- float b1 = intBitsToFloat(ivec4(1, 1, 1, 1).x);
- vec4 b2 = intBitsToFloat(ivec4(1, 1, 1, 1));
+ int s1_ = (true ? 1 : 0);
+ vec4 s2_ = (true ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0));
+ vec4 s3_ = mix(vec4(1.0, 1.0, 1.0, 1.0), vec4(0.0, 0.0, 0.0, 0.0), bvec4(false, false, false, false));
+ vec4 m1_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), vec4(0.5, 0.5, 0.5, 0.5));
+ vec4 m2_ = mix(vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612);
+ float b1_ = intBitsToFloat(ivec4(1, 1, 1, 1).x);
+ vec4 b2_ = intBitsToFloat(ivec4(1, 1, 1, 1));
ivec4 v_i32_zero = ivec4(vec4(0.0, 0.0, 0.0, 0.0));
- return (((((vec4((ivec4(s1) + v_i32_zero)) + s2) + m1) + m2) + vec4(b1)) + b2);
+ return (((((vec4((ivec4(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4(b1_)) + b2_);
}
vec4 splat() {
diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl
--- a/tests/out/glsl/operators.main.Compute.glsl
+++ b/tests/out/glsl/operators.main.Compute.glsl
@@ -50,8 +50,8 @@ float constructors() {
}
void modulo() {
- int a1 = (1 % 1);
- float b1 = (1.0 - 1.0 * trunc(1.0 / 1.0));
+ int a_1 = (1 % 1);
+ float b_1 = (1.0 - 1.0 * trunc(1.0 / 1.0));
ivec3 c = (ivec3(1) % ivec3(1));
vec3 d = (vec3(1.0) - vec3(1.0) * trunc(vec3(1.0) / vec3(1.0)));
}
diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl
--- a/tests/out/glsl/quad-vert.main.Vertex.glsl
+++ b/tests/out/glsl/quad-vert.main.Vertex.glsl
@@ -3,14 +3,14 @@
precision highp float;
precision highp int;
-struct type9 {
+struct type_9 {
vec2 member;
vec4 gen_gl_Position;
};
vec2 v_uv = vec2(0.0, 0.0);
-vec2 a_uv1 = vec2(0.0, 0.0);
+vec2 a_uv_1 = vec2(0.0, 0.0);
struct gen_gl_PerVertex_block_0Vs {
vec4 gen_gl_Position;
diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl
--- a/tests/out/glsl/quad-vert.main.Vertex.glsl
+++ b/tests/out/glsl/quad-vert.main.Vertex.glsl
@@ -19,16 +19,16 @@ struct gen_gl_PerVertex_block_0Vs {
float gen_gl_CullDistance[1];
} perVertexStruct;
-vec2 a_pos1 = vec2(0.0, 0.0);
+vec2 a_pos_1 = vec2(0.0, 0.0);
layout(location = 1) in vec2 _p2vs_location1;
layout(location = 0) in vec2 _p2vs_location0;
layout(location = 0) smooth out vec2 _vs2fs_location0;
-void main2() {
- vec2 _e12 = a_uv1;
+void main_1() {
+ vec2 _e12 = a_uv_1;
v_uv = _e12;
- vec2 _e13 = a_pos1;
+ vec2 _e13 = a_pos_1;
perVertexStruct.gen_gl_Position = vec4(_e13.x, _e13.y, 0.0, 1.0);
return;
}
diff --git a/tests/out/glsl/quad-vert.main.Vertex.glsl b/tests/out/glsl/quad-vert.main.Vertex.glsl
--- a/tests/out/glsl/quad-vert.main.Vertex.glsl
+++ b/tests/out/glsl/quad-vert.main.Vertex.glsl
@@ -36,12 +36,12 @@ void main2() {
void main() {
vec2 a_uv = _p2vs_location1;
vec2 a_pos = _p2vs_location0;
- a_uv1 = a_uv;
- a_pos1 = a_pos;
- main2();
+ a_uv_1 = a_uv;
+ a_pos_1 = a_pos;
+ main_1();
vec2 _e7 = v_uv;
vec4 _e8 = perVertexStruct.gen_gl_Position;
- type9 _tmp_return = type9(_e7, _e8);
+ type_9 _tmp_return = type_9(_e7, _e8);
_vs2fs_location0 = _tmp_return.member;
gl_Position = _tmp_return.gen_gl_Position;
gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);
diff --git a/tests/out/glsl/quad.main.Fragment.glsl b/tests/out/glsl/quad.main.Fragment.glsl
--- a/tests/out/glsl/quad.main.Fragment.glsl
+++ b/tests/out/glsl/quad.main.Fragment.glsl
@@ -14,8 +14,8 @@ smooth in vec2 _vs2fs_location0;
layout(location = 0) out vec4 _fs2p_location0;
void main() {
- vec2 uv1 = _vs2fs_location0;
- vec4 color = texture(_group_0_binding_0, vec2(uv1));
+ vec2 uv_1 = _vs2fs_location0;
+ vec4 color = texture(_group_0_binding_0, vec2(uv_1));
if ((color.w == 0.0)) {
discard;
}
diff --git a/tests/out/glsl/skybox.fs_main.Fragment.glsl b/tests/out/glsl/skybox.fs_main.Fragment.glsl
--- a/tests/out/glsl/skybox.fs_main.Fragment.glsl
+++ b/tests/out/glsl/skybox.fs_main.Fragment.glsl
@@ -14,8 +14,8 @@ layout(location = 0) smooth in vec3 _vs2fs_location0;
layout(location = 0) out vec4 _fs2p_location0;
void main() {
- VertexOutput in1 = VertexOutput(gl_FragCoord, _vs2fs_location0);
- vec4 _e5 = texture(_group_0_binding_1, vec3(in1.uv));
+ VertexOutput in_ = VertexOutput(gl_FragCoord, _vs2fs_location0);
+ vec4 _e5 = texture(_group_0_binding_1, vec3(in_.uv));
_fs2p_location0 = _e5;
return;
}
diff --git a/tests/out/glsl/skybox.vs_main.Vertex.glsl b/tests/out/glsl/skybox.vs_main.Vertex.glsl
--- a/tests/out/glsl/skybox.vs_main.Vertex.glsl
+++ b/tests/out/glsl/skybox.vs_main.Vertex.glsl
@@ -17,12 +17,12 @@ layout(location = 0) smooth out vec3 _vs2fs_location0;
void main() {
uint vertex_index = uint(gl_VertexID);
- int tmp1 = 0;
- int tmp2 = 0;
- tmp1 = (int(vertex_index) / 2);
- tmp2 = (int(vertex_index) & 1);
- int _e10 = tmp1;
- int _e16 = tmp2;
+ int tmp1_ = 0;
+ int tmp2_ = 0;
+ tmp1_ = (int(vertex_index) / 2);
+ tmp2_ = (int(vertex_index) & 1);
+ int _e10 = tmp1_;
+ int _e16 = tmp2_;
vec4 pos = vec4(((float(_e10) * 4.0) - 1.0), ((float(_e16) * 4.0) - 1.0), 0.0, 1.0);
vec4 _e27 = _group_0_binding_0.view[0];
vec4 _e31 = _group_0_binding_0.view[1];
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -1,9 +1,9 @@
RWByteAddressBuffer bar : register(u0);
-float read_from_private(inout float foo2)
+float read_from_private(inout float foo_2)
{
- float _expr2 = foo2;
+ float _expr2 = foo_2;
return _expr2;
}
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -16,16 +16,16 @@ uint NagaBufferLengthRW(RWByteAddressBuffer buffer)
float4 foo(uint vi : SV_VertexID) : SV_Position
{
- float foo1 = 0.0;
+ float foo_1 = 0.0;
int c[5] = {(int)0,(int)0,(int)0,(int)0,(int)0};
- float baz = foo1;
- foo1 = 1.0;
- float4x4 matrix1 = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48)));
+ float baz = foo_1;
+ foo_1 = 1.0;
+ float4x4 matrix_ = float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48)));
uint2 arr[2] = {asuint(bar.Load2(72+0)), asuint(bar.Load2(72+8))};
float b = asfloat(bar.Load(0+48+0));
int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 8) - 2u)*8+88));
- const float _e25 = read_from_private(foo1);
+ const float _e25 = read_from_private(foo_1);
bar.Store(8+16+0, asuint(1.0));
{
float4x4 _value2 = float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx));
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -46,7 +46,7 @@ float4 foo(uint vi : SV_VertexID) : SV_Position
}
c[(vi + 1u)] = 42;
int value = c[vi];
- return mul(float4(int4(value.xxxx)), matrix1);
+ return mul(float4(int4(value.xxxx)), matrix_);
}
[numthreads(1, 1, 1)]
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -54,7 +54,7 @@ void atomics()
{
int tmp = (int)0;
- int value1 = asint(bar.Load(64));
+ int value_1 = asint(bar.Load(64));
int _e6; bar.InterlockedAdd(64, 5, _e6);
tmp = _e6;
int _e9; bar.InterlockedAdd(64, -5, _e9);
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -71,6 +71,6 @@ void atomics()
tmp = _e24;
int _e27; bar.InterlockedExchange(64, 5, _e27);
tmp = _e27;
- bar.Store(64, asuint(value1));
+ bar.Store(64, asuint(value_1));
return;
}
diff --git a/tests/out/hlsl/empty-global-name.hlsl b/tests/out/hlsl/empty-global-name.hlsl
--- a/tests/out/hlsl/empty-global-name.hlsl
+++ b/tests/out/hlsl/empty-global-name.hlsl
@@ -1,14 +1,14 @@
-struct type1 {
+struct type_1 {
int member;
};
-RWByteAddressBuffer global : register(u0);
+RWByteAddressBuffer unnamed : register(u0);
void function()
{
- int _expr8 = asint(global.Load(0));
- global.Store(0, asuint((_expr8 + 1)));
+ int _expr8 = asint(unnamed.Load(0));
+ unnamed.Store(0, asuint((_expr8 + 1)));
return;
}
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -29,21 +29,21 @@ void main(uint3 local_id : SV_GroupThreadID)
{
int2 dim = NagaRWDimensions2D(image_storage_src);
int2 itc = ((dim * int2(local_id.xy)) % int2(10, 20));
- uint4 value1 = image_mipmapped_src.Load(int3(itc, int(local_id.z)));
- uint4 value2 = image_multisampled_src.Load(itc, int(local_id.z));
- uint4 value4 = image_storage_src.Load(itc);
- uint4 value5 = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1)));
- image_dst[itc.x] = (((value1 + value2) + value4) + value5);
+ uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(local_id.z)));
+ uint4 value2_ = image_multisampled_src.Load(itc, int(local_id.z));
+ uint4 value4_ = image_storage_src.Load(itc);
+ uint4 value5_ = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1)));
+ image_dst[itc.x] = (((value1_ + value2_) + value4_) + value5_);
return;
}
[numthreads(16, 1, 1)]
-void depth_load(uint3 local_id1 : SV_GroupThreadID)
+void depth_load(uint3 local_id_1 : SV_GroupThreadID)
{
- int2 dim1 = NagaRWDimensions2D(image_storage_src);
- int2 itc1 = ((dim1 * int2(local_id1.xy)) % int2(10, 20));
- float val = image_depth_multisampled_src.Load(itc1, int(local_id1.z)).x;
- image_dst[itc1.x] = uint4(uint(val).xxxx);
+ int2 dim_1 = NagaRWDimensions2D(image_storage_src);
+ int2 itc_1 = ((dim_1 * int2(local_id_1.xy)) % int2(10, 20));
+ float val = image_depth_multisampled_src.Load(itc_1, int(local_id_1.z)).x;
+ image_dst[itc_1.x] = uint4(uint(val).xxxx);
return;
}
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -207,11 +207,11 @@ float4 levels_queries() : SV_Position
int num_layers_cube = NagaNumLayersCubeArray(image_cube_array);
int num_levels_3d = NagaNumLevels3D(image_3d);
int num_samples_aa = NagaMSNumSamples2D(image_aa);
- int sum1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array);
- return float4(float(sum1).xxxx);
+ int sum_1 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array);
+ return float4(float(sum_1).xxxx);
}
-float4 sample1() : SV_Target0
+float4 sample_() : SV_Target0
{
float2 tc = float2(0.5.xx);
float4 s1d = image_1d.Sample(sampler_reg, tc.x);
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -224,8 +224,8 @@ float4 sample1() : SV_Target0
float sample_comparison() : SV_Target0
{
- float2 tc1 = float2(0.5.xx);
- float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc1, 0.5);
- float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc1, 0.5);
+ float2 tc_1 = float2(0.5.xx);
+ float s2d_depth = image_2d_depth.SampleCmp(sampler_cmp, tc_1, 0.5);
+ float s2d_depth_level = image_2d_depth.SampleCmpLevelZero(sampler_cmp, tc_1, 0.5);
return (s2d_depth + s2d_depth_level);
}
diff --git a/tests/out/hlsl/image.hlsl.config b/tests/out/hlsl/image.hlsl.config
--- a/tests/out/hlsl/image.hlsl.config
+++ b/tests/out/hlsl/image.hlsl.config
@@ -1,3 +1,3 @@
vertex=(queries:vs_5_1 levels_queries:vs_5_1 )
-fragment=(sample1:ps_5_1 sample_comparison:ps_5_1 )
+fragment=(sample_:ps_5_1 sample_comparison:ps_5_1 )
compute=(main:cs_5_1 depth_load:cs_5_1 )
diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl
--- a/tests/out/hlsl/interface.hlsl
+++ b/tests/out/hlsl/interface.hlsl
@@ -24,11 +24,11 @@ struct VertexOutput_vertex {
};
struct FragmentInput_fragment {
- float varying1 : LOC1;
- float4 position1 : SV_Position;
- bool front_facing1 : SV_IsFrontFace;
- uint sample_index1 : SV_SampleIndex;
- uint sample_mask1 : SV_Coverage;
+ float varying_1 : LOC1;
+ float4 position_1 : SV_Position;
+ bool front_facing_1 : SV_IsFrontFace;
+ uint sample_index_1 : SV_SampleIndex;
+ uint sample_mask_1 : SV_Coverage;
};
VertexOutput ConstructVertexOutput(float4 arg0, float arg1) {
diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl
--- a/tests/out/hlsl/interface.hlsl
+++ b/tests/out/hlsl/interface.hlsl
@@ -42,8 +42,8 @@ VertexOutput_vertex vertex(uint vertex_index : SV_VertexID, uint instance_index
{
uint tmp = (((_NagaConstants.base_vertex + vertex_index) + (_NagaConstants.base_instance + instance_index)) + color);
const VertexOutput vertexoutput = ConstructVertexOutput(float4(1.0.xxxx), float(tmp));
- const VertexOutput_vertex vertexoutput1 = { vertexoutput.varying, vertexoutput.position };
- return vertexoutput1;
+ const VertexOutput_vertex vertexoutput_1 = { vertexoutput.varying, vertexoutput.position };
+ return vertexoutput_1;
}
FragmentOutput ConstructFragmentOutput(float arg0, uint arg1, float arg2) {
diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl
--- a/tests/out/hlsl/interface.hlsl
+++ b/tests/out/hlsl/interface.hlsl
@@ -56,13 +56,13 @@ FragmentOutput ConstructFragmentOutput(float arg0, uint arg1, float arg2) {
FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment)
{
- VertexOutput in1 = { fragmentinput_fragment.position1, fragmentinput_fragment.varying1 };
- bool front_facing = fragmentinput_fragment.front_facing1;
- uint sample_index = fragmentinput_fragment.sample_index1;
- uint sample_mask = fragmentinput_fragment.sample_mask1;
+ VertexOutput in_ = { fragmentinput_fragment.position_1, fragmentinput_fragment.varying_1 };
+ bool front_facing = fragmentinput_fragment.front_facing_1;
+ uint sample_index = fragmentinput_fragment.sample_index_1;
+ uint sample_mask = fragmentinput_fragment.sample_mask_1;
uint mask = (sample_mask & (1u << sample_index));
- float color1 = (front_facing ? 1.0 : 0.0);
- const FragmentOutput fragmentoutput = ConstructFragmentOutput(in1.varying, mask, color1);
+ float color_1 = (front_facing ? 1.0 : 0.0);
+ const FragmentOutput fragmentoutput = ConstructFragmentOutput(in_.varying, mask, color_1);
return fragmentoutput;
}
diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl
--- a/tests/out/hlsl/interpolate.hlsl
+++ b/tests/out/hlsl/interpolate.hlsl
@@ -2,7 +2,7 @@
struct FragmentInput {
float4 position : SV_Position;
nointerpolation uint flat : LOC0;
- noperspective float linear1 : LOC1;
+ noperspective float linear_ : LOC1;
noperspective centroid float2 linear_centroid : LOC2;
noperspective sample float3 linear_sample : LOC3;
linear float4 perspective : LOC4;
diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl
--- a/tests/out/hlsl/interpolate.hlsl
+++ b/tests/out/hlsl/interpolate.hlsl
@@ -12,7 +12,7 @@ struct FragmentInput {
struct VertexOutput_main {
uint flat : LOC0;
- float linear1 : LOC1;
+ float linear_ : LOC1;
float2 linear_centroid : LOC2;
float3 linear_sample : LOC3;
float4 perspective : LOC4;
diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl
--- a/tests/out/hlsl/interpolate.hlsl
+++ b/tests/out/hlsl/interpolate.hlsl
@@ -22,36 +22,36 @@ struct VertexOutput_main {
};
struct FragmentInput_main {
- uint flat1 : LOC0;
- float linear2 : LOC1;
- float2 linear_centroid1 : LOC2;
- float3 linear_sample1 : LOC3;
- float4 perspective1 : LOC4;
- float perspective_centroid1 : LOC5;
- float perspective_sample1 : LOC6;
- float4 position1 : SV_Position;
+ uint flat_1 : LOC0;
+ float linear_1 : LOC1;
+ float2 linear_centroid_1 : LOC2;
+ float3 linear_sample_1 : LOC3;
+ float4 perspective_1 : LOC4;
+ float perspective_centroid_1 : LOC5;
+ float perspective_sample_1 : LOC6;
+ float4 position_1 : SV_Position;
};
VertexOutput_main main()
{
- FragmentInput out1 = (FragmentInput)0;
+ FragmentInput out_ = (FragmentInput)0;
- out1.position = float4(2.0, 4.0, 5.0, 6.0);
- out1.flat = 8u;
- out1.linear1 = 27.0;
- out1.linear_centroid = float2(64.0, 125.0);
- out1.linear_sample = float3(216.0, 343.0, 512.0);
- out1.perspective = float4(729.0, 1000.0, 1331.0, 1728.0);
- out1.perspective_centroid = 2197.0;
- out1.perspective_sample = 2744.0;
- FragmentInput _expr30 = out1;
+ out_.position = float4(2.0, 4.0, 5.0, 6.0);
+ out_.flat = 8u;
+ out_.linear_ = 27.0;
+ out_.linear_centroid = float2(64.0, 125.0);
+ out_.linear_sample = float3(216.0, 343.0, 512.0);
+ out_.perspective = float4(729.0, 1000.0, 1331.0, 1728.0);
+ out_.perspective_centroid = 2197.0;
+ out_.perspective_sample = 2744.0;
+ FragmentInput _expr30 = out_;
const FragmentInput fragmentinput = _expr30;
- const VertexOutput_main fragmentinput1 = { fragmentinput.flat, fragmentinput.linear1, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position };
- return fragmentinput1;
+ const VertexOutput_main fragmentinput_1 = { fragmentinput.flat, fragmentinput.linear_, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position };
+ return fragmentinput_1;
}
-void main1(FragmentInput_main fragmentinput_main)
+void main_1(FragmentInput_main fragmentinput_main)
{
- FragmentInput val = { fragmentinput_main.position1, fragmentinput_main.flat1, fragmentinput_main.linear2, fragmentinput_main.linear_centroid1, fragmentinput_main.linear_sample1, fragmentinput_main.perspective1, fragmentinput_main.perspective_centroid1, fragmentinput_main.perspective_sample1 };
+ FragmentInput val = { fragmentinput_main.position_1, fragmentinput_main.flat_1, fragmentinput_main.linear_1, fragmentinput_main.linear_centroid_1, fragmentinput_main.linear_sample_1, fragmentinput_main.perspective_1, fragmentinput_main.perspective_centroid_1, fragmentinput_main.perspective_sample_1 };
return;
}
diff --git a/tests/out/hlsl/interpolate.hlsl.config b/tests/out/hlsl/interpolate.hlsl.config
--- a/tests/out/hlsl/interpolate.hlsl.config
+++ b/tests/out/hlsl/interpolate.hlsl.config
@@ -1,3 +1,3 @@
vertex=(main:vs_5_1 )
-fragment=(main1:ps_5_1 )
+fragment=(main_1:ps_5_1 )
compute=()
diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
--- a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
+++ b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
@@ -1,7 +1,7 @@
static float a = (float)0;
-void main1()
+void main_1()
{
float b = (float)0;
float c = (float)0;
diff --git a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
--- a/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
+++ b/tests/out/hlsl/inv-hyperbolic-trig-functions.hlsl
@@ -18,5 +18,5 @@ void main1()
void main()
{
- main1();
+ main_1();
}
diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl
--- a/tests/out/hlsl/operators.hlsl
+++ b/tests/out/hlsl/operators.hlsl
@@ -10,15 +10,15 @@ struct Foo {
float4 builtins()
{
- int s1 = (true ? 1 : 0);
- float4 s2 = (true ? float4(1.0, 1.0, 1.0, 1.0) : float4(0.0, 0.0, 0.0, 0.0));
- float4 s3 = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0));
- float4 m1 = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5));
- float4 m2 = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612);
- float b1 = float(int4(1, 1, 1, 1).x);
- float4 b2 = float4(int4(1, 1, 1, 1));
+ int s1_ = (true ? 1 : 0);
+ float4 s2_ = (true ? float4(1.0, 1.0, 1.0, 1.0) : float4(0.0, 0.0, 0.0, 0.0));
+ float4 s3_ = (bool4(false, false, false, false) ? float4(0.0, 0.0, 0.0, 0.0) : float4(1.0, 1.0, 1.0, 1.0));
+ float4 m1_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), float4(0.5, 0.5, 0.5, 0.5));
+ float4 m2_ = lerp(float4(0.0, 0.0, 0.0, 0.0), float4(1.0, 1.0, 1.0, 1.0), 0.10000000149011612);
+ float b1_ = float(int4(1, 1, 1, 1).x);
+ float4 b2_ = float4(int4(1, 1, 1, 1));
int4 v_i32_zero = int4(float4(0.0, 0.0, 0.0, 0.0));
- return (((((float4((int4(s1.xxxx) + v_i32_zero)) + s2) + m1) + m2) + float4(b1.xxxx)) + b2);
+ return (((((float4((int4(s1_.xxxx) + v_i32_zero)) + s2_) + m1_) + m2_) + float4(b1_.xxxx)) + b2_);
}
float4 splat()
diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl
--- a/tests/out/hlsl/operators.hlsl
+++ b/tests/out/hlsl/operators.hlsl
@@ -61,8 +61,8 @@ float constructors()
void modulo()
{
- int a1 = (1 % 1);
- float b1 = (1.0 % 1.0);
+ int a_1 = (1 % 1);
+ float b_1 = (1.0 % 1.0);
int3 c = (int3(1.xxx) % int3(1.xxx));
float3 d = (float3(1.0.xxx) % float3(1.0.xxx));
}
diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl
--- a/tests/out/hlsl/quad-vert.hlsl
+++ b/tests/out/hlsl/quad-vert.hlsl
@@ -6,32 +6,32 @@ struct gl_PerVertex {
float gl_CullDistance[1] : SV_CullDistance;
};
-struct type9 {
+struct type_9 {
linear float2 member : LOC0;
float4 gl_Position : SV_Position;
};
static float2 v_uv = (float2)0;
-static float2 a_uv1 = (float2)0;
+static float2 a_uv_1 = (float2)0;
static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, { 0.0 }, { 0.0 } };
-static float2 a_pos1 = (float2)0;
+static float2 a_pos_1 = (float2)0;
struct VertexOutput_main {
float2 member : LOC0;
float4 gl_Position : SV_Position;
};
-void main1()
+void main_1()
{
- float2 _expr12 = a_uv1;
+ float2 _expr12 = a_uv_1;
v_uv = _expr12;
- float2 _expr13 = a_pos1;
+ float2 _expr13 = a_pos_1;
perVertexStruct.gl_Position = float4(_expr13.x, _expr13.y, 0.0, 1.0);
return;
}
-type9 Constructtype9(float2 arg0, float4 arg1) {
- type9 ret;
+type_9 Constructtype_9(float2 arg0, float4 arg1) {
+ type_9 ret;
ret.member = arg0;
ret.gl_Position = arg1;
return ret;
diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl
--- a/tests/out/hlsl/quad-vert.hlsl
+++ b/tests/out/hlsl/quad-vert.hlsl
@@ -39,12 +39,12 @@ type9 Constructtype9(float2 arg0, float4 arg1) {
VertexOutput_main main(float2 a_uv : LOC1, float2 a_pos : LOC0)
{
- a_uv1 = a_uv;
- a_pos1 = a_pos;
- main1();
+ a_uv_1 = a_uv;
+ a_pos_1 = a_pos;
+ main_1();
float2 _expr7 = v_uv;
float4 _expr8 = perVertexStruct.gl_Position;
- const type9 type9 = Constructtype9(_expr7, _expr8);
- const VertexOutput_main type9_1 = { type9.member, type9.gl_Position };
- return type9_1;
+ const type_9 type_9_ = Constructtype_9(_expr7, _expr8);
+ const VertexOutput_main type_9_1 = { type_9_.member, type_9_.gl_Position };
+ return type_9_1;
}
diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl
--- a/tests/out/hlsl/quad.hlsl
+++ b/tests/out/hlsl/quad.hlsl
@@ -9,12 +9,12 @@ Texture2D<float4> u_texture : register(t0);
SamplerState u_sampler : register(s1);
struct VertexOutput_main {
- float2 uv2 : LOC0;
+ float2 uv_2 : LOC0;
float4 position : SV_Position;
};
struct FragmentInput_main {
- float2 uv3 : LOC0;
+ float2 uv_3 : LOC0;
};
VertexOutput ConstructVertexOutput(float2 arg0, float4 arg1) {
diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl
--- a/tests/out/hlsl/quad.hlsl
+++ b/tests/out/hlsl/quad.hlsl
@@ -27,14 +27,14 @@ VertexOutput ConstructVertexOutput(float2 arg0, float4 arg1) {
VertexOutput_main main(float2 pos : LOC0, float2 uv : LOC1)
{
const VertexOutput vertexoutput = ConstructVertexOutput(uv, float4((c_scale * pos), 0.0, 1.0));
- const VertexOutput_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position };
- return vertexoutput1;
+ const VertexOutput_main vertexoutput_1 = { vertexoutput.uv, vertexoutput.position };
+ return vertexoutput_1;
}
-float4 main1(FragmentInput_main fragmentinput_main) : SV_Target0
+float4 main_1(FragmentInput_main fragmentinput_main) : SV_Target0
{
- float2 uv1 = fragmentinput_main.uv3;
- float4 color = u_texture.Sample(u_sampler, uv1);
+ float2 uv_1 = fragmentinput_main.uv_3;
+ float4 color = u_texture.Sample(u_sampler, uv_1);
if ((color.w == 0.0)) {
discard;
}
diff --git a/tests/out/hlsl/quad.hlsl.config b/tests/out/hlsl/quad.hlsl.config
--- a/tests/out/hlsl/quad.hlsl.config
+++ b/tests/out/hlsl/quad.hlsl.config
@@ -1,3 +1,3 @@
vertex=(main:vs_5_1 )
-fragment=(main1:ps_5_1 fs_extra:ps_5_1 )
+fragment=(main_1:ps_5_1 fs_extra:ps_5_1 )
compute=()
diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl
--- a/tests/out/hlsl/shadow.hlsl
+++ b/tests/out/hlsl/shadow.hlsl
@@ -17,8 +17,8 @@ Texture2DArray<float> t_shadow : register(t2);
SamplerComparisonState sampler_shadow : register(s3);
struct FragmentInput_fs_main {
- float3 raw_normal1 : LOC0;
- float4 position1 : LOC1;
+ float3 raw_normal_1 : LOC0;
+ float4 position_1 : LOC1;
};
float fetch_shadow(uint light_id, float4 homogeneous_coords)
diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl
--- a/tests/out/hlsl/shadow.hlsl
+++ b/tests/out/hlsl/shadow.hlsl
@@ -34,8 +34,8 @@ float fetch_shadow(uint light_id, float4 homogeneous_coords)
float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0
{
- float3 raw_normal = fragmentinput_fs_main.raw_normal1;
- float4 position = fragmentinput_fs_main.position1;
+ float3 raw_normal = fragmentinput_fs_main.raw_normal_1;
+ float4 position = fragmentinput_fs_main.position_1;
float3 color = float3(0.05000000074505806, 0.05000000074505806, 0.05000000074505806);
uint i = 0u;
diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl
--- a/tests/out/hlsl/skybox.hlsl
+++ b/tests/out/hlsl/skybox.hlsl
@@ -25,8 +25,8 @@ struct VertexOutput_vs_main {
};
struct FragmentInput_fs_main {
- float3 uv1 : LOC0;
- float4 position1 : SV_Position;
+ float3 uv_1 : LOC0;
+ float4 position_1 : SV_Position;
};
VertexOutput ConstructVertexOutput(float4 arg0, float3 arg1) {
diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl
--- a/tests/out/hlsl/skybox.hlsl
+++ b/tests/out/hlsl/skybox.hlsl
@@ -38,13 +38,13 @@ VertexOutput ConstructVertexOutput(float4 arg0, float3 arg1) {
VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID)
{
- int tmp1 = (int)0;
- int tmp2 = (int)0;
+ int tmp1_ = (int)0;
+ int tmp2_ = (int)0;
- tmp1 = (int((_NagaConstants.base_vertex + vertex_index)) / 2);
- tmp2 = (int((_NagaConstants.base_vertex + vertex_index)) & 1);
- int _expr10 = tmp1;
- int _expr16 = tmp2;
+ tmp1_ = (int((_NagaConstants.base_vertex + vertex_index)) / 2);
+ tmp2_ = (int((_NagaConstants.base_vertex + vertex_index)) & 1);
+ int _expr10 = tmp1_;
+ int _expr16 = tmp2_;
float4 pos = float4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0);
float4 _expr27 = r_data.view[0];
float4 _expr31 = r_data.view[1];
diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl
--- a/tests/out/hlsl/skybox.hlsl
+++ b/tests/out/hlsl/skybox.hlsl
@@ -53,13 +53,13 @@ VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID)
float4x4 _expr40 = r_data.proj_inv;
float4 unprojected = mul(pos, _expr40);
const VertexOutput vertexoutput = ConstructVertexOutput(pos, mul(unprojected.xyz, inv_model_view));
- const VertexOutput_vs_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position };
- return vertexoutput1;
+ const VertexOutput_vs_main vertexoutput_1 = { vertexoutput.uv, vertexoutput.position };
+ return vertexoutput_1;
}
float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0
{
- VertexOutput in1 = { fragmentinput_fs_main.position1, fragmentinput_fs_main.uv1 };
- float4 _expr5 = r_texture.Sample(r_sampler, in1.uv);
+ VertexOutput in_ = { fragmentinput_fs_main.position_1, fragmentinput_fs_main.uv_1 };
+ float4 _expr5 = r_texture.Sample(r_sampler, in_.uv);
return _expr5;
}
diff --git a/tests/out/hlsl/standard.hlsl b/tests/out/hlsl/standard.hlsl
--- a/tests/out/hlsl/standard.hlsl
+++ b/tests/out/hlsl/standard.hlsl
@@ -1,11 +1,11 @@
struct FragmentInput_derivatives {
- float4 foo1 : SV_Position;
+ float4 foo_1 : SV_Position;
};
float4 derivatives(FragmentInput_derivatives fragmentinput_derivatives) : SV_Target0
{
- float4 foo = fragmentinput_derivatives.foo1;
+ float4 foo = fragmentinput_derivatives.foo_1;
float4 x = ddx(foo);
float4 y = ddy(foo);
float4 z = fwidth(foo);
diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl
--- a/tests/out/msl/access.msl
+++ b/tests/out/msl/access.msl
@@ -6,25 +6,25 @@ struct _mslBufferSizes {
metal::uint size0;
};
-struct type3 {
+struct type_3 {
metal::uint2 inner[2];
};
-typedef int type5[1];
+typedef int type_5[1];
struct Bar {
metal::float4x4 matrix;
metal::atomic_int atom;
char _pad2[4];
- type3 arr;
- type5 data;
+ type_3 arr;
+ type_5 data;
};
-struct type11 {
+struct type_11 {
int inner[5];
};
float read_from_private(
- thread float& foo2
+ thread float& foo_2
) {
- float _e2 = foo2;
+ float _e2 = foo_2;
return _e2;
}
diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl
--- a/tests/out/msl/access.msl
+++ b/tests/out/msl/access.msl
@@ -38,20 +38,20 @@ vertex fooOutput foo(
, device Bar& bar [[buffer(0)]]
, constant _mslBufferSizes& _buffer_sizes [[buffer(24)]]
) {
- float foo1 = 0.0;
- type11 c;
- float baz = foo1;
- foo1 = 1.0;
+ float foo_1 = 0.0;
+ type_11 c;
+ float baz = foo_1;
+ foo_1 = 1.0;
metal::float4x4 matrix = bar.matrix;
- type3 arr = bar.arr;
+ type_3 arr = bar.arr;
float b = bar.matrix[3].x;
int a = bar.data[(1 + (_buffer_sizes.size0 - 88 - 4) / 8) - 2u];
- float _e25 = read_from_private(foo1);
+ float _e25 = read_from_private(foo_1);
bar.matrix[1].z = 1.0;
bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0));
- for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type3 {metal::uint2(0u), metal::uint2(1u)}.inner[_i];
+ for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type_3 {metal::uint2(0u), metal::uint2(1u)}.inner[_i];
bar.data[1] = 1;
- for(int _i=0; _i<5; ++_i) c.inner[_i] = type11 {a, static_cast<int>(b), 3, 4, 5}.inner[_i];
+ for(int _i=0; _i<5; ++_i) c.inner[_i] = type_11 {a, static_cast<int>(b), 3, 4, 5}.inner[_i];
c.inner[vi + 1u] = 42;
int value = c.inner[vi];
return fooOutput { matrix * static_cast<metal::float4>(metal::int4(value)) };
diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl
--- a/tests/out/msl/access.msl
+++ b/tests/out/msl/access.msl
@@ -63,7 +63,7 @@ kernel void atomics(
, constant _mslBufferSizes& _buffer_sizes [[buffer(24)]]
) {
int tmp;
- int value1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed);
+ int value_1 = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed);
int _e6 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed);
tmp = _e6;
int _e9 = metal::atomic_fetch_sub_explicit(&bar.atom, 5, metal::memory_order_relaxed);
diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl
--- a/tests/out/msl/access.msl
+++ b/tests/out/msl/access.msl
@@ -80,6 +80,6 @@ kernel void atomics(
tmp = _e24;
int _e27 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed);
tmp = _e27;
- metal::atomic_store_explicit(&bar.atom, value1, metal::memory_order_relaxed);
+ metal::atomic_store_explicit(&bar.atom, value_1, metal::memory_order_relaxed);
return;
}
diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl
--- a/tests/out/msl/bits.msl
+++ b/tests/out/msl/bits.msl
@@ -3,85 +3,85 @@
#include <simd/simd.h>
-kernel void main1(
+kernel void main_(
) {
int i = 0;
- metal::int2 i2;
- metal::int3 i3;
- metal::int4 i4;
+ metal::int2 i2_;
+ metal::int3 i3_;
+ metal::int4 i4_;
metal::uint u = 0u;
- metal::uint2 u2;
- metal::uint3 u3;
- metal::uint4 u4;
- metal::float2 f2;
- metal::float4 f4;
- i2 = metal::int2(0);
- i3 = metal::int3(0);
- i4 = metal::int4(0);
- u2 = metal::uint2(0u);
- u3 = metal::uint3(0u);
- u4 = metal::uint4(0u);
- f2 = metal::float2(0.0);
- f4 = metal::float4(0.0);
- metal::float4 _e28 = f4;
+ metal::uint2 u2_;
+ metal::uint3 u3_;
+ metal::uint4 u4_;
+ metal::float2 f2_;
+ metal::float4 f4_;
+ i2_ = metal::int2(0);
+ i3_ = metal::int3(0);
+ i4_ = metal::int4(0);
+ u2_ = metal::uint2(0u);
+ u3_ = metal::uint3(0u);
+ u4_ = metal::uint4(0u);
+ f2_ = metal::float2(0.0);
+ f4_ = metal::float4(0.0);
+ metal::float4 _e28 = f4_;
u = metal::pack_float_to_unorm4x8(_e28);
- metal::float4 _e30 = f4;
+ metal::float4 _e30 = f4_;
u = metal::pack_float_to_snorm4x8(_e30);
- metal::float2 _e32 = f2;
+ metal::float2 _e32 = f2_;
u = metal::pack_float_to_unorm2x16(_e32);
- metal::float2 _e34 = f2;
+ metal::float2 _e34 = f2_;
u = metal::pack_float_to_snorm2x16(_e34);
- metal::float2 _e36 = f2;
+ metal::float2 _e36 = f2_;
u = as_type<uint>(half2(_e36));
metal::uint _e38 = u;
- f4 = metal::unpack_snorm4x8_to_float(_e38);
+ f4_ = metal::unpack_snorm4x8_to_float(_e38);
metal::uint _e40 = u;
- f4 = metal::unpack_unorm4x8_to_float(_e40);
+ f4_ = metal::unpack_unorm4x8_to_float(_e40);
metal::uint _e42 = u;
- f2 = metal::unpack_snorm2x16_to_float(_e42);
+ f2_ = metal::unpack_snorm2x16_to_float(_e42);
metal::uint _e44 = u;
- f2 = metal::unpack_unorm2x16_to_float(_e44);
+ f2_ = metal::unpack_unorm2x16_to_float(_e44);
metal::uint _e46 = u;
- f2 = float2(as_type<half2>(_e46));
+ f2_ = float2(as_type<half2>(_e46));
int _e48 = i;
int _e49 = i;
i = metal::insert_bits(_e48, _e49, 5u, 10u);
- metal::int2 _e53 = i2;
- metal::int2 _e54 = i2;
- i2 = metal::insert_bits(_e53, _e54, 5u, 10u);
- metal::int3 _e58 = i3;
- metal::int3 _e59 = i3;
- i3 = metal::insert_bits(_e58, _e59, 5u, 10u);
- metal::int4 _e63 = i4;
- metal::int4 _e64 = i4;
- i4 = metal::insert_bits(_e63, _e64, 5u, 10u);
+ metal::int2 _e53 = i2_;
+ metal::int2 _e54 = i2_;
+ i2_ = metal::insert_bits(_e53, _e54, 5u, 10u);
+ metal::int3 _e58 = i3_;
+ metal::int3 _e59 = i3_;
+ i3_ = metal::insert_bits(_e58, _e59, 5u, 10u);
+ metal::int4 _e63 = i4_;
+ metal::int4 _e64 = i4_;
+ i4_ = metal::insert_bits(_e63, _e64, 5u, 10u);
metal::uint _e68 = u;
metal::uint _e69 = u;
u = metal::insert_bits(_e68, _e69, 5u, 10u);
- metal::uint2 _e73 = u2;
- metal::uint2 _e74 = u2;
- u2 = metal::insert_bits(_e73, _e74, 5u, 10u);
- metal::uint3 _e78 = u3;
- metal::uint3 _e79 = u3;
- u3 = metal::insert_bits(_e78, _e79, 5u, 10u);
- metal::uint4 _e83 = u4;
- metal::uint4 _e84 = u4;
- u4 = metal::insert_bits(_e83, _e84, 5u, 10u);
+ metal::uint2 _e73 = u2_;
+ metal::uint2 _e74 = u2_;
+ u2_ = metal::insert_bits(_e73, _e74, 5u, 10u);
+ metal::uint3 _e78 = u3_;
+ metal::uint3 _e79 = u3_;
+ u3_ = metal::insert_bits(_e78, _e79, 5u, 10u);
+ metal::uint4 _e83 = u4_;
+ metal::uint4 _e84 = u4_;
+ u4_ = metal::insert_bits(_e83, _e84, 5u, 10u);
int _e88 = i;
i = metal::extract_bits(_e88, 5u, 10u);
- metal::int2 _e92 = i2;
- i2 = metal::extract_bits(_e92, 5u, 10u);
- metal::int3 _e96 = i3;
- i3 = metal::extract_bits(_e96, 5u, 10u);
- metal::int4 _e100 = i4;
- i4 = metal::extract_bits(_e100, 5u, 10u);
+ metal::int2 _e92 = i2_;
+ i2_ = metal::extract_bits(_e92, 5u, 10u);
+ metal::int3 _e96 = i3_;
+ i3_ = metal::extract_bits(_e96, 5u, 10u);
+ metal::int4 _e100 = i4_;
+ i4_ = metal::extract_bits(_e100, 5u, 10u);
metal::uint _e104 = u;
u = metal::extract_bits(_e104, 5u, 10u);
- metal::uint2 _e108 = u2;
- u2 = metal::extract_bits(_e108, 5u, 10u);
- metal::uint3 _e112 = u3;
- u3 = metal::extract_bits(_e112, 5u, 10u);
- metal::uint4 _e116 = u4;
- u4 = metal::extract_bits(_e116, 5u, 10u);
+ metal::uint2 _e108 = u2_;
+ u2_ = metal::extract_bits(_e108, 5u, 10u);
+ metal::uint3 _e112 = u3_;
+ u3_ = metal::extract_bits(_e112, 5u, 10u);
+ metal::uint4 _e116 = u4_;
+ u4_ = metal::extract_bits(_e116, 5u, 10u);
return;
}
diff --git a/tests/out/msl/boids.msl b/tests/out/msl/boids.msl
--- a/tests/out/msl/boids.msl
+++ b/tests/out/msl/boids.msl
@@ -21,14 +21,14 @@ struct SimParams {
float rule2Scale;
float rule3Scale;
};
-typedef Particle type3[1];
+typedef Particle type_3[1];
struct Particles {
- type3 particles;
+ type_3 particles;
};
-struct main1Input {
+struct main_Input {
};
-kernel void main1(
+kernel void main_(
metal::uint3 global_invocation_id [[thread_position_in_grid]]
, constant SimParams& params [[buffer(0)]]
, constant Particles& particlesSrc [[buffer(1)]]
diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl
--- a/tests/out/msl/collatz.msl
+++ b/tests/out/msl/collatz.msl
@@ -6,9 +6,9 @@ struct _mslBufferSizes {
metal::uint size0;
};
-typedef metal::uint type1[1];
+typedef metal::uint type_1[1];
struct PrimeIndices {
- type1 data;
+ type_1 data;
};
metal::uint collatz_iterations(
diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl
--- a/tests/out/msl/collatz.msl
+++ b/tests/out/msl/collatz.msl
@@ -37,9 +37,9 @@ metal::uint collatz_iterations(
return _e24;
}
-struct main1Input {
+struct main_Input {
};
-kernel void main1(
+kernel void main_(
metal::uint3 global_id [[thread_position_in_grid]]
, device PrimeIndices& v_indices [[user(fake0)]]
) {
diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl
--- a/tests/out/msl/control-flow.msl
+++ b/tests/out/msl/control-flow.msl
@@ -36,9 +36,9 @@ void loop_switch_continue(
return;
}
-struct main1Input {
+struct main_Input {
};
-kernel void main1(
+kernel void main_(
metal::uint3 global_id [[thread_position_in_grid]]
) {
int pos;
diff --git a/tests/out/msl/empty-global-name.msl b/tests/out/msl/empty-global-name.msl
--- a/tests/out/msl/empty-global-name.msl
+++ b/tests/out/msl/empty-global-name.msl
@@ -2,20 +2,20 @@
#include <metal_stdlib>
#include <simd/simd.h>
-struct type1 {
+struct type_1 {
int member;
};
void function(
- device type1& global
+ device type_1& unnamed
) {
- int _e8 = global.member;
- global.member = _e8 + 1;
+ int _e8 = unnamed.member;
+ unnamed.member = _e8 + 1;
return;
}
-kernel void main1(
- device type1& global [[user(fake0)]]
+kernel void main_(
+ device type_1& unnamed [[user(fake0)]]
) {
- function(global);
+ function(unnamed);
}
diff --git a/tests/out/msl/empty.msl b/tests/out/msl/empty.msl
--- a/tests/out/msl/empty.msl
+++ b/tests/out/msl/empty.msl
@@ -3,7 +3,7 @@
#include <simd/simd.h>
-kernel void main1(
+kernel void main_(
) {
return;
}
diff --git a/tests/out/msl/extra.msl b/tests/out/msl/extra.msl
--- a/tests/out/msl/extra.msl
+++ b/tests/out/msl/extra.msl
@@ -5,27 +5,27 @@
struct PushConstants {
metal::uint index;
char _pad1[12];
- metal::float2 double1;
+ metal::float2 double_;
};
struct FragmentIn {
metal::float4 color;
metal::uint primitive_index;
};
-struct main1Input {
+struct main_Input {
metal::float4 color [[user(loc0), center_perspective]];
};
-struct main1Output {
+struct main_Output {
metal::float4 member [[color(0)]];
};
-fragment main1Output main1(
- main1Input varyings [[stage_in]]
+fragment main_Output main_(
+ main_Input varyings [[stage_in]]
, metal::uint primitive_index [[primitive_id]]
) {
const FragmentIn in = { varyings.color, primitive_index };
if ((in.primitive_index % 2u) == 0u) {
- return main1Output { in.color };
+ return main_Output { in.color };
} else {
- return main1Output { metal::float4(metal::float3(1.0) - in.color.xyz, in.color.w) };
+ return main_Output { metal::float4(metal::float3(1.0) - in.color.xyz, in.color.w) };
}
}
diff --git a/tests/out/msl/globals.msl b/tests/out/msl/globals.msl
--- a/tests/out/msl/globals.msl
+++ b/tests/out/msl/globals.msl
@@ -3,12 +3,12 @@
#include <simd/simd.h>
constexpr constant bool Foo = true;
-struct type2 {
+struct type_2 {
float inner[10u];
};
-kernel void main1(
- threadgroup type2& wg
+kernel void main_(
+ threadgroup type_2& wg
, threadgroup metal::atomic_uint& at
) {
wg.inner[3] = 1.0;
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -2,11 +2,11 @@
#include <metal_stdlib>
#include <simd/simd.h>
-constant metal::int2 const_type8 = {3, 1};
+constant metal::int2 const_type_8_ = {3, 1};
-struct main1Input {
+struct main_Input {
};
-kernel void main1(
+kernel void main_(
metal::uint3 local_id [[thread_position_in_threadgroup]]
, metal::texture2d<uint, metal::access::sample> image_mipmapped_src [[user(fake0)]]
, metal::texture2d_ms<uint, metal::access::read> image_multisampled_src [[user(fake0)]]
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -16,11 +16,11 @@ kernel void main1(
) {
metal::int2 dim = int2(image_storage_src.get_width(), image_storage_src.get_height());
metal::int2 itc = (dim * static_cast<metal::int2>(local_id.xy)) % metal::int2(10, 20);
- metal::uint4 value1 = image_mipmapped_src.read(metal::uint2(itc), static_cast<int>(local_id.z));
- metal::uint4 value2 = image_multisampled_src.read(metal::uint2(itc), static_cast<int>(local_id.z));
- metal::uint4 value4 = image_storage_src.read(metal::uint2(itc));
- metal::uint4 value5 = image_array_src.read(metal::uint2(itc), static_cast<int>(local_id.z), static_cast<int>(local_id.z) + 1);
- image_dst.write(((value1 + value2) + value4) + value5, metal::uint(itc.x));
+ metal::uint4 value1_ = image_mipmapped_src.read(metal::uint2(itc), static_cast<int>(local_id.z));
+ metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast<int>(local_id.z));
+ metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc));
+ metal::uint4 value5_ = image_array_src.read(metal::uint2(itc), static_cast<int>(local_id.z), static_cast<int>(local_id.z) + 1);
+ image_dst.write(((value1_ + value2_) + value4_) + value5_, metal::uint(itc.x));
return;
}
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -28,21 +28,21 @@ kernel void main1(
struct depth_loadInput {
};
kernel void depth_load(
- metal::uint3 local_id1 [[thread_position_in_threadgroup]]
+ metal::uint3 local_id_1 [[thread_position_in_threadgroup]]
, metal::depth2d_ms<float, metal::access::read> image_depth_multisampled_src [[user(fake0)]]
, metal::texture2d<uint, metal::access::read> image_storage_src [[user(fake0)]]
, metal::texture1d<uint, metal::access::write> image_dst [[user(fake0)]]
) {
- metal::int2 dim1 = int2(image_storage_src.get_width(), image_storage_src.get_height());
- metal::int2 itc1 = (dim1 * static_cast<metal::int2>(local_id1.xy)) % metal::int2(10, 20);
- float val = image_depth_multisampled_src.read(metal::uint2(itc1), static_cast<int>(local_id1.z));
- image_dst.write(metal::uint4(static_cast<uint>(val)), metal::uint(itc1.x));
+ metal::int2 dim_1 = int2(image_storage_src.get_width(), image_storage_src.get_height());
+ metal::int2 itc_1 = (dim_1 * static_cast<metal::int2>(local_id_1.xy)) % metal::int2(10, 20);
+ float val = image_depth_multisampled_src.read(metal::uint2(itc_1), static_cast<int>(local_id_1.z));
+ image_dst.write(metal::uint4(static_cast<uint>(val)), metal::uint(itc_1.x));
return;
}
struct queriesOutput {
- metal::float4 member2 [[position]];
+ metal::float4 member_2 [[position]];
};
vertex queriesOutput queries(
metal::texture1d<float, metal::access::sample> image_1d [[user(fake0)]]
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -69,7 +69,7 @@ vertex queriesOutput queries(
struct levels_queriesOutput {
- metal::float4 member3 [[position]];
+ metal::float4 member_3 [[position]];
};
vertex levels_queriesOutput levels_queries(
metal::texture2d<float, metal::access::sample> image_2d [[user(fake0)]]
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -87,13 +87,13 @@ vertex levels_queriesOutput levels_queries(
int num_layers_cube = int(image_cube_array.get_array_size());
int num_levels_3d = int(image_3d.get_num_mip_levels());
int num_samples_aa = int(image_aa.get_num_samples());
- int sum1 = ((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array;
- return levels_queriesOutput { metal::float4(static_cast<float>(sum1)) };
+ int sum_1 = ((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array;
+ return levels_queriesOutput { metal::float4(static_cast<float>(sum_1)) };
}
struct sampleOutput {
- metal::float4 member4 [[color(0)]];
+ metal::float4 member_4 [[color(0)]];
};
fragment sampleOutput sample(
metal::texture1d<float, metal::access::sample> image_1d [[user(fake0)]]
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -103,22 +103,22 @@ fragment sampleOutput sample(
metal::float2 tc = metal::float2(0.5);
metal::float4 s1d = image_1d.sample(sampler_reg, tc.x);
metal::float4 s2d = image_2d.sample(sampler_reg, tc);
- metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type8);
+ metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type_8_);
metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284));
- metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type8);
+ metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_8_);
return sampleOutput { (((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset };
}
struct sample_comparisonOutput {
- float member5 [[color(0)]];
+ float member_5 [[color(0)]];
};
fragment sample_comparisonOutput sample_comparison(
metal::sampler sampler_cmp [[user(fake0)]]
, metal::depth2d<float, metal::access::sample> image_2d_depth [[user(fake0)]]
) {
- metal::float2 tc1 = metal::float2(0.5);
- float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc1, 0.5);
- float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc1, 0.5);
+ metal::float2 tc_1 = metal::float2(0.5);
+ float s2d_depth = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5);
+ float s2d_depth_level = image_2d_depth.sample_compare(sampler_cmp, tc_1, 0.5);
return sample_comparisonOutput { s2d_depth + s2d_depth_level };
}
diff --git a/tests/out/msl/interface.msl b/tests/out/msl/interface.msl
--- a/tests/out/msl/interface.msl
+++ b/tests/out/msl/interface.msl
@@ -11,61 +11,61 @@ struct FragmentOutput {
metal::uint sample_mask;
float color;
};
-struct type4 {
+struct type_4 {
metal::uint inner[1];
};
-struct vertex1Input {
+struct vertex_Input {
metal::uint color [[attribute(10)]];
};
-struct vertex1Output {
+struct vertex_Output {
metal::float4 position [[position]];
float varying [[user(loc1), center_perspective]];
};
-vertex vertex1Output vertex1(
- vertex1Input varyings [[stage_in]]
+vertex vertex_Output vertex_(
+ vertex_Input varyings [[stage_in]]
, metal::uint vertex_index [[vertex_id]]
, metal::uint instance_index [[instance_id]]
) {
const auto color = varyings.color;
metal::uint tmp = (vertex_index + instance_index) + color;
const auto _tmp = VertexOutput {metal::float4(1.0), static_cast<float>(tmp)};
- return vertex1Output { _tmp.position, _tmp.varying };
+ return vertex_Output { _tmp.position, _tmp.varying };
}
-struct fragment1Input {
+struct fragment_Input {
float varying [[user(loc1), center_perspective]];
};
-struct fragment1Output {
+struct fragment_Output {
float depth [[depth(any)]];
metal::uint sample_mask [[sample_mask]];
float color [[color(0)]];
};
-fragment fragment1Output fragment1(
- fragment1Input varyings1 [[stage_in]]
+fragment fragment_Output fragment_(
+ fragment_Input varyings_1 [[stage_in]]
, metal::float4 position [[position]]
, bool front_facing [[front_facing]]
, metal::uint sample_index [[sample_id]]
, metal::uint sample_mask [[sample_mask]]
) {
- const VertexOutput in = { position, varyings1.varying };
+ const VertexOutput in = { position, varyings_1.varying };
metal::uint mask = sample_mask & (1u << sample_index);
- float color1 = front_facing ? 1.0 : 0.0;
- const auto _tmp = FragmentOutput {in.varying, mask, color1};
- return fragment1Output { _tmp.depth, _tmp.sample_mask, _tmp.color };
+ float color_1 = front_facing ? 1.0 : 0.0;
+ const auto _tmp = FragmentOutput {in.varying, mask, color_1};
+ return fragment_Output { _tmp.depth, _tmp.sample_mask, _tmp.color };
}
-struct compute1Input {
+struct compute_Input {
};
-kernel void compute1(
+kernel void compute_(
metal::uint3 global_id [[thread_position_in_grid]]
, metal::uint3 local_id [[thread_position_in_threadgroup]]
, metal::uint local_index [[thread_index_in_threadgroup]]
, metal::uint3 wg_id [[threadgroup_position_in_grid]]
, metal::uint3 num_wgs [[threadgroups_per_grid]]
-, threadgroup type4& output
+, threadgroup type_4& output
) {
output.inner[0] = (((global_id.x + local_id.x) + local_index) + wg_id.x) + num_wgs.x;
return;
diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl
--- a/tests/out/msl/interpolate.msl
+++ b/tests/out/msl/interpolate.msl
@@ -13,7 +13,7 @@ struct FragmentInput {
float perspective_sample;
};
-struct main1Output {
+struct main_Output {
metal::float4 position [[position]];
metal::uint flat [[user(loc0), flat]];
float linear [[user(loc1), center_no_perspective]];
diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl
--- a/tests/out/msl/interpolate.msl
+++ b/tests/out/msl/interpolate.msl
@@ -23,7 +23,7 @@ struct main1Output {
float perspective_centroid [[user(loc5), centroid_perspective]];
float perspective_sample [[user(loc6), sample_perspective]];
};
-vertex main1Output main1(
+vertex main_Output main_(
) {
FragmentInput out;
out.position = metal::float4(2.0, 4.0, 5.0, 6.0);
diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl
--- a/tests/out/msl/interpolate.msl
+++ b/tests/out/msl/interpolate.msl
@@ -36,11 +36,11 @@ vertex main1Output main1(
out.perspective_sample = 2744.0;
FragmentInput _e30 = out;
const auto _tmp = _e30;
- return main1Output { _tmp.position, _tmp.flat, _tmp.linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample };
+ return main_Output { _tmp.position, _tmp.flat, _tmp.linear, _tmp.linear_centroid, _tmp.linear_sample, _tmp.perspective, _tmp.perspective_centroid, _tmp.perspective_sample };
}
-struct main2Input {
+struct main_1Input {
metal::uint flat [[user(loc0), flat]];
float linear [[user(loc1), center_no_perspective]];
metal::float2 linear_centroid [[user(loc2), centroid_no_perspective]];
diff --git a/tests/out/msl/interpolate.msl b/tests/out/msl/interpolate.msl
--- a/tests/out/msl/interpolate.msl
+++ b/tests/out/msl/interpolate.msl
@@ -49,10 +49,10 @@ struct main2Input {
float perspective_centroid [[user(loc5), centroid_perspective]];
float perspective_sample [[user(loc6), sample_perspective]];
};
-fragment void main2(
- main2Input varyings1 [[stage_in]]
+fragment void main_1(
+ main_1Input varyings_1 [[stage_in]]
, metal::float4 position [[position]]
) {
- const FragmentInput val = { position, varyings1.flat, varyings1.linear, varyings1.linear_centroid, varyings1.linear_sample, varyings1.perspective, varyings1.perspective_centroid, varyings1.perspective_sample };
+ const FragmentInput val = { position, varyings_1.flat, varyings_1.linear, varyings_1.linear_centroid, varyings_1.linear_sample, varyings_1.perspective, varyings_1.perspective_centroid, varyings_1.perspective_sample };
return;
}
diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl
--- a/tests/out/msl/operators.msl
+++ b/tests/out/msl/operators.msl
@@ -13,15 +13,15 @@ constant metal::int4 v_i32_one = {1, 1, 1, 1};
metal::float4 builtins(
) {
- int s1 = true ? 1 : 0;
- metal::float4 s2 = true ? v_f32_one : v_f32_zero;
- metal::float4 s3 = metal::select(v_f32_one, v_f32_zero, metal::bool4(false, false, false, false));
- metal::float4 m1 = metal::mix(v_f32_zero, v_f32_one, v_f32_half);
- metal::float4 m2 = metal::mix(v_f32_zero, v_f32_one, 0.10000000149011612);
- float b1 = as_type<float>(v_i32_one.x);
- metal::float4 b2 = as_type<metal::float4>(v_i32_one);
+ int s1_ = true ? 1 : 0;
+ metal::float4 s2_ = true ? v_f32_one : v_f32_zero;
+ metal::float4 s3_ = metal::select(v_f32_one, v_f32_zero, metal::bool4(false, false, false, false));
+ metal::float4 m1_ = metal::mix(v_f32_zero, v_f32_one, v_f32_half);
+ metal::float4 m2_ = metal::mix(v_f32_zero, v_f32_one, 0.10000000149011612);
+ float b1_ = as_type<float>(v_i32_one.x);
+ metal::float4 b2_ = as_type<metal::float4>(v_i32_one);
metal::int4 v_i32_zero = static_cast<metal::int4>(v_f32_zero);
- return ((((static_cast<metal::float4>(metal::int4(s1) + v_i32_zero) + s2) + m1) + m2) + metal::float4(b1)) + b2;
+ return ((((static_cast<metal::float4>(metal::int4(s1_) + v_i32_zero) + s2_) + m1_) + m2_) + metal::float4(b1_)) + b2_;
}
metal::float4 splat(
diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl
--- a/tests/out/msl/operators.msl
+++ b/tests/out/msl/operators.msl
@@ -57,13 +57,13 @@ float constructors(
void modulo(
) {
- int a1 = 1 % 1;
- float b1 = metal::fmod(1.0, 1.0);
+ int a_1 = 1 % 1;
+ float b_1 = metal::fmod(1.0, 1.0);
metal::int3 c = metal::int3(1) % metal::int3(1);
metal::float3 d = metal::fmod(metal::float3(1.0), metal::float3(1.0));
}
-kernel void main1(
+kernel void main_(
) {
metal::float4 _e4 = builtins();
metal::float4 _e5 = splat();
diff --git a/tests/out/msl/quad-vert.msl b/tests/out/msl/quad-vert.msl
--- a/tests/out/msl/quad-vert.msl
+++ b/tests/out/msl/quad-vert.msl
@@ -2,58 +2,58 @@
#include <metal_stdlib>
#include <simd/simd.h>
-struct type5 {
+struct type_5 {
float inner[1u];
};
struct gl_PerVertex {
metal::float4 gl_Position;
float gl_PointSize;
- type5 gl_ClipDistance;
- type5 gl_CullDistance;
+ type_5 gl_ClipDistance;
+ type_5 gl_CullDistance;
};
-struct type9 {
+struct type_9 {
metal::float2 member;
metal::float4 gl_Position;
};
-constant metal::float4 const_type3 = {0.0, 0.0, 0.0, 1.0};
-constant type5 const_type5 = {0.0};
-constant gl_PerVertex const_gl_PerVertex = {const_type3, 1.0, const_type5, const_type5};
+constant metal::float4 const_type_3_ = {0.0, 0.0, 0.0, 1.0};
+constant type_5 const_type_5_ = {0.0};
+constant gl_PerVertex const_gl_PerVertex = {const_type_3_, 1.0, const_type_5_, const_type_5_};
-void main2(
+void main_1(
thread metal::float2& v_uv,
- thread metal::float2 const& a_uv1,
+ thread metal::float2 const& a_uv_1,
thread gl_PerVertex& perVertexStruct,
- thread metal::float2 const& a_pos1
+ thread metal::float2 const& a_pos_1
) {
- metal::float2 _e12 = a_uv1;
+ metal::float2 _e12 = a_uv_1;
v_uv = _e12;
- metal::float2 _e13 = a_pos1;
+ metal::float2 _e13 = a_pos_1;
perVertexStruct.gl_Position = metal::float4(_e13.x, _e13.y, 0.0, 1.0);
return;
}
-struct main1Input {
+struct main_Input {
metal::float2 a_uv [[attribute(1)]];
metal::float2 a_pos [[attribute(0)]];
};
-struct main1Output {
+struct main_Output {
metal::float2 member [[user(loc0), center_perspective]];
metal::float4 gl_Position [[position]];
};
-vertex main1Output main1(
- main1Input varyings [[stage_in]]
+vertex main_Output main_(
+ main_Input varyings [[stage_in]]
) {
metal::float2 v_uv = {};
- metal::float2 a_uv1 = {};
+ metal::float2 a_uv_1 = {};
gl_PerVertex perVertexStruct = const_gl_PerVertex;
- metal::float2 a_pos1 = {};
+ metal::float2 a_pos_1 = {};
const auto a_uv = varyings.a_uv;
const auto a_pos = varyings.a_pos;
- a_uv1 = a_uv;
- a_pos1 = a_pos;
- main2(v_uv, a_uv1, perVertexStruct, a_pos1);
+ a_uv_1 = a_uv;
+ a_pos_1 = a_pos;
+ main_1(v_uv, a_uv_1, perVertexStruct, a_pos_1);
metal::float2 _e7 = v_uv;
metal::float4 _e8 = perVertexStruct.gl_Position;
- const auto _tmp = type9 {_e7, _e8};
- return main1Output { _tmp.member, _tmp.gl_Position };
+ const auto _tmp = type_9 {_e7, _e8};
+ return main_Output { _tmp.member, _tmp.gl_Position };
}
diff --git a/tests/out/msl/quad.msl b/tests/out/msl/quad.msl
--- a/tests/out/msl/quad.msl
+++ b/tests/out/msl/quad.msl
@@ -8,47 +8,47 @@ struct VertexOutput {
metal::float4 position;
};
-struct main1Input {
+struct main_Input {
metal::float2 pos [[attribute(0)]];
metal::float2 uv [[attribute(1)]];
};
-struct main1Output {
+struct main_Output {
metal::float2 uv [[user(loc0), center_perspective]];
metal::float4 position [[position]];
};
-vertex main1Output main1(
- main1Input varyings [[stage_in]]
+vertex main_Output main_(
+ main_Input varyings [[stage_in]]
) {
const auto pos = varyings.pos;
const auto uv = varyings.uv;
const auto _tmp = VertexOutput {uv, metal::float4(c_scale * pos, 0.0, 1.0)};
- return main1Output { _tmp.uv, _tmp.position };
+ return main_Output { _tmp.uv, _tmp.position };
}
-struct main2Input {
- metal::float2 uv1 [[user(loc0), center_perspective]];
+struct main_1Input {
+ metal::float2 uv_1 [[user(loc0), center_perspective]];
};
-struct main2Output {
- metal::float4 member1 [[color(0)]];
+struct main_1Output {
+ metal::float4 member_1 [[color(0)]];
};
-fragment main2Output main2(
- main2Input varyings1 [[stage_in]]
+fragment main_1Output main_1(
+ main_1Input varyings_1 [[stage_in]]
, metal::texture2d<float, metal::access::sample> u_texture [[user(fake0)]]
, metal::sampler u_sampler [[user(fake0)]]
) {
- const auto uv1 = varyings1.uv1;
- metal::float4 color = u_texture.sample(u_sampler, uv1);
+ const auto uv_1 = varyings_1.uv_1;
+ metal::float4 color = u_texture.sample(u_sampler, uv_1);
if (color.w == 0.0) {
metal::discard_fragment();
}
metal::float4 premultiplied = color.w * color;
- return main2Output { premultiplied };
+ return main_1Output { premultiplied };
}
struct fs_extraOutput {
- metal::float4 member2 [[color(0)]];
+ metal::float4 member_2 [[color(0)]];
};
fragment fs_extraOutput fs_extra(
) {
diff --git a/tests/out/msl/shadow.msl b/tests/out/msl/shadow.msl
--- a/tests/out/msl/shadow.msl
+++ b/tests/out/msl/shadow.msl
@@ -15,9 +15,9 @@ struct Light {
metal::float4 pos;
metal::float4 color;
};
-typedef Light type3[1];
+typedef Light type_3[1];
struct Lights {
- type3 data;
+ type_3 data;
};
constant metal::float3 c_ambient = {0.05000000074505806, 0.05000000074505806, 0.05000000074505806};
diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl
--- a/tests/out/msl/skybox.msl
+++ b/tests/out/msl/skybox.msl
@@ -21,12 +21,12 @@ vertex vs_mainOutput vs_main(
metal::uint vertex_index [[vertex_id]]
, constant Data& r_data [[buffer(0)]]
) {
- int tmp1;
- int tmp2;
- tmp1 = static_cast<int>(vertex_index) / 2;
- tmp2 = static_cast<int>(vertex_index) & 1;
- int _e10 = tmp1;
- int _e16 = tmp2;
+ int tmp1_;
+ int tmp2_;
+ tmp1_ = static_cast<int>(vertex_index) / 2;
+ tmp2_ = static_cast<int>(vertex_index) & 1;
+ int _e10 = tmp1_;
+ int _e16 = tmp2_;
metal::float4 pos = metal::float4((static_cast<float>(_e10) * 4.0) - 1.0, (static_cast<float>(_e16) * 4.0) - 1.0, 0.0, 1.0);
metal::float4 _e27 = r_data.view[0];
metal::float4 _e31 = r_data.view[1];
diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl
--- a/tests/out/msl/skybox.msl
+++ b/tests/out/msl/skybox.msl
@@ -43,10 +43,10 @@ struct fs_mainInput {
metal::float3 uv [[user(loc0), center_perspective]];
};
struct fs_mainOutput {
- metal::float4 member1 [[color(0)]];
+ metal::float4 member_1 [[color(0)]];
};
fragment fs_mainOutput fs_main(
- fs_mainInput varyings1 [[stage_in]]
+ fs_mainInput varyings_1 [[stage_in]]
, metal::float4 position [[position]]
, metal::texturecube<float, metal::access::sample> r_texture [[texture(0)]]
) {
diff --git a/tests/out/msl/skybox.msl b/tests/out/msl/skybox.msl
--- a/tests/out/msl/skybox.msl
+++ b/tests/out/msl/skybox.msl
@@ -58,7 +58,7 @@ fragment fs_mainOutput fs_main(
metal::min_filter::linear,
metal::coord::normalized
);
- const VertexOutput in = { position, varyings1.uv };
+ const VertexOutput in = { position, varyings_1.uv };
metal::float4 _e5 = r_texture.sample(r_sampler, in.uv);
return fs_mainOutput { _e5 };
}
diff --git a/tests/out/msl/texture-arg.msl b/tests/out/msl/texture-arg.msl
--- a/tests/out/msl/texture-arg.msl
+++ b/tests/out/msl/texture-arg.msl
@@ -11,13 +11,13 @@ metal::float4 test(
return _e7;
}
-struct main1Output {
+struct main_Output {
metal::float4 member [[color(0)]];
};
-fragment main1Output main1(
+fragment main_Output main_(
metal::texture2d<float, metal::access::sample> Texture [[user(fake0)]]
, metal::sampler Sampler [[user(fake0)]]
) {
metal::float4 _e2 = test(Texture, Sampler);
- return main1Output { _e2 };
+ return main_Output { _e2 };
}
diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
--- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
+++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
@@ -7,12 +7,12 @@ struct FragmentOutput {
[[location(0)]] o_Target: vec4<f32>;
};
-var<private> v_Uv1: vec2<f32>;
+var<private> v_Uv_1: vec2<f32>;
var<private> o_Target: vec4<f32>;
[[group(1), binding(0)]]
var<uniform> global: ColorMaterial_color;
-fn main1() {
+fn main_1() {
var color: vec4<f32>;
let e4: vec4<f32> = global.Color;
diff --git a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
--- a/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
+++ b/tests/out/wgsl/210-bevy-2d-shader-frag.wgsl
@@ -24,8 +24,8 @@ fn main1() {
[[stage(fragment)]]
fn main([[location(0)]] v_Uv: vec2<f32>) -> FragmentOutput {
- v_Uv1 = v_Uv;
- main1();
+ v_Uv_1 = v_Uv;
+ main_1();
let e9: vec4<f32> = o_Target;
return FragmentOutput(e9);
}
diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
--- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
+++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
@@ -18,28 +18,28 @@ struct VertexOutput {
[[builtin(position)]] member: vec4<f32>;
};
-var<private> Vertex_Position1: vec3<f32>;
-var<private> Vertex_Normal1: vec3<f32>;
-var<private> Vertex_Uv1: vec2<f32>;
+var<private> Vertex_Position_1: vec3<f32>;
+var<private> Vertex_Normal_1: vec3<f32>;
+var<private> Vertex_Uv_1: vec2<f32>;
var<private> v_Uv: vec2<f32>;
[[group(0), binding(0)]]
var<uniform> global: Camera;
[[group(2), binding(0)]]
-var<uniform> global1: Transform;
+var<uniform> global_1: Transform;
[[group(2), binding(1)]]
-var<uniform> global2: Sprite_size;
+var<uniform> global_2: Sprite_size;
var<private> gl_Position: vec4<f32>;
-fn main1() {
+fn main_1() {
var position: vec3<f32>;
- let e10: vec2<f32> = Vertex_Uv1;
+ let e10: vec2<f32> = Vertex_Uv_1;
v_Uv = e10;
- let e11: vec3<f32> = Vertex_Position1;
- let e12: vec2<f32> = global2.size;
+ let e11: vec3<f32> = Vertex_Position_1;
+ let e12: vec2<f32> = global_2.size;
position = (e11 * vec3<f32>(e12, 1.0));
let e18: mat4x4<f32> = global.ViewProj;
- let e19: mat4x4<f32> = global1.Model;
+ let e19: mat4x4<f32> = global_1.Model;
let e21: vec3<f32> = position;
gl_Position = ((e18 * e19) * vec4<f32>(e21, 1.0));
return;
diff --git a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
--- a/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
+++ b/tests/out/wgsl/210-bevy-2d-shader-vert.wgsl
@@ -47,10 +47,10 @@ fn main1() {
[[stage(vertex)]]
fn main([[location(0)]] Vertex_Position: vec3<f32>, [[location(1)]] Vertex_Normal: vec3<f32>, [[location(2)]] Vertex_Uv: vec2<f32>) -> VertexOutput {
- Vertex_Position1 = Vertex_Position;
- Vertex_Normal1 = Vertex_Normal;
- Vertex_Uv1 = Vertex_Uv;
- main1();
+ Vertex_Position_1 = Vertex_Position;
+ Vertex_Normal_1 = Vertex_Normal;
+ Vertex_Uv_1 = Vertex_Uv;
+ main_1();
let e21: vec2<f32> = v_Uv;
let e23: vec4<f32> = gl_Position;
return VertexOutput(e21, e23);
diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl
--- a/tests/out/wgsl/210-bevy-shader-vert.wgsl
+++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl
@@ -15,29 +15,29 @@ struct VertexOutput {
[[builtin(position)]] member: vec4<f32>;
};
-var<private> Vertex_Position1: vec3<f32>;
-var<private> Vertex_Normal1: vec3<f32>;
-var<private> Vertex_Uv1: vec2<f32>;
+var<private> Vertex_Position_1: vec3<f32>;
+var<private> Vertex_Normal_1: vec3<f32>;
+var<private> Vertex_Uv_1: vec2<f32>;
var<private> v_Position: vec3<f32>;
var<private> v_Normal: vec3<f32>;
var<private> v_Uv: vec2<f32>;
[[group(0), binding(0)]]
var<uniform> global: Camera;
[[group(2), binding(0)]]
-var<uniform> global1: Transform;
+var<uniform> global_1: Transform;
var<private> gl_Position: vec4<f32>;
-fn main1() {
- let e10: mat4x4<f32> = global1.Model;
- let e11: vec3<f32> = Vertex_Normal1;
+fn main_1() {
+ let e10: mat4x4<f32> = global_1.Model;
+ let e11: vec3<f32> = Vertex_Normal_1;
v_Normal = (e10 * vec4<f32>(e11, 1.0)).xyz;
- let e16: mat4x4<f32> = global1.Model;
- let e24: vec3<f32> = Vertex_Normal1;
+ let e16: mat4x4<f32> = global_1.Model;
+ let e24: vec3<f32> = Vertex_Normal_1;
v_Normal = (mat3x3<f32>(e16[0].xyz, e16[1].xyz, e16[2].xyz) * e24);
- let e26: mat4x4<f32> = global1.Model;
- let e27: vec3<f32> = Vertex_Position1;
+ let e26: mat4x4<f32> = global_1.Model;
+ let e27: vec3<f32> = Vertex_Position_1;
v_Position = (e26 * vec4<f32>(e27, 1.0)).xyz;
- let e32: vec2<f32> = Vertex_Uv1;
+ let e32: vec2<f32> = Vertex_Uv_1;
v_Uv = e32;
let e34: mat4x4<f32> = global.ViewProj;
let e35: vec3<f32> = v_Position;
diff --git a/tests/out/wgsl/210-bevy-shader-vert.wgsl b/tests/out/wgsl/210-bevy-shader-vert.wgsl
--- a/tests/out/wgsl/210-bevy-shader-vert.wgsl
+++ b/tests/out/wgsl/210-bevy-shader-vert.wgsl
@@ -47,10 +47,10 @@ fn main1() {
[[stage(vertex)]]
fn main([[location(0)]] Vertex_Position: vec3<f32>, [[location(1)]] Vertex_Normal: vec3<f32>, [[location(2)]] Vertex_Uv: vec2<f32>) -> VertexOutput {
- Vertex_Position1 = Vertex_Position;
- Vertex_Normal1 = Vertex_Normal;
- Vertex_Uv1 = Vertex_Uv;
- main1();
+ Vertex_Position_1 = Vertex_Position;
+ Vertex_Normal_1 = Vertex_Normal;
+ Vertex_Uv_1 = Vertex_Uv;
+ main_1();
let e23: vec3<f32> = v_Position;
let e25: vec3<f32> = v_Normal;
let e27: vec2<f32> = v_Uv;
diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl
--- a/tests/out/wgsl/246-collatz-comp.wgsl
+++ b/tests/out/wgsl/246-collatz-comp.wgsl
@@ -8,26 +8,26 @@ var<storage, read_write> global: PrimeIndices;
var<private> gl_GlobalInvocationID: vec3<u32>;
fn collatz_iterations(n: u32) -> u32 {
- var n1: u32;
+ var n_1: u32;
var i: u32 = 0u;
- n1 = n;
+ n_1 = n;
loop {
- let e7: u32 = n1;
+ let e7: u32 = n_1;
if (!((e7 != u32(1)))) {
break;
}
{
- let e14: u32 = n1;
+ let e14: u32 = n_1;
if (((f32(e14) % f32(2)) == f32(0))) {
{
- let e22: u32 = n1;
- n1 = (e22 / u32(2));
+ let e22: u32 = n_1;
+ n_1 = (e22 / u32(2));
}
} else {
{
- let e27: u32 = n1;
- n1 = ((u32(3) * e27) + u32(1));
+ let e27: u32 = n_1;
+ n_1 = ((u32(3) * e27) + u32(1));
}
}
let e33: u32 = i;
diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl
--- a/tests/out/wgsl/246-collatz-comp.wgsl
+++ b/tests/out/wgsl/246-collatz-comp.wgsl
@@ -38,7 +38,7 @@ fn collatz_iterations(n: u32) -> u32 {
return e36;
}
-fn main1() {
+fn main_1() {
var index: u32;
let e3: vec3<u32> = gl_GlobalInvocationID;
diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl
--- a/tests/out/wgsl/246-collatz-comp.wgsl
+++ b/tests/out/wgsl/246-collatz-comp.wgsl
@@ -55,6 +55,6 @@ fn main1() {
[[stage(compute), workgroup_size(1, 1, 1)]]
fn main([[builtin(global_invocation_id)]] param: vec3<u32>) {
gl_GlobalInvocationID = param;
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/277-casting-vert.wgsl b/tests/out/wgsl/277-casting-vert.wgsl
--- a/tests/out/wgsl/277-casting-vert.wgsl
+++ b/tests/out/wgsl/277-casting-vert.wgsl
@@ -1,10 +1,10 @@
-fn main1() {
+fn main_1() {
var a: f32 = 1.0;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl
--- a/tests/out/wgsl/280-matrix-cast-vert.wgsl
+++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var a: mat4x4<f32> = mat4x4<f32>(vec4<f32>(1.0, 0.0, 0.0, 0.0), vec4<f32>(0.0, 1.0, 0.0, 0.0), vec4<f32>(0.0, 0.0, 1.0, 0.0), vec4<f32>(0.0, 0.0, 0.0, 1.0));
let e1: f32 = f32(1);
diff --git a/tests/out/wgsl/280-matrix-cast-vert.wgsl b/tests/out/wgsl/280-matrix-cast-vert.wgsl
--- a/tests/out/wgsl/280-matrix-cast-vert.wgsl
+++ b/tests/out/wgsl/280-matrix-cast-vert.wgsl
@@ -6,6 +6,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/484-preprocessor-if-vert.wgsl b/tests/out/wgsl/484-preprocessor-if-vert.wgsl
--- a/tests/out/wgsl/484-preprocessor-if-vert.wgsl
+++ b/tests/out/wgsl/484-preprocessor-if-vert.wgsl
@@ -1,9 +1,9 @@
-fn main1() {
+fn main_1() {
return;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
--- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
+++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
@@ -15,18 +15,18 @@ struct VertexOutput {
[[group(0), binding(0)]]
var<uniform> global: Globals;
-var<push_constant> global1: VertexPushConstants;
-var<private> position1: vec2<f32>;
-var<private> color1: vec4<f32>;
+var<push_constant> global_1: VertexPushConstants;
+var<private> position_1: vec2<f32>;
+var<private> color_1: vec4<f32>;
var<private> frag_color: vec4<f32>;
var<private> gl_Position: vec4<f32>;
-fn main1() {
- let e7: vec4<f32> = color1;
+fn main_1() {
+ let e7: vec4<f32> = color_1;
frag_color = e7;
let e9: mat4x4<f32> = global.view_matrix;
- let e10: mat4x4<f32> = global1.world_matrix;
- let e12: vec2<f32> = position1;
+ let e10: mat4x4<f32> = global_1.world_matrix;
+ let e12: vec2<f32> = position_1;
gl_Position = ((e9 * e10) * vec4<f32>(e12, 0.0, 1.0));
let e18: vec4<f32> = gl_Position;
let e20: vec4<f32> = gl_Position;
diff --git a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
--- a/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
+++ b/tests/out/wgsl/800-out-of-bounds-panic-vert.wgsl
@@ -36,9 +36,9 @@ fn main1() {
[[stage(vertex)]]
fn main([[location(0)]] position: vec2<f32>, [[location(1)]] color: vec4<f32>) -> VertexOutput {
- position1 = position;
- color1 = color;
- main1();
+ position_1 = position;
+ color_1 = color;
+ main_1();
let e15: vec4<f32> = frag_color;
let e17: vec4<f32> = gl_Position;
return VertexOutput(e15, e17);
diff --git a/tests/out/wgsl/896-push-constant-vert.wgsl b/tests/out/wgsl/896-push-constant-vert.wgsl
--- a/tests/out/wgsl/896-push-constant-vert.wgsl
+++ b/tests/out/wgsl/896-push-constant-vert.wgsl
@@ -5,12 +5,12 @@ struct PushConstants {
var<push_constant> c: PushConstants;
-fn main1() {
+fn main_1() {
return;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/900-implicit-conversions-vert.wgsl b/tests/out/wgsl/900-implicit-conversions-vert.wgsl
--- a/tests/out/wgsl/900-implicit-conversions-vert.wgsl
+++ b/tests/out/wgsl/900-implicit-conversions-vert.wgsl
@@ -1,68 +1,68 @@
fn exact(a: f32) {
- var a1: f32;
+ var a_1: f32;
- a1 = a;
+ a_1 = a;
return;
}
-fn exact1(a2: i32) {
- var a3: i32;
+fn exact_1(a_2: i32) {
+ var a_3: i32;
- a3 = a2;
+ a_3 = a_2;
return;
}
-fn implicit(a4: f32) {
- var a5: f32;
+fn implicit(a_4: f32) {
+ var a_5: f32;
- a5 = a4;
+ a_5 = a_4;
return;
}
-fn implicit1(a6: i32) {
- var a7: i32;
+fn implicit_1(a_6: i32) {
+ var a_7: i32;
- a7 = a6;
+ a_7 = a_6;
return;
}
fn implicit_dims(v: f32) {
- var v1: f32;
+ var v_1: f32;
- v1 = v;
+ v_1 = v;
return;
}
-fn implicit_dims1(v2: vec2<f32>) {
- var v3: vec2<f32>;
+fn implicit_dims_1(v_2: vec2<f32>) {
+ var v_3: vec2<f32>;
- v3 = v2;
+ v_3 = v_2;
return;
}
-fn implicit_dims2(v4: vec3<f32>) {
- var v5: vec3<f32>;
+fn implicit_dims_2(v_4: vec3<f32>) {
+ var v_5: vec3<f32>;
- v5 = v4;
+ v_5 = v_4;
return;
}
-fn implicit_dims3(v6: vec4<f32>) {
- var v7: vec4<f32>;
+fn implicit_dims_3(v_6: vec4<f32>) {
+ var v_7: vec4<f32>;
- v7 = v6;
+ v_7 = v_6;
return;
}
-fn main1() {
- exact1(1);
+fn main_1() {
+ exact_1(1);
implicit(f32(1u));
- implicit_dims2(vec3<f32>(vec3<i32>(1)));
+ implicit_dims_2(vec3<f32>(vec3<i32>(1)));
return;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/901-lhs-field-select-vert.wgsl b/tests/out/wgsl/901-lhs-field-select-vert.wgsl
--- a/tests/out/wgsl/901-lhs-field-select-vert.wgsl
+++ b/tests/out/wgsl/901-lhs-field-select-vert.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var a: vec4<f32> = vec4<f32>(1.0, 1.0, 1.0, 1.0);
a.x = 2.0;
diff --git a/tests/out/wgsl/901-lhs-field-select-vert.wgsl b/tests/out/wgsl/901-lhs-field-select-vert.wgsl
--- a/tests/out/wgsl/901-lhs-field-select-vert.wgsl
+++ b/tests/out/wgsl/901-lhs-field-select-vert.wgsl
@@ -7,6 +7,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/931-constant-emitting-vert.wgsl b/tests/out/wgsl/931-constant-emitting-vert.wgsl
--- a/tests/out/wgsl/931-constant-emitting-vert.wgsl
+++ b/tests/out/wgsl/931-constant-emitting-vert.wgsl
@@ -1,13 +1,13 @@
-fn function1() -> f32 {
+fn function_() -> f32 {
return 0.0;
}
-fn main1() {
+fn main_1() {
return;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl
--- a/tests/out/wgsl/932-for-loop-if-vert.wgsl
+++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var i: i32 = 0;
loop {
diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl
--- a/tests/out/wgsl/932-for-loop-if-vert.wgsl
+++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl
@@ -18,6 +18,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl
--- a/tests/out/wgsl/access.wgsl
+++ b/tests/out/wgsl/access.wgsl
@@ -9,24 +9,24 @@ struct Bar {
[[group(0), binding(0)]]
var<storage, read_write> bar: Bar;
-fn read_from_private(foo2: ptr<function, f32>) -> f32 {
- let e2: f32 = (*foo2);
+fn read_from_private(foo_2: ptr<function, f32>) -> f32 {
+ let e2: f32 = (*foo_2);
return e2;
}
[[stage(vertex)]]
fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4<f32> {
- var foo1: f32 = 0.0;
+ var foo_1: f32 = 0.0;
var c: array<i32,5>;
- let baz: f32 = foo1;
- foo1 = 1.0;
+ let baz: f32 = foo_1;
+ foo_1 = 1.0;
let matrix: mat4x4<f32> = bar.matrix;
let arr: array<vec2<u32>,2> = bar.arr;
let b: f32 = bar.matrix[3][0];
let a: i32 = bar.data[(arrayLength((&bar.data)) - 2u)];
- let pointer1: ptr<storage, i32, read_write> = (&bar.data[0]);
- let e25: f32 = read_from_private((&foo1));
+ let pointer_: ptr<storage, i32, read_write> = (&bar.data[0]);
+ let e25: f32 = read_from_private((&foo_1));
bar.matrix[1][2] = 1.0;
bar.matrix = mat4x4<f32>(vec4<f32>(0.0), vec4<f32>(1.0), vec4<f32>(2.0), vec4<f32>(3.0));
bar.arr = array<vec2<u32>,2>(vec2<u32>(0u), vec2<u32>(1u));
diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl
--- a/tests/out/wgsl/access.wgsl
+++ b/tests/out/wgsl/access.wgsl
@@ -41,7 +41,7 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4<f32> {
fn atomics() {
var tmp: i32;
- let value1: i32 = atomicLoad((&bar.atom));
+ let value_1: i32 = atomicLoad((&bar.atom));
let e6: i32 = atomicAdd((&bar.atom), 5);
tmp = e6;
let e9: i32 = atomicSub((&bar.atom), 5);
diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl
--- a/tests/out/wgsl/access.wgsl
+++ b/tests/out/wgsl/access.wgsl
@@ -58,6 +58,6 @@ fn atomics() {
tmp = e24;
let e27: i32 = atomicExchange((&bar.atom), 5);
tmp = e27;
- atomicStore((&bar.atom), value1);
+ atomicStore((&bar.atom), value_1);
return;
}
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -56,33 +56,33 @@ struct FragmentOutput {
[[location(0)]] o_Target: vec4<f32>;
};
-var<private> v_WorldPosition1: vec3<f32>;
-var<private> v_WorldNormal1: vec3<f32>;
-var<private> v_Uv1: vec2<f32>;
-var<private> v_WorldTangent1: vec4<f32>;
+var<private> v_WorldPosition_1: vec3<f32>;
+var<private> v_WorldNormal_1: vec3<f32>;
+var<private> v_Uv_1: vec2<f32>;
+var<private> v_WorldTangent_1: vec4<f32>;
var<private> o_Target: vec4<f32>;
[[group(0), binding(0)]]
var<uniform> global: CameraViewProj;
[[group(0), binding(1)]]
-var<uniform> global1: CameraPosition;
+var<uniform> global_1: CameraPosition;
[[group(1), binding(0)]]
-var<uniform> global2: Lights;
+var<uniform> global_2: Lights;
[[group(3), binding(0)]]
-var<uniform> global3: StandardMaterial_base_color;
+var<uniform> global_3: StandardMaterial_base_color;
[[group(3), binding(1)]]
var StandardMaterial_base_color_texture: texture_2d<f32>;
[[group(3), binding(2)]]
var StandardMaterial_base_color_texture_sampler: sampler;
[[group(3), binding(3)]]
-var<uniform> global4: StandardMaterial_roughness;
+var<uniform> global_4: StandardMaterial_roughness;
[[group(3), binding(4)]]
-var<uniform> global5: StandardMaterial_metallic;
+var<uniform> global_5: StandardMaterial_metallic;
[[group(3), binding(5)]]
var StandardMaterial_metallic_roughness_texture: texture_2d<f32>;
[[group(3), binding(6)]]
var StandardMaterial_metallic_roughness_texture_sampler: sampler;
[[group(3), binding(7)]]
-var<uniform> global6: StandardMaterial_reflectance;
+var<uniform> global_6: StandardMaterial_reflectance;
[[group(3), binding(8)]]
var StandardMaterial_normal_map: texture_2d<f32>;
[[group(3), binding(9)]]
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -92,38 +92,38 @@ var StandardMaterial_occlusion_texture: texture_2d<f32>;
[[group(3), binding(11)]]
var StandardMaterial_occlusion_texture_sampler: sampler;
[[group(3), binding(12)]]
-var<uniform> global7: StandardMaterial_emissive;
+var<uniform> global_7: StandardMaterial_emissive;
[[group(3), binding(13)]]
var StandardMaterial_emissive_texture: texture_2d<f32>;
[[group(3), binding(14)]]
var StandardMaterial_emissive_texture_sampler: sampler;
var<private> gl_FrontFacing: bool;
-fn pow5(x: f32) -> f32 {
- var x1: f32;
- var x2: f32;
-
- x1 = x;
- let e42: f32 = x1;
- let e43: f32 = x1;
- x2 = (e42 * e43);
- let e46: f32 = x2;
- let e47: f32 = x2;
- let e49: f32 = x1;
+fn pow5_(x: f32) -> f32 {
+ var x_1: f32;
+ var x2_: f32;
+
+ x_1 = x;
+ let e42: f32 = x_1;
+ let e43: f32 = x_1;
+ x2_ = (e42 * e43);
+ let e46: f32 = x2_;
+ let e47: f32 = x2_;
+ let e49: f32 = x_1;
return ((e46 * e47) * e49);
}
fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32 {
- var distanceSquare1: f32;
- var inverseRangeSquared1: f32;
+ var distanceSquare_1: f32;
+ var inverseRangeSquared_1: f32;
var factor: f32;
var smoothFactor: f32;
var attenuation: f32;
- distanceSquare1 = distanceSquare;
- inverseRangeSquared1 = inverseRangeSquared;
- let e44: f32 = distanceSquare1;
- let e45: f32 = inverseRangeSquared1;
+ distanceSquare_1 = distanceSquare;
+ inverseRangeSquared_1 = inverseRangeSquared;
+ let e44: f32 = distanceSquare_1;
+ let e45: f32 = inverseRangeSquared_1;
factor = (e44 * e45);
let e49: f32 = factor;
let e50: f32 = factor;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -134,27 +134,27 @@ fn getDistanceAttenuation(distanceSquare: f32, inverseRangeSquared: f32) -> f32
let e65: f32 = smoothFactor;
attenuation = (e64 * e65);
let e68: f32 = attenuation;
- let e73: f32 = distanceSquare1;
+ let e73: f32 = distanceSquare_1;
return ((e68 * 1.0) / max(e73, 0.0010000000474974513));
}
fn D_GGX(roughness: f32, NoH: f32, h: vec3<f32>) -> f32 {
- var roughness1: f32;
- var NoH1: f32;
+ var roughness_1: f32;
+ var NoH_1: f32;
var oneMinusNoHSquared: f32;
var a: f32;
var k: f32;
var d: f32;
- roughness1 = roughness;
- NoH1 = NoH;
- let e46: f32 = NoH1;
- let e47: f32 = NoH1;
+ roughness_1 = roughness;
+ NoH_1 = NoH;
+ let e46: f32 = NoH_1;
+ let e47: f32 = NoH_1;
oneMinusNoHSquared = (1.0 - (e46 * e47));
- let e51: f32 = NoH1;
- let e52: f32 = roughness1;
+ let e51: f32 = NoH_1;
+ let e52: f32 = roughness_1;
a = (e51 * e52);
- let e55: f32 = roughness1;
+ let e55: f32 = roughness_1;
let e56: f32 = oneMinusNoHSquared;
let e57: f32 = a;
let e58: f32 = a;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -166,44 +166,44 @@ fn D_GGX(roughness: f32, NoH: f32, h: vec3<f32>) -> f32 {
return e70;
}
-fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 {
- var roughness3: f32;
- var NoV1: f32;
- var NoL1: f32;
- var a2: f32;
+fn V_SmithGGXCorrelated(roughness_2: f32, NoV: f32, NoL: f32) -> f32 {
+ var roughness_3: f32;
+ var NoV_1: f32;
+ var NoL_1: f32;
+ var a2_: f32;
var lambdaV: f32;
var lambdaL: f32;
var v: f32;
- roughness3 = roughness2;
- NoV1 = NoV;
- NoL1 = NoL;
- let e46: f32 = roughness3;
- let e47: f32 = roughness3;
- a2 = (e46 * e47);
- let e50: f32 = NoL1;
- let e51: f32 = NoV1;
- let e52: f32 = a2;
- let e53: f32 = NoV1;
- let e56: f32 = NoV1;
- let e58: f32 = a2;
- let e60: f32 = NoV1;
- let e61: f32 = a2;
- let e62: f32 = NoV1;
- let e65: f32 = NoV1;
- let e67: f32 = a2;
+ roughness_3 = roughness_2;
+ NoV_1 = NoV;
+ NoL_1 = NoL;
+ let e46: f32 = roughness_3;
+ let e47: f32 = roughness_3;
+ a2_ = (e46 * e47);
+ let e50: f32 = NoL_1;
+ let e51: f32 = NoV_1;
+ let e52: f32 = a2_;
+ let e53: f32 = NoV_1;
+ let e56: f32 = NoV_1;
+ let e58: f32 = a2_;
+ let e60: f32 = NoV_1;
+ let e61: f32 = a2_;
+ let e62: f32 = NoV_1;
+ let e65: f32 = NoV_1;
+ let e67: f32 = a2_;
lambdaV = (e50 * sqrt((((e60 - (e61 * e62)) * e65) + e67)));
- let e72: f32 = NoV1;
- let e73: f32 = NoL1;
- let e74: f32 = a2;
- let e75: f32 = NoL1;
- let e78: f32 = NoL1;
- let e80: f32 = a2;
- let e82: f32 = NoL1;
- let e83: f32 = a2;
- let e84: f32 = NoL1;
- let e87: f32 = NoL1;
- let e89: f32 = a2;
+ let e72: f32 = NoV_1;
+ let e73: f32 = NoL_1;
+ let e74: f32 = a2_;
+ let e75: f32 = NoL_1;
+ let e78: f32 = NoL_1;
+ let e80: f32 = a2_;
+ let e82: f32 = NoL_1;
+ let e83: f32 = a2_;
+ let e84: f32 = NoL_1;
+ let e87: f32 = NoL_1;
+ let e89: f32 = a2_;
lambdaL = (e72 * sqrt((((e82 - (e83 * e84)) * e87) + e89)));
let e95: f32 = lambdaV;
let e96: f32 = lambdaL;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -212,151 +212,151 @@ fn V_SmithGGXCorrelated(roughness2: f32, NoV: f32, NoL: f32) -> f32 {
return e100;
}
-fn F_Schlick(f0: vec3<f32>, f90: f32, VoH: f32) -> vec3<f32> {
+fn F_Schlick(f0_: vec3<f32>, f90_: f32, VoH: f32) -> vec3<f32> {
var f90_1: f32;
- var VoH1: f32;
+ var VoH_1: f32;
- f90_1 = f90;
- VoH1 = VoH;
+ f90_1 = f90_;
+ VoH_1 = VoH;
let e45: f32 = f90_1;
- let e49: f32 = VoH1;
- let e52: f32 = VoH1;
- let e54: f32 = pow5((1.0 - e52));
- return (f0 + ((vec3<f32>(e45) - f0) * e54));
+ let e49: f32 = VoH_1;
+ let e52: f32 = VoH_1;
+ let e54: f32 = pow5_((1.0 - e52));
+ return (f0_ + ((vec3<f32>(e45) - f0_) * e54));
}
-fn F_Schlick1(f0_1: f32, f90_2: f32, VoH2: f32) -> f32 {
+fn F_Schlick_1(f0_1: f32, f90_2: f32, VoH_2: f32) -> f32 {
var f0_2: f32;
var f90_3: f32;
- var VoH3: f32;
+ var VoH_3: f32;
f0_2 = f0_1;
f90_3 = f90_2;
- VoH3 = VoH2;
+ VoH_3 = VoH_2;
let e46: f32 = f0_2;
let e47: f32 = f90_3;
let e48: f32 = f0_2;
- let e51: f32 = VoH3;
- let e54: f32 = VoH3;
- let e56: f32 = pow5((1.0 - e54));
+ let e51: f32 = VoH_3;
+ let e54: f32 = VoH_3;
+ let e56: f32 = pow5_((1.0 - e54));
return (e46 + ((e47 - e48) * e56));
}
fn fresnel(f0_3: vec3<f32>, LoH: f32) -> vec3<f32> {
var f0_4: vec3<f32>;
- var LoH1: f32;
+ var LoH_1: f32;
var f90_4: f32;
f0_4 = f0_3;
- LoH1 = LoH;
+ LoH_1 = LoH;
let e49: vec3<f32> = f0_4;
let e62: vec3<f32> = f0_4;
f90_4 = clamp(dot(e62, vec3<f32>((50.0 * 0.33000001311302185))), 0.0, 1.0);
let e75: vec3<f32> = f0_4;
let e76: f32 = f90_4;
- let e77: f32 = LoH1;
+ let e77: f32 = LoH_1;
let e78: vec3<f32> = F_Schlick(e75, e76, e77);
return e78;
}
-fn specular(f0_5: vec3<f32>, roughness4: f32, h1: vec3<f32>, NoV2: f32, NoL2: f32, NoH2: f32, LoH2: f32, specularIntensity: f32) -> vec3<f32> {
+fn specular(f0_5: vec3<f32>, roughness_4: f32, h_1: vec3<f32>, NoV_2: f32, NoL_2: f32, NoH_2: f32, LoH_2: f32, specularIntensity: f32) -> vec3<f32> {
var f0_6: vec3<f32>;
- var roughness5: f32;
- var NoV3: f32;
- var NoL3: f32;
- var NoH3: f32;
- var LoH3: f32;
- var specularIntensity1: f32;
+ var roughness_5: f32;
+ var NoV_3: f32;
+ var NoL_3: f32;
+ var NoH_3: f32;
+ var LoH_3: f32;
+ var specularIntensity_1: f32;
var D: f32;
var V: f32;
var F: vec3<f32>;
f0_6 = f0_5;
- roughness5 = roughness4;
- NoV3 = NoV2;
- NoL3 = NoL2;
- NoH3 = NoH2;
- LoH3 = LoH2;
- specularIntensity1 = specularIntensity;
- let e57: f32 = roughness5;
- let e58: f32 = NoH3;
- let e59: f32 = D_GGX(e57, e58, h1);
+ roughness_5 = roughness_4;
+ NoV_3 = NoV_2;
+ NoL_3 = NoL_2;
+ NoH_3 = NoH_2;
+ LoH_3 = LoH_2;
+ specularIntensity_1 = specularIntensity;
+ let e57: f32 = roughness_5;
+ let e58: f32 = NoH_3;
+ let e59: f32 = D_GGX(e57, e58, h_1);
D = e59;
- let e64: f32 = roughness5;
- let e65: f32 = NoV3;
- let e66: f32 = NoL3;
+ let e64: f32 = roughness_5;
+ let e65: f32 = NoV_3;
+ let e66: f32 = NoL_3;
let e67: f32 = V_SmithGGXCorrelated(e64, e65, e66);
V = e67;
let e71: vec3<f32> = f0_6;
- let e72: f32 = LoH3;
+ let e72: f32 = LoH_3;
let e73: vec3<f32> = fresnel(e71, e72);
F = e73;
- let e75: f32 = specularIntensity1;
+ let e75: f32 = specularIntensity_1;
let e76: f32 = D;
let e78: f32 = V;
let e80: vec3<f32> = F;
return (((e75 * e76) * e78) * e80);
}
-fn Fd_Burley(roughness6: f32, NoV4: f32, NoL4: f32, LoH4: f32) -> f32 {
- var roughness7: f32;
- var NoV5: f32;
- var NoL5: f32;
- var LoH5: f32;
+fn Fd_Burley(roughness_6: f32, NoV_4: f32, NoL_4: f32, LoH_4: f32) -> f32 {
+ var roughness_7: f32;
+ var NoV_5: f32;
+ var NoL_5: f32;
+ var LoH_5: f32;
var f90_5: f32;
var lightScatter: f32;
var viewScatter: f32;
- roughness7 = roughness6;
- NoV5 = NoV4;
- NoL5 = NoL4;
- LoH5 = LoH4;
- let e50: f32 = roughness7;
- let e52: f32 = LoH5;
- let e54: f32 = LoH5;
+ roughness_7 = roughness_6;
+ NoV_5 = NoV_4;
+ NoL_5 = NoL_4;
+ LoH_5 = LoH_4;
+ let e50: f32 = roughness_7;
+ let e52: f32 = LoH_5;
+ let e54: f32 = LoH_5;
f90_5 = (0.5 + (((2.0 * e50) * e52) * e54));
let e62: f32 = f90_5;
- let e63: f32 = NoL5;
- let e64: f32 = F_Schlick1(1.0, e62, e63);
+ let e63: f32 = NoL_5;
+ let e64: f32 = F_Schlick_1(1.0, e62, e63);
lightScatter = e64;
let e70: f32 = f90_5;
- let e71: f32 = NoV5;
- let e72: f32 = F_Schlick1(1.0, e70, e71);
+ let e71: f32 = NoV_5;
+ let e72: f32 = F_Schlick_1(1.0, e70, e71);
viewScatter = e72;
let e74: f32 = lightScatter;
let e75: f32 = viewScatter;
return ((e74 * e75) * (1.0 / 3.1415927410125732));
}
-fn EnvBRDFApprox(f0_7: vec3<f32>, perceptual_roughness: f32, NoV6: f32) -> vec3<f32> {
+fn EnvBRDFApprox(f0_7: vec3<f32>, perceptual_roughness: f32, NoV_6: f32) -> vec3<f32> {
var f0_8: vec3<f32>;
- var perceptual_roughness1: f32;
- var NoV7: f32;
- var c0: vec4<f32> = vec4<f32>(-1.0, -0.027499999850988388, -0.5720000267028809, 0.02199999988079071);
- var c1: vec4<f32> = vec4<f32>(1.0, 0.042500000447034836, 1.0399999618530273, -0.03999999910593033);
+ var perceptual_roughness_1: f32;
+ var NoV_7: f32;
+ var c0_: vec4<f32> = vec4<f32>(-1.0, -0.027499999850988388, -0.5720000267028809, 0.02199999988079071);
+ var c1_: vec4<f32> = vec4<f32>(1.0, 0.042500000447034836, 1.0399999618530273, -0.03999999910593033);
var r: vec4<f32>;
- var a004: f32;
+ var a004_: f32;
var AB: vec2<f32>;
f0_8 = f0_7;
- perceptual_roughness1 = perceptual_roughness;
- NoV7 = NoV6;
- let e62: f32 = perceptual_roughness1;
- let e64: vec4<f32> = c0;
- let e66: vec4<f32> = c1;
+ perceptual_roughness_1 = perceptual_roughness;
+ NoV_7 = NoV_6;
+ let e62: f32 = perceptual_roughness_1;
+ let e64: vec4<f32> = c0_;
+ let e66: vec4<f32> = c1_;
r = ((vec4<f32>(e62) * e64) + e66);
let e69: vec4<f32> = r;
let e71: vec4<f32> = r;
- let e76: f32 = NoV7;
- let e80: f32 = NoV7;
+ let e76: f32 = NoV_7;
+ let e80: f32 = NoV_7;
let e83: vec4<f32> = r;
let e85: vec4<f32> = r;
- let e90: f32 = NoV7;
- let e94: f32 = NoV7;
+ let e90: f32 = NoV_7;
+ let e94: f32 = NoV_7;
let e98: vec4<f32> = r;
let e101: vec4<f32> = r;
- a004 = ((min((e83.x * e85.x), exp2((-(9.279999732971191) * e94))) * e98.x) + e101.y);
- let e109: f32 = a004;
+ a004_ = ((min((e83.x * e85.x), exp2((-(9.279999732971191) * e94))) * e98.x) + e101.y);
+ let e109: f32 = a004_;
let e112: vec4<f32> = r;
AB = ((vec2<f32>(-(1.0399999618530273), 1.0399999618530273) * vec2<f32>(e109)) + e112.zw);
let e116: vec3<f32> = f0_8;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -366,11 +366,11 @@ fn EnvBRDFApprox(f0_7: vec3<f32>, perceptual_roughness: f32, NoV6: f32) -> vec3<
}
fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 {
- var perceptualRoughness1: f32;
+ var perceptualRoughness_1: f32;
var clampedPerceptualRoughness: f32;
- perceptualRoughness1 = perceptualRoughness;
- let e45: f32 = perceptualRoughness1;
+ perceptualRoughness_1 = perceptualRoughness;
+ let e45: f32 = perceptualRoughness_1;
clampedPerceptualRoughness = clamp(e45, 0.08900000154972076, 1.0);
let e50: f32 = clampedPerceptualRoughness;
let e51: f32 = clampedPerceptualRoughness;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -378,152 +378,152 @@ fn perceptualRoughnessToRoughness(perceptualRoughness: f32) -> f32 {
}
fn reinhard(color: vec3<f32>) -> vec3<f32> {
- var color1: vec3<f32>;
+ var color_1: vec3<f32>;
- color1 = color;
- let e42: vec3<f32> = color1;
- let e45: vec3<f32> = color1;
+ color_1 = color;
+ let e42: vec3<f32> = color_1;
+ let e45: vec3<f32> = color_1;
return (e42 / (vec3<f32>(1.0) + e45));
}
-fn reinhard_extended(color2: vec3<f32>, max_white: f32) -> vec3<f32> {
- var color3: vec3<f32>;
- var max_white1: f32;
+fn reinhard_extended(color_2: vec3<f32>, max_white: f32) -> vec3<f32> {
+ var color_3: vec3<f32>;
+ var max_white_1: f32;
var numerator: vec3<f32>;
- color3 = color2;
- max_white1 = max_white;
- let e44: vec3<f32> = color3;
- let e47: vec3<f32> = color3;
- let e48: f32 = max_white1;
- let e49: f32 = max_white1;
+ color_3 = color_2;
+ max_white_1 = max_white;
+ let e44: vec3<f32> = color_3;
+ let e47: vec3<f32> = color_3;
+ let e48: f32 = max_white_1;
+ let e49: f32 = max_white_1;
numerator = (e44 * (vec3<f32>(1.0) + (e47 / vec3<f32>((e48 * e49)))));
let e56: vec3<f32> = numerator;
- let e59: vec3<f32> = color3;
+ let e59: vec3<f32> = color_3;
return (e56 / (vec3<f32>(1.0) + e59));
}
-fn luminance(v1: vec3<f32>) -> f32 {
- var v2: vec3<f32>;
+fn luminance(v_1: vec3<f32>) -> f32 {
+ var v_2: vec3<f32>;
- v2 = v1;
- let e47: vec3<f32> = v2;
+ v_2 = v_1;
+ let e47: vec3<f32> = v_2;
return dot(e47, vec3<f32>(0.2125999927520752, 0.7152000069618225, 0.0722000002861023));
}
fn change_luminance(c_in: vec3<f32>, l_out: f32) -> vec3<f32> {
- var c_in1: vec3<f32>;
- var l_out1: f32;
+ var c_in_1: vec3<f32>;
+ var l_out_1: f32;
var l_in: f32;
- c_in1 = c_in;
- l_out1 = l_out;
- let e45: vec3<f32> = c_in1;
+ c_in_1 = c_in;
+ l_out_1 = l_out;
+ let e45: vec3<f32> = c_in_1;
let e46: f32 = luminance(e45);
l_in = e46;
- let e48: vec3<f32> = c_in1;
- let e49: f32 = l_out1;
+ let e48: vec3<f32> = c_in_1;
+ let e49: f32 = l_out_1;
let e50: f32 = l_in;
return (e48 * (e49 / e50));
}
-fn reinhard_luminance(color4: vec3<f32>) -> vec3<f32> {
- var color5: vec3<f32>;
+fn reinhard_luminance(color_4: vec3<f32>) -> vec3<f32> {
+ var color_5: vec3<f32>;
var l_old: f32;
var l_new: f32;
- color5 = color4;
- let e43: vec3<f32> = color5;
+ color_5 = color_4;
+ let e43: vec3<f32> = color_5;
let e44: f32 = luminance(e43);
l_old = e44;
let e46: f32 = l_old;
let e48: f32 = l_old;
l_new = (e46 / (1.0 + e48));
- let e54: vec3<f32> = color5;
+ let e54: vec3<f32> = color_5;
let e55: f32 = l_new;
let e56: vec3<f32> = change_luminance(e54, e55);
return e56;
}
-fn reinhard_extended_luminance(color6: vec3<f32>, max_white_l: f32) -> vec3<f32> {
- var color7: vec3<f32>;
- var max_white_l1: f32;
- var l_old1: f32;
- var numerator1: f32;
- var l_new1: f32;
+fn reinhard_extended_luminance(color_6: vec3<f32>, max_white_l: f32) -> vec3<f32> {
+ var color_7: vec3<f32>;
+ var max_white_l_1: f32;
+ var l_old_1: f32;
+ var numerator_1: f32;
+ var l_new_1: f32;
- color7 = color6;
- max_white_l1 = max_white_l;
- let e45: vec3<f32> = color7;
+ color_7 = color_6;
+ max_white_l_1 = max_white_l;
+ let e45: vec3<f32> = color_7;
let e46: f32 = luminance(e45);
- l_old1 = e46;
- let e48: f32 = l_old1;
- let e50: f32 = l_old1;
- let e51: f32 = max_white_l1;
- let e52: f32 = max_white_l1;
- numerator1 = (e48 * (1.0 + (e50 / (e51 * e52))));
- let e58: f32 = numerator1;
- let e60: f32 = l_old1;
- l_new1 = (e58 / (1.0 + e60));
- let e66: vec3<f32> = color7;
- let e67: f32 = l_new1;
+ l_old_1 = e46;
+ let e48: f32 = l_old_1;
+ let e50: f32 = l_old_1;
+ let e51: f32 = max_white_l_1;
+ let e52: f32 = max_white_l_1;
+ numerator_1 = (e48 * (1.0 + (e50 / (e51 * e52))));
+ let e58: f32 = numerator_1;
+ let e60: f32 = l_old_1;
+ l_new_1 = (e58 / (1.0 + e60));
+ let e66: vec3<f32> = color_7;
+ let e67: f32 = l_new_1;
let e68: vec3<f32> = change_luminance(e66, e67);
return e68;
}
-fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3<f32>, V1: vec3<f32>, R: vec3<f32>, F0: vec3<f32>, diffuseColor: vec3<f32>) -> vec3<f32> {
- var light1: PointLight;
- var roughness9: f32;
- var NdotV1: f32;
- var N1: vec3<f32>;
- var V2: vec3<f32>;
- var R1: vec3<f32>;
+fn point_light(light: PointLight, roughness_8: f32, NdotV: f32, N: vec3<f32>, V_1: vec3<f32>, R: vec3<f32>, F0_: vec3<f32>, diffuseColor: vec3<f32>) -> vec3<f32> {
+ var light_1: PointLight;
+ var roughness_9: f32;
+ var NdotV_1: f32;
+ var N_1: vec3<f32>;
+ var V_2: vec3<f32>;
+ var R_1: vec3<f32>;
var F0_1: vec3<f32>;
- var diffuseColor1: vec3<f32>;
+ var diffuseColor_1: vec3<f32>;
var light_to_frag: vec3<f32>;
var distance_square: f32;
var rangeAttenuation: f32;
- var a1: f32;
+ var a_1: f32;
var radius: f32;
var centerToRay: vec3<f32>;
var closestPoint: vec3<f32>;
var LspecLengthInverse: f32;
var normalizationFactor: f32;
- var specularIntensity2: f32;
+ var specularIntensity_2: f32;
var L: vec3<f32>;
var H: vec3<f32>;
- var NoL6: f32;
- var NoH4: f32;
- var LoH6: f32;
- var specular1: vec3<f32>;
+ var NoL_6: f32;
+ var NoH_4: f32;
+ var LoH_6: f32;
+ var specular_1: vec3<f32>;
var diffuse: vec3<f32>;
- light1 = light;
- roughness9 = roughness8;
- NdotV1 = NdotV;
- N1 = N;
- V2 = V1;
- R1 = R;
- F0_1 = F0;
- diffuseColor1 = diffuseColor;
- let e56: PointLight = light1;
- let e59: vec3<f32> = v_WorldPosition1;
+ light_1 = light;
+ roughness_9 = roughness_8;
+ NdotV_1 = NdotV;
+ N_1 = N;
+ V_2 = V_1;
+ R_1 = R;
+ F0_1 = F0_;
+ diffuseColor_1 = diffuseColor;
+ let e56: PointLight = light_1;
+ let e59: vec3<f32> = v_WorldPosition_1;
light_to_frag = (e56.pos.xyz - e59.xyz);
let e65: vec3<f32> = light_to_frag;
let e66: vec3<f32> = light_to_frag;
distance_square = dot(e65, e66);
- let e70: PointLight = light1;
+ let e70: PointLight = light_1;
let e73: f32 = distance_square;
- let e74: PointLight = light1;
+ let e74: PointLight = light_1;
let e77: f32 = getDistanceAttenuation(e73, e74.lightParams.x);
rangeAttenuation = e77;
- let e79: f32 = roughness9;
- a1 = e79;
- let e81: PointLight = light1;
+ let e79: f32 = roughness_9;
+ a_1 = e79;
+ let e81: PointLight = light_1;
radius = e81.lightParams.y;
let e87: vec3<f32> = light_to_frag;
- let e88: vec3<f32> = R1;
- let e90: vec3<f32> = R1;
+ let e88: vec3<f32> = R_1;
+ let e90: vec3<f32> = R_1;
let e92: vec3<f32> = light_to_frag;
centerToRay = ((dot(e87, e88) * e90) - e92);
let e95: vec3<f32> = light_to_frag;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -544,213 +544,213 @@ fn point_light(light: PointLight, roughness8: f32, NdotV: f32, N: vec3<f32>, V1:
let e138: vec3<f32> = closestPoint;
let e139: vec3<f32> = closestPoint;
LspecLengthInverse = inverseSqrt(dot(e138, e139));
- let e143: f32 = a1;
- let e144: f32 = a1;
+ let e143: f32 = a_1;
+ let e144: f32 = a_1;
let e145: f32 = radius;
let e148: f32 = LspecLengthInverse;
- let e153: f32 = a1;
+ let e153: f32 = a_1;
let e154: f32 = radius;
let e157: f32 = LspecLengthInverse;
normalizationFactor = (e143 / clamp((e153 + ((e154 * 0.5) * e157)), 0.0, 1.0));
let e165: f32 = normalizationFactor;
let e166: f32 = normalizationFactor;
- specularIntensity2 = (e165 * e166);
+ specularIntensity_2 = (e165 * e166);
let e169: vec3<f32> = closestPoint;
let e170: f32 = LspecLengthInverse;
L = (e169 * e170);
let e173: vec3<f32> = L;
- let e174: vec3<f32> = V2;
+ let e174: vec3<f32> = V_2;
let e176: vec3<f32> = L;
- let e177: vec3<f32> = V2;
+ let e177: vec3<f32> = V_2;
H = normalize((e176 + e177));
- let e183: vec3<f32> = N1;
+ let e183: vec3<f32> = N_1;
let e184: vec3<f32> = L;
- let e190: vec3<f32> = N1;
+ let e190: vec3<f32> = N_1;
let e191: vec3<f32> = L;
- NoL6 = clamp(dot(e190, e191), 0.0, 1.0);
- let e199: vec3<f32> = N1;
+ NoL_6 = clamp(dot(e190, e191), 0.0, 1.0);
+ let e199: vec3<f32> = N_1;
let e200: vec3<f32> = H;
- let e206: vec3<f32> = N1;
+ let e206: vec3<f32> = N_1;
let e207: vec3<f32> = H;
- NoH4 = clamp(dot(e206, e207), 0.0, 1.0);
+ NoH_4 = clamp(dot(e206, e207), 0.0, 1.0);
let e215: vec3<f32> = L;
let e216: vec3<f32> = H;
let e222: vec3<f32> = L;
let e223: vec3<f32> = H;
- LoH6 = clamp(dot(e222, e223), 0.0, 1.0);
+ LoH_6 = clamp(dot(e222, e223), 0.0, 1.0);
let e237: vec3<f32> = F0_1;
- let e238: f32 = roughness9;
+ let e238: f32 = roughness_9;
let e239: vec3<f32> = H;
- let e240: f32 = NdotV1;
- let e241: f32 = NoL6;
- let e242: f32 = NoH4;
- let e243: f32 = LoH6;
- let e244: f32 = specularIntensity2;
+ let e240: f32 = NdotV_1;
+ let e241: f32 = NoL_6;
+ let e242: f32 = NoH_4;
+ let e243: f32 = LoH_6;
+ let e244: f32 = specularIntensity_2;
let e245: vec3<f32> = specular(e237, e238, e239, e240, e241, e242, e243, e244);
- specular1 = e245;
+ specular_1 = e245;
let e248: vec3<f32> = light_to_frag;
L = normalize(e248);
let e250: vec3<f32> = L;
- let e251: vec3<f32> = V2;
+ let e251: vec3<f32> = V_2;
let e253: vec3<f32> = L;
- let e254: vec3<f32> = V2;
+ let e254: vec3<f32> = V_2;
H = normalize((e253 + e254));
- let e259: vec3<f32> = N1;
+ let e259: vec3<f32> = N_1;
let e260: vec3<f32> = L;
- let e266: vec3<f32> = N1;
+ let e266: vec3<f32> = N_1;
let e267: vec3<f32> = L;
- NoL6 = clamp(dot(e266, e267), 0.0, 1.0);
- let e274: vec3<f32> = N1;
+ NoL_6 = clamp(dot(e266, e267), 0.0, 1.0);
+ let e274: vec3<f32> = N_1;
let e275: vec3<f32> = H;
- let e281: vec3<f32> = N1;
+ let e281: vec3<f32> = N_1;
let e282: vec3<f32> = H;
- NoH4 = clamp(dot(e281, e282), 0.0, 1.0);
+ NoH_4 = clamp(dot(e281, e282), 0.0, 1.0);
let e289: vec3<f32> = L;
let e290: vec3<f32> = H;
let e296: vec3<f32> = L;
let e297: vec3<f32> = H;
- LoH6 = clamp(dot(e296, e297), 0.0, 1.0);
- let e302: vec3<f32> = diffuseColor1;
- let e307: f32 = roughness9;
- let e308: f32 = NdotV1;
- let e309: f32 = NoL6;
- let e310: f32 = LoH6;
+ LoH_6 = clamp(dot(e296, e297), 0.0, 1.0);
+ let e302: vec3<f32> = diffuseColor_1;
+ let e307: f32 = roughness_9;
+ let e308: f32 = NdotV_1;
+ let e309: f32 = NoL_6;
+ let e310: f32 = LoH_6;
let e311: f32 = Fd_Burley(e307, e308, e309, e310);
diffuse = (e302 * e311);
let e314: vec3<f32> = diffuse;
- let e315: vec3<f32> = specular1;
- let e317: PointLight = light1;
+ let e315: vec3<f32> = specular_1;
+ let e317: PointLight = light_1;
let e321: f32 = rangeAttenuation;
- let e322: f32 = NoL6;
+ let e322: f32 = NoL_6;
return (((e314 + e315) * e317.color.xyz) * (e321 * e322));
}
-fn dir_light(light2: DirectionalLight, roughness10: f32, NdotV2: f32, normal: vec3<f32>, view: vec3<f32>, R2: vec3<f32>, F0_2: vec3<f32>, diffuseColor2: vec3<f32>) -> vec3<f32> {
- var light3: DirectionalLight;
- var roughness11: f32;
- var NdotV3: f32;
- var normal1: vec3<f32>;
- var view1: vec3<f32>;
- var R3: vec3<f32>;
+fn dir_light(light_2: DirectionalLight, roughness_10: f32, NdotV_2: f32, normal: vec3<f32>, view: vec3<f32>, R_2: vec3<f32>, F0_2: vec3<f32>, diffuseColor_2: vec3<f32>) -> vec3<f32> {
+ var light_3: DirectionalLight;
+ var roughness_11: f32;
+ var NdotV_3: f32;
+ var normal_1: vec3<f32>;
+ var view_1: vec3<f32>;
+ var R_3: vec3<f32>;
var F0_3: vec3<f32>;
- var diffuseColor3: vec3<f32>;
+ var diffuseColor_3: vec3<f32>;
var incident_light: vec3<f32>;
var half_vector: vec3<f32>;
- var NoL7: f32;
- var NoH5: f32;
- var LoH7: f32;
- var diffuse1: vec3<f32>;
- var specularIntensity3: f32 = 1.0;
- var specular2: vec3<f32>;
-
- light3 = light2;
- roughness11 = roughness10;
- NdotV3 = NdotV2;
- normal1 = normal;
- view1 = view;
- R3 = R2;
+ var NoL_7: f32;
+ var NoH_5: f32;
+ var LoH_7: f32;
+ var diffuse_1: vec3<f32>;
+ var specularIntensity_3: f32 = 1.0;
+ var specular_2: vec3<f32>;
+
+ light_3 = light_2;
+ roughness_11 = roughness_10;
+ NdotV_3 = NdotV_2;
+ normal_1 = normal;
+ view_1 = view;
+ R_3 = R_2;
F0_3 = F0_2;
- diffuseColor3 = diffuseColor2;
- let e56: DirectionalLight = light3;
+ diffuseColor_3 = diffuseColor_2;
+ let e56: DirectionalLight = light_3;
incident_light = e56.direction.xyz;
let e60: vec3<f32> = incident_light;
- let e61: vec3<f32> = view1;
+ let e61: vec3<f32> = view_1;
let e63: vec3<f32> = incident_light;
- let e64: vec3<f32> = view1;
+ let e64: vec3<f32> = view_1;
half_vector = normalize((e63 + e64));
- let e70: vec3<f32> = normal1;
+ let e70: vec3<f32> = normal_1;
let e71: vec3<f32> = incident_light;
- let e77: vec3<f32> = normal1;
+ let e77: vec3<f32> = normal_1;
let e78: vec3<f32> = incident_light;
- NoL7 = clamp(dot(e77, e78), 0.0, 1.0);
- let e86: vec3<f32> = normal1;
+ NoL_7 = clamp(dot(e77, e78), 0.0, 1.0);
+ let e86: vec3<f32> = normal_1;
let e87: vec3<f32> = half_vector;
- let e93: vec3<f32> = normal1;
+ let e93: vec3<f32> = normal_1;
let e94: vec3<f32> = half_vector;
- NoH5 = clamp(dot(e93, e94), 0.0, 1.0);
+ NoH_5 = clamp(dot(e93, e94), 0.0, 1.0);
let e102: vec3<f32> = incident_light;
let e103: vec3<f32> = half_vector;
let e109: vec3<f32> = incident_light;
let e110: vec3<f32> = half_vector;
- LoH7 = clamp(dot(e109, e110), 0.0, 1.0);
- let e116: vec3<f32> = diffuseColor3;
- let e121: f32 = roughness11;
- let e122: f32 = NdotV3;
- let e123: f32 = NoL7;
- let e124: f32 = LoH7;
+ LoH_7 = clamp(dot(e109, e110), 0.0, 1.0);
+ let e116: vec3<f32> = diffuseColor_3;
+ let e121: f32 = roughness_11;
+ let e122: f32 = NdotV_3;
+ let e123: f32 = NoL_7;
+ let e124: f32 = LoH_7;
let e125: f32 = Fd_Burley(e121, e122, e123, e124);
- diffuse1 = (e116 * e125);
+ diffuse_1 = (e116 * e125);
let e138: vec3<f32> = F0_3;
- let e139: f32 = roughness11;
+ let e139: f32 = roughness_11;
let e140: vec3<f32> = half_vector;
- let e141: f32 = NdotV3;
- let e142: f32 = NoL7;
- let e143: f32 = NoH5;
- let e144: f32 = LoH7;
- let e145: f32 = specularIntensity3;
+ let e141: f32 = NdotV_3;
+ let e142: f32 = NoL_7;
+ let e143: f32 = NoH_5;
+ let e144: f32 = LoH_7;
+ let e145: f32 = specularIntensity_3;
let e146: vec3<f32> = specular(e138, e139, e140, e141, e142, e143, e144, e145);
- specular2 = e146;
- let e148: vec3<f32> = specular2;
- let e149: vec3<f32> = diffuse1;
- let e151: DirectionalLight = light3;
- let e155: f32 = NoL7;
+ specular_2 = e146;
+ let e148: vec3<f32> = specular_2;
+ let e149: vec3<f32> = diffuse_1;
+ let e151: DirectionalLight = light_3;
+ let e155: f32 = NoL_7;
return (((e148 + e149) * e151.color.xyz) * e155);
}
-fn main1() {
+fn main_1() {
var output_color: vec4<f32>;
var metallic_roughness: vec4<f32>;
var metallic: f32;
- var perceptual_roughness2: f32;
- var roughness12: f32;
- var N2: vec3<f32>;
+ var perceptual_roughness_2: f32;
+ var roughness_12: f32;
+ var N_2: vec3<f32>;
var T: vec3<f32>;
var B: vec3<f32>;
var TBN: mat3x3<f32>;
var occlusion: f32;
var emissive: vec4<f32>;
- var V3: vec3<f32>;
- var NdotV4: f32;
+ var V_3: vec3<f32>;
+ var NdotV_4: f32;
var F0_4: vec3<f32>;
- var diffuseColor4: vec3<f32>;
- var R4: vec3<f32>;
+ var diffuseColor_4: vec3<f32>;
+ var R_4: vec3<f32>;
var light_accum: vec3<f32> = vec3<f32>(0.0, 0.0, 0.0);
var i: i32 = 0;
- var i1: i32 = 0;
+ var i_1: i32 = 0;
var diffuse_ambient: vec3<f32>;
var specular_ambient: vec3<f32>;
- let e40: vec4<f32> = global3.base_color;
+ let e40: vec4<f32> = global_3.base_color;
output_color = e40;
let e42: vec4<f32> = output_color;
- let e44: vec2<f32> = v_Uv1;
+ let e44: vec2<f32> = v_Uv_1;
let e45: vec4<f32> = textureSample(StandardMaterial_base_color_texture, StandardMaterial_base_color_texture_sampler, e44);
output_color = (e42 * e45);
- let e48: vec2<f32> = v_Uv1;
+ let e48: vec2<f32> = v_Uv_1;
let e49: vec4<f32> = textureSample(StandardMaterial_metallic_roughness_texture, StandardMaterial_metallic_roughness_texture_sampler, e48);
metallic_roughness = e49;
- let e51: f32 = global5.metallic;
+ let e51: f32 = global_5.metallic;
let e52: vec4<f32> = metallic_roughness;
metallic = (e51 * e52.z);
- let e56: f32 = global4.perceptual_roughness;
+ let e56: f32 = global_4.perceptual_roughness;
let e57: vec4<f32> = metallic_roughness;
- perceptual_roughness2 = (e56 * e57.y);
- let e62: f32 = perceptual_roughness2;
+ perceptual_roughness_2 = (e56 * e57.y);
+ let e62: f32 = perceptual_roughness_2;
let e63: f32 = perceptualRoughnessToRoughness(e62);
- roughness12 = e63;
- let e66: vec3<f32> = v_WorldNormal1;
- N2 = normalize(e66);
- let e69: vec4<f32> = v_WorldTangent1;
- let e71: vec4<f32> = v_WorldTangent1;
+ roughness_12 = e63;
+ let e66: vec3<f32> = v_WorldNormal_1;
+ N_2 = normalize(e66);
+ let e69: vec4<f32> = v_WorldTangent_1;
+ let e71: vec4<f32> = v_WorldTangent_1;
T = normalize(e71.xyz);
- let e77: vec3<f32> = N2;
+ let e77: vec3<f32> = N_2;
let e78: vec3<f32> = T;
- let e80: vec4<f32> = v_WorldTangent1;
+ let e80: vec4<f32> = v_WorldTangent_1;
B = (cross(e77, e78) * e80.w);
let e85: bool = gl_FrontFacing;
- let e86: vec3<f32> = N2;
- let e87: vec3<f32> = N2;
- N2 = select(-(e87), e86, e85);
+ let e86: vec3<f32> = N_2;
+ let e87: vec3<f32> = N_2;
+ N_2 = select(-(e87), e86, e85);
let e90: bool = gl_FrontFacing;
let e91: vec3<f32> = T;
let e92: vec3<f32> = T;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -761,53 +761,53 @@ fn main1() {
B = select(-(e97), e96, e95);
let e100: vec3<f32> = T;
let e101: vec3<f32> = B;
- let e102: vec3<f32> = N2;
+ let e102: vec3<f32> = N_2;
TBN = mat3x3<f32>(vec3<f32>(e100.x, e100.y, e100.z), vec3<f32>(e101.x, e101.y, e101.z), vec3<f32>(e102.x, e102.y, e102.z));
let e117: mat3x3<f32> = TBN;
- let e119: vec2<f32> = v_Uv1;
+ let e119: vec2<f32> = v_Uv_1;
let e120: vec4<f32> = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, e119);
- let e128: vec2<f32> = v_Uv1;
+ let e128: vec2<f32> = v_Uv_1;
let e129: vec4<f32> = textureSample(StandardMaterial_normal_map, StandardMaterial_normal_map_sampler, e128);
- N2 = (e117 * normalize(((e129.xyz * 2.0) - vec3<f32>(1.0))));
- let e139: vec2<f32> = v_Uv1;
+ N_2 = (e117 * normalize(((e129.xyz * 2.0) - vec3<f32>(1.0))));
+ let e139: vec2<f32> = v_Uv_1;
let e140: vec4<f32> = textureSample(StandardMaterial_occlusion_texture, StandardMaterial_occlusion_texture_sampler, e139);
occlusion = e140.x;
- let e143: vec4<f32> = global7.emissive;
+ let e143: vec4<f32> = global_7.emissive;
emissive = e143;
let e145: vec4<f32> = emissive;
let e147: vec4<f32> = emissive;
- let e150: vec2<f32> = v_Uv1;
+ let e150: vec2<f32> = v_Uv_1;
let e151: vec4<f32> = textureSample(StandardMaterial_emissive_texture, StandardMaterial_emissive_texture_sampler, e150);
let e153: vec3<f32> = (e147.xyz * e151.xyz);
emissive.x = e153.x;
emissive.y = e153.y;
emissive.z = e153.z;
- let e160: vec4<f32> = global1.CameraPos;
- let e162: vec3<f32> = v_WorldPosition1;
- let e165: vec4<f32> = global1.CameraPos;
- let e167: vec3<f32> = v_WorldPosition1;
- V3 = normalize((e165.xyz - e167.xyz));
- let e174: vec3<f32> = N2;
- let e175: vec3<f32> = V3;
- let e180: vec3<f32> = N2;
- let e181: vec3<f32> = V3;
- NdotV4 = max(dot(e180, e181), 0.0010000000474974513);
- let e187: f32 = global6.reflectance;
- let e189: f32 = global6.reflectance;
+ let e160: vec4<f32> = global_1.CameraPos;
+ let e162: vec3<f32> = v_WorldPosition_1;
+ let e165: vec4<f32> = global_1.CameraPos;
+ let e167: vec3<f32> = v_WorldPosition_1;
+ V_3 = normalize((e165.xyz - e167.xyz));
+ let e174: vec3<f32> = N_2;
+ let e175: vec3<f32> = V_3;
+ let e180: vec3<f32> = N_2;
+ let e181: vec3<f32> = V_3;
+ NdotV_4 = max(dot(e180, e181), 0.0010000000474974513);
+ let e187: f32 = global_6.reflectance;
+ let e189: f32 = global_6.reflectance;
let e192: f32 = metallic;
let e196: vec4<f32> = output_color;
let e198: f32 = metallic;
F0_4 = (vec3<f32>((((0.1599999964237213 * e187) * e189) * (1.0 - e192))) + (e196.xyz * vec3<f32>(e198)));
let e203: vec4<f32> = output_color;
let e206: f32 = metallic;
- diffuseColor4 = (e203.xyz * vec3<f32>((1.0 - e206)));
- let e211: vec3<f32> = V3;
- let e214: vec3<f32> = V3;
- let e216: vec3<f32> = N2;
- R4 = reflect(-(e214), e216);
+ diffuseColor_4 = (e203.xyz * vec3<f32>((1.0 - e206)));
+ let e211: vec3<f32> = V_3;
+ let e214: vec3<f32> = V_3;
+ let e216: vec3<f32> = N_2;
+ R_4 = reflect(-(e214), e216);
loop {
let e224: i32 = i;
- let e225: vec4<u32> = global2.NumLights;
+ let e225: vec4<u32> = global_2.NumLights;
let e229: i32 = i;
if (!(((e224 < i32(e225.x)) && (e229 < 10)))) {
break;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -816,14 +816,14 @@ fn main1() {
let e236: vec3<f32> = light_accum;
let e237: i32 = i;
let e247: i32 = i;
- let e249: PointLight = global2.PointLights[e247];
- let e250: f32 = roughness12;
- let e251: f32 = NdotV4;
- let e252: vec3<f32> = N2;
- let e253: vec3<f32> = V3;
- let e254: vec3<f32> = R4;
+ let e249: PointLight = global_2.PointLights[e247];
+ let e250: f32 = roughness_12;
+ let e251: f32 = NdotV_4;
+ let e252: vec3<f32> = N_2;
+ let e253: vec3<f32> = V_3;
+ let e254: vec3<f32> = R_4;
let e255: vec3<f32> = F0_4;
- let e256: vec3<f32> = diffuseColor4;
+ let e256: vec3<f32> = diffuseColor_4;
let e257: vec3<f32> = point_light(e249, e250, e251, e252, e253, e254, e255, e256);
light_accum = (e236 + e257);
}
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -833,39 +833,39 @@ fn main1() {
}
}
loop {
- let e261: i32 = i1;
- let e262: vec4<u32> = global2.NumLights;
- let e266: i32 = i1;
+ let e261: i32 = i_1;
+ let e262: vec4<u32> = global_2.NumLights;
+ let e266: i32 = i_1;
if (!(((e261 < i32(e262.y)) && (e266 < 1)))) {
break;
}
{
let e273: vec3<f32> = light_accum;
- let e274: i32 = i1;
- let e284: i32 = i1;
- let e286: DirectionalLight = global2.DirectionalLights[e284];
- let e287: f32 = roughness12;
- let e288: f32 = NdotV4;
- let e289: vec3<f32> = N2;
- let e290: vec3<f32> = V3;
- let e291: vec3<f32> = R4;
+ let e274: i32 = i_1;
+ let e284: i32 = i_1;
+ let e286: DirectionalLight = global_2.DirectionalLights[e284];
+ let e287: f32 = roughness_12;
+ let e288: f32 = NdotV_4;
+ let e289: vec3<f32> = N_2;
+ let e290: vec3<f32> = V_3;
+ let e291: vec3<f32> = R_4;
let e292: vec3<f32> = F0_4;
- let e293: vec3<f32> = diffuseColor4;
+ let e293: vec3<f32> = diffuseColor_4;
let e294: vec3<f32> = dir_light(e286, e287, e288, e289, e290, e291, e292, e293);
light_accum = (e273 + e294);
}
continuing {
- let e270: i32 = i1;
- i1 = (e270 + 1);
+ let e270: i32 = i_1;
+ i_1 = (e270 + 1);
}
}
- let e299: vec3<f32> = diffuseColor4;
- let e301: f32 = NdotV4;
+ let e299: vec3<f32> = diffuseColor_4;
+ let e301: f32 = NdotV_4;
let e302: vec3<f32> = EnvBRDFApprox(e299, 1.0, e301);
diffuse_ambient = e302;
let e307: vec3<f32> = F0_4;
- let e308: f32 = perceptual_roughness2;
- let e309: f32 = NdotV4;
+ let e308: f32 = perceptual_roughness_2;
+ let e309: f32 = NdotV_4;
let e310: vec3<f32> = EnvBRDFApprox(e307, e308, e309);
specular_ambient = e310;
let e312: vec4<f32> = output_color;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -877,7 +877,7 @@ fn main1() {
let e323: vec4<f32> = output_color;
let e325: vec3<f32> = diffuse_ambient;
let e326: vec3<f32> = specular_ambient;
- let e328: vec4<f32> = global2.AmbientColor;
+ let e328: vec4<f32> = global_2.AmbientColor;
let e331: f32 = occlusion;
let e333: vec3<f32> = (e323.xyz + (((e325 + e326) * e328.xyz) * e331));
output_color.x = e333.x;
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -905,12 +905,12 @@ fn main1() {
[[stage(fragment)]]
fn main([[location(0)]] v_WorldPosition: vec3<f32>, [[location(1)]] v_WorldNormal: vec3<f32>, [[location(2)]] v_Uv: vec2<f32>, [[location(3)]] v_WorldTangent: vec4<f32>, [[builtin(front_facing)]] param: bool) -> FragmentOutput {
- v_WorldPosition1 = v_WorldPosition;
- v_WorldNormal1 = v_WorldNormal;
- v_Uv1 = v_Uv;
- v_WorldTangent1 = v_WorldTangent;
+ v_WorldPosition_1 = v_WorldPosition;
+ v_WorldNormal_1 = v_WorldNormal;
+ v_Uv_1 = v_Uv;
+ v_WorldTangent_1 = v_WorldTangent;
gl_FrontFacing = param;
- main1();
+ main_1();
let e72: vec4<f32> = o_Target;
return FragmentOutput(e72);
}
diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl
--- a/tests/out/wgsl/bevy-pbr-vert.wgsl
+++ b/tests/out/wgsl/bevy-pbr-vert.wgsl
@@ -16,10 +16,10 @@ struct VertexOutput {
[[builtin(position)]] member: vec4<f32>;
};
-var<private> Vertex_Position1: vec3<f32>;
-var<private> Vertex_Normal1: vec3<f32>;
-var<private> Vertex_Uv1: vec2<f32>;
-var<private> Vertex_Tangent1: vec4<f32>;
+var<private> Vertex_Position_1: vec3<f32>;
+var<private> Vertex_Normal_1: vec3<f32>;
+var<private> Vertex_Uv_1: vec2<f32>;
+var<private> Vertex_Tangent_1: vec4<f32>;
var<private> v_WorldPosition: vec3<f32>;
var<private> v_WorldNormal: vec3<f32>;
var<private> v_Uv: vec2<f32>;
diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl
--- a/tests/out/wgsl/bevy-pbr-vert.wgsl
+++ b/tests/out/wgsl/bevy-pbr-vert.wgsl
@@ -27,25 +27,25 @@ var<private> v_Uv: vec2<f32>;
var<uniform> global: CameraViewProj;
var<private> v_WorldTangent: vec4<f32>;
[[group(2), binding(0)]]
-var<uniform> global1: Transform;
+var<uniform> global_1: Transform;
var<private> gl_Position: vec4<f32>;
-fn main1() {
+fn main_1() {
var world_position: vec4<f32>;
- let e12: mat4x4<f32> = global1.Model;
- let e13: vec3<f32> = Vertex_Position1;
+ let e12: mat4x4<f32> = global_1.Model;
+ let e13: vec3<f32> = Vertex_Position_1;
world_position = (e12 * vec4<f32>(e13, 1.0));
let e18: vec4<f32> = world_position;
v_WorldPosition = e18.xyz;
- let e20: mat4x4<f32> = global1.Model;
- let e28: vec3<f32> = Vertex_Normal1;
+ let e20: mat4x4<f32> = global_1.Model;
+ let e28: vec3<f32> = Vertex_Normal_1;
v_WorldNormal = (mat3x3<f32>(e20[0].xyz, e20[1].xyz, e20[2].xyz) * e28);
- let e30: vec2<f32> = Vertex_Uv1;
+ let e30: vec2<f32> = Vertex_Uv_1;
v_Uv = e30;
- let e31: mat4x4<f32> = global1.Model;
- let e39: vec4<f32> = Vertex_Tangent1;
- let e42: vec4<f32> = Vertex_Tangent1;
+ let e31: mat4x4<f32> = global_1.Model;
+ let e39: vec4<f32> = Vertex_Tangent_1;
+ let e42: vec4<f32> = Vertex_Tangent_1;
v_WorldTangent = vec4<f32>((mat3x3<f32>(e31[0].xyz, e31[1].xyz, e31[2].xyz) * e39.xyz), e42.w);
let e46: mat4x4<f32> = global.ViewProj;
let e47: vec4<f32> = world_position;
diff --git a/tests/out/wgsl/bevy-pbr-vert.wgsl b/tests/out/wgsl/bevy-pbr-vert.wgsl
--- a/tests/out/wgsl/bevy-pbr-vert.wgsl
+++ b/tests/out/wgsl/bevy-pbr-vert.wgsl
@@ -55,11 +55,11 @@ fn main1() {
[[stage(vertex)]]
fn main([[location(0)]] Vertex_Position: vec3<f32>, [[location(1)]] Vertex_Normal: vec3<f32>, [[location(2)]] Vertex_Uv: vec2<f32>, [[location(3)]] Vertex_Tangent: vec4<f32>) -> VertexOutput {
- Vertex_Position1 = Vertex_Position;
- Vertex_Normal1 = Vertex_Normal;
- Vertex_Uv1 = Vertex_Uv;
- Vertex_Tangent1 = Vertex_Tangent;
- main1();
+ Vertex_Position_1 = Vertex_Position;
+ Vertex_Normal_1 = Vertex_Normal;
+ Vertex_Uv_1 = Vertex_Uv;
+ Vertex_Tangent_1 = Vertex_Tangent;
+ main_1();
let e29: vec3<f32> = v_WorldPosition;
let e31: vec3<f32> = v_WorldNormal;
let e33: vec2<f32> = v_Uv;
diff --git a/tests/out/wgsl/bits.wgsl b/tests/out/wgsl/bits.wgsl
--- a/tests/out/wgsl/bits.wgsl
+++ b/tests/out/wgsl/bits.wgsl
@@ -1,83 +1,83 @@
[[stage(compute), workgroup_size(1, 1, 1)]]
fn main() {
var i: i32 = 0;
- var i2: vec2<i32>;
- var i3: vec3<i32>;
- var i4: vec4<i32>;
+ var i2_: vec2<i32>;
+ var i3_: vec3<i32>;
+ var i4_: vec4<i32>;
var u: u32 = 0u;
- var u2: vec2<u32>;
- var u3: vec3<u32>;
- var u4: vec4<u32>;
- var f2: vec2<f32>;
- var f4: vec4<f32>;
+ var u2_: vec2<u32>;
+ var u3_: vec3<u32>;
+ var u4_: vec4<u32>;
+ var f2_: vec2<f32>;
+ var f4_: vec4<f32>;
- i2 = vec2<i32>(0);
- i3 = vec3<i32>(0);
- i4 = vec4<i32>(0);
- u2 = vec2<u32>(0u);
- u3 = vec3<u32>(0u);
- u4 = vec4<u32>(0u);
- f2 = vec2<f32>(0.0);
- f4 = vec4<f32>(0.0);
- let e28: vec4<f32> = f4;
+ i2_ = vec2<i32>(0);
+ i3_ = vec3<i32>(0);
+ i4_ = vec4<i32>(0);
+ u2_ = vec2<u32>(0u);
+ u3_ = vec3<u32>(0u);
+ u4_ = vec4<u32>(0u);
+ f2_ = vec2<f32>(0.0);
+ f4_ = vec4<f32>(0.0);
+ let e28: vec4<f32> = f4_;
u = pack4x8snorm(e28);
- let e30: vec4<f32> = f4;
+ let e30: vec4<f32> = f4_;
u = pack4x8unorm(e30);
- let e32: vec2<f32> = f2;
+ let e32: vec2<f32> = f2_;
u = pack2x16snorm(e32);
- let e34: vec2<f32> = f2;
+ let e34: vec2<f32> = f2_;
u = pack2x16unorm(e34);
- let e36: vec2<f32> = f2;
+ let e36: vec2<f32> = f2_;
u = pack2x16float(e36);
let e38: u32 = u;
- f4 = unpack4x8snorm(e38);
+ f4_ = unpack4x8snorm(e38);
let e40: u32 = u;
- f4 = unpack4x8unorm(e40);
+ f4_ = unpack4x8unorm(e40);
let e42: u32 = u;
- f2 = unpack2x16snorm(e42);
+ f2_ = unpack2x16snorm(e42);
let e44: u32 = u;
- f2 = unpack2x16unorm(e44);
+ f2_ = unpack2x16unorm(e44);
let e46: u32 = u;
- f2 = unpack2x16float(e46);
+ f2_ = unpack2x16float(e46);
let e48: i32 = i;
let e49: i32 = i;
i = insertBits(e48, e49, 5u, 10u);
- let e53: vec2<i32> = i2;
- let e54: vec2<i32> = i2;
- i2 = insertBits(e53, e54, 5u, 10u);
- let e58: vec3<i32> = i3;
- let e59: vec3<i32> = i3;
- i3 = insertBits(e58, e59, 5u, 10u);
- let e63: vec4<i32> = i4;
- let e64: vec4<i32> = i4;
- i4 = insertBits(e63, e64, 5u, 10u);
+ let e53: vec2<i32> = i2_;
+ let e54: vec2<i32> = i2_;
+ i2_ = insertBits(e53, e54, 5u, 10u);
+ let e58: vec3<i32> = i3_;
+ let e59: vec3<i32> = i3_;
+ i3_ = insertBits(e58, e59, 5u, 10u);
+ let e63: vec4<i32> = i4_;
+ let e64: vec4<i32> = i4_;
+ i4_ = insertBits(e63, e64, 5u, 10u);
let e68: u32 = u;
let e69: u32 = u;
u = insertBits(e68, e69, 5u, 10u);
- let e73: vec2<u32> = u2;
- let e74: vec2<u32> = u2;
- u2 = insertBits(e73, e74, 5u, 10u);
- let e78: vec3<u32> = u3;
- let e79: vec3<u32> = u3;
- u3 = insertBits(e78, e79, 5u, 10u);
- let e83: vec4<u32> = u4;
- let e84: vec4<u32> = u4;
- u4 = insertBits(e83, e84, 5u, 10u);
+ let e73: vec2<u32> = u2_;
+ let e74: vec2<u32> = u2_;
+ u2_ = insertBits(e73, e74, 5u, 10u);
+ let e78: vec3<u32> = u3_;
+ let e79: vec3<u32> = u3_;
+ u3_ = insertBits(e78, e79, 5u, 10u);
+ let e83: vec4<u32> = u4_;
+ let e84: vec4<u32> = u4_;
+ u4_ = insertBits(e83, e84, 5u, 10u);
let e88: i32 = i;
i = extractBits(e88, 5u, 10u);
- let e92: vec2<i32> = i2;
- i2 = extractBits(e92, 5u, 10u);
- let e96: vec3<i32> = i3;
- i3 = extractBits(e96, 5u, 10u);
- let e100: vec4<i32> = i4;
- i4 = extractBits(e100, 5u, 10u);
+ let e92: vec2<i32> = i2_;
+ i2_ = extractBits(e92, 5u, 10u);
+ let e96: vec3<i32> = i3_;
+ i3_ = extractBits(e96, 5u, 10u);
+ let e100: vec4<i32> = i4_;
+ i4_ = extractBits(e100, 5u, 10u);
let e104: u32 = u;
u = extractBits(e104, 5u, 10u);
- let e108: vec2<u32> = u2;
- u2 = extractBits(e108, 5u, 10u);
- let e112: vec3<u32> = u3;
- u3 = extractBits(e112, 5u, 10u);
- let e116: vec4<u32> = u4;
- u4 = extractBits(e116, 5u, 10u);
+ let e108: vec2<u32> = u2_;
+ u2_ = extractBits(e108, 5u, 10u);
+ let e112: vec3<u32> = u3_;
+ u3_ = extractBits(e112, 5u, 10u);
+ let e116: vec4<u32> = u4_;
+ u4_ = extractBits(e116, 5u, 10u);
return;
}
diff --git a/tests/out/wgsl/bits_glsl-frag.wgsl b/tests/out/wgsl/bits_glsl-frag.wgsl
--- a/tests/out/wgsl/bits_glsl-frag.wgsl
+++ b/tests/out/wgsl/bits_glsl-frag.wgsl
@@ -1,80 +1,80 @@
-fn main1() {
+fn main_1() {
var i: i32 = 0;
- var i2: vec2<i32> = vec2<i32>(0, 0);
- var i3: vec3<i32> = vec3<i32>(0, 0, 0);
- var i4: vec4<i32> = vec4<i32>(0, 0, 0, 0);
+ var i2_: vec2<i32> = vec2<i32>(0, 0);
+ var i3_: vec3<i32> = vec3<i32>(0, 0, 0);
+ var i4_: vec4<i32> = vec4<i32>(0, 0, 0, 0);
var u: u32 = 0u;
- var u2: vec2<u32> = vec2<u32>(0u, 0u);
- var u3: vec3<u32> = vec3<u32>(0u, 0u, 0u);
- var u4: vec4<u32> = vec4<u32>(0u, 0u, 0u, 0u);
- var f2: vec2<f32> = vec2<f32>(0.0, 0.0);
- var f4: vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 0.0);
+ var u2_: vec2<u32> = vec2<u32>(0u, 0u);
+ var u3_: vec3<u32> = vec3<u32>(0u, 0u, 0u);
+ var u4_: vec4<u32> = vec4<u32>(0u, 0u, 0u, 0u);
+ var f2_: vec2<f32> = vec2<f32>(0.0, 0.0);
+ var f4_: vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 0.0);
- let e33: vec4<f32> = f4;
+ let e33: vec4<f32> = f4_;
u = pack4x8snorm(e33);
- let e36: vec4<f32> = f4;
+ let e36: vec4<f32> = f4_;
u = pack4x8unorm(e36);
- let e39: vec2<f32> = f2;
+ let e39: vec2<f32> = f2_;
u = pack2x16unorm(e39);
- let e42: vec2<f32> = f2;
+ let e42: vec2<f32> = f2_;
u = pack2x16snorm(e42);
- let e45: vec2<f32> = f2;
+ let e45: vec2<f32> = f2_;
u = pack2x16float(e45);
let e48: u32 = u;
- f4 = unpack4x8snorm(e48);
+ f4_ = unpack4x8snorm(e48);
let e51: u32 = u;
- f4 = unpack4x8unorm(e51);
+ f4_ = unpack4x8unorm(e51);
let e54: u32 = u;
- f2 = unpack2x16snorm(e54);
+ f2_ = unpack2x16snorm(e54);
let e57: u32 = u;
- f2 = unpack2x16unorm(e57);
+ f2_ = unpack2x16unorm(e57);
let e60: u32 = u;
- f2 = unpack2x16float(e60);
+ f2_ = unpack2x16float(e60);
let e66: i32 = i;
let e67: i32 = i;
i = insertBits(e66, e67, u32(5), u32(10));
- let e77: vec2<i32> = i2;
- let e78: vec2<i32> = i2;
- i2 = insertBits(e77, e78, u32(5), u32(10));
- let e88: vec3<i32> = i3;
- let e89: vec3<i32> = i3;
- i3 = insertBits(e88, e89, u32(5), u32(10));
- let e99: vec4<i32> = i4;
- let e100: vec4<i32> = i4;
- i4 = insertBits(e99, e100, u32(5), u32(10));
+ let e77: vec2<i32> = i2_;
+ let e78: vec2<i32> = i2_;
+ i2_ = insertBits(e77, e78, u32(5), u32(10));
+ let e88: vec3<i32> = i3_;
+ let e89: vec3<i32> = i3_;
+ i3_ = insertBits(e88, e89, u32(5), u32(10));
+ let e99: vec4<i32> = i4_;
+ let e100: vec4<i32> = i4_;
+ i4_ = insertBits(e99, e100, u32(5), u32(10));
let e110: u32 = u;
let e111: u32 = u;
u = insertBits(e110, e111, u32(5), u32(10));
- let e121: vec2<u32> = u2;
- let e122: vec2<u32> = u2;
- u2 = insertBits(e121, e122, u32(5), u32(10));
- let e132: vec3<u32> = u3;
- let e133: vec3<u32> = u3;
- u3 = insertBits(e132, e133, u32(5), u32(10));
- let e143: vec4<u32> = u4;
- let e144: vec4<u32> = u4;
- u4 = insertBits(e143, e144, u32(5), u32(10));
+ let e121: vec2<u32> = u2_;
+ let e122: vec2<u32> = u2_;
+ u2_ = insertBits(e121, e122, u32(5), u32(10));
+ let e132: vec3<u32> = u3_;
+ let e133: vec3<u32> = u3_;
+ u3_ = insertBits(e132, e133, u32(5), u32(10));
+ let e143: vec4<u32> = u4_;
+ let e144: vec4<u32> = u4_;
+ u4_ = insertBits(e143, e144, u32(5), u32(10));
let e153: i32 = i;
i = extractBits(e153, u32(5), u32(10));
- let e162: vec2<i32> = i2;
- i2 = extractBits(e162, u32(5), u32(10));
- let e171: vec3<i32> = i3;
- i3 = extractBits(e171, u32(5), u32(10));
- let e180: vec4<i32> = i4;
- i4 = extractBits(e180, u32(5), u32(10));
+ let e162: vec2<i32> = i2_;
+ i2_ = extractBits(e162, u32(5), u32(10));
+ let e171: vec3<i32> = i3_;
+ i3_ = extractBits(e171, u32(5), u32(10));
+ let e180: vec4<i32> = i4_;
+ i4_ = extractBits(e180, u32(5), u32(10));
let e189: u32 = u;
u = extractBits(e189, u32(5), u32(10));
- let e198: vec2<u32> = u2;
- u2 = extractBits(e198, u32(5), u32(10));
- let e207: vec3<u32> = u3;
- u3 = extractBits(e207, u32(5), u32(10));
- let e216: vec4<u32> = u4;
- u4 = extractBits(e216, u32(5), u32(10));
+ let e198: vec2<u32> = u2_;
+ u2_ = extractBits(e198, u32(5), u32(10));
+ let e207: vec3<u32> = u3_;
+ u3_ = extractBits(e207, u32(5), u32(10));
+ let e216: vec4<u32> = u4_;
+ u4_ = extractBits(e216, u32(5), u32(10));
return;
}
[[stage(fragment)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl
--- a/tests/out/wgsl/bool-select-frag.wgsl
+++ b/tests/out/wgsl/bool-select-frag.wgsl
@@ -5,30 +5,30 @@ struct FragmentOutput {
var<private> o_color: vec4<f32>;
fn TevPerCompGT(a: f32, b: f32) -> f32 {
- var a1: f32;
- var b1: f32;
+ var a_1: f32;
+ var b_1: f32;
- a1 = a;
- b1 = b;
- let e5: f32 = a1;
- let e6: f32 = b1;
+ a_1 = a;
+ b_1 = b;
+ let e5: f32 = a_1;
+ let e6: f32 = b_1;
return select(0.0, 1.0, (e5 > e6));
}
-fn TevPerCompGT1(a2: vec3<f32>, b2: vec3<f32>) -> vec3<f32> {
- var a3: vec3<f32>;
- var b3: vec3<f32>;
+fn TevPerCompGT_1(a_2: vec3<f32>, b_2: vec3<f32>) -> vec3<f32> {
+ var a_3: vec3<f32>;
+ var b_3: vec3<f32>;
- a3 = a2;
- b3 = b2;
- let e7: vec3<f32> = a3;
- let e8: vec3<f32> = b3;
+ a_3 = a_2;
+ b_3 = b_2;
+ let e7: vec3<f32> = a_3;
+ let e8: vec3<f32> = b_3;
return select(vec3<f32>(0.0), vec3<f32>(1.0), (e7 > e8));
}
-fn main1() {
+fn main_1() {
let e1: vec4<f32> = o_color;
- let e11: vec3<f32> = TevPerCompGT1(vec3<f32>(3.0), vec3<f32>(5.0));
+ let e11: vec3<f32> = TevPerCompGT_1(vec3<f32>(3.0), vec3<f32>(5.0));
o_color.x = e11.x;
o_color.y = e11.y;
o_color.z = e11.z;
diff --git a/tests/out/wgsl/bool-select-frag.wgsl b/tests/out/wgsl/bool-select-frag.wgsl
--- a/tests/out/wgsl/bool-select-frag.wgsl
+++ b/tests/out/wgsl/bool-select-frag.wgsl
@@ -39,7 +39,7 @@ fn main1() {
[[stage(fragment)]]
fn main() -> FragmentOutput {
- main1();
+ main_1();
let e3: vec4<f32> = o_color;
return FragmentOutput(e3);
}
diff --git a/tests/out/wgsl/clamp-splat-vert.wgsl b/tests/out/wgsl/clamp-splat-vert.wgsl
--- a/tests/out/wgsl/clamp-splat-vert.wgsl
+++ b/tests/out/wgsl/clamp-splat-vert.wgsl
@@ -2,19 +2,19 @@ struct VertexOutput {
[[builtin(position)]] member: vec4<f32>;
};
-var<private> a_pos1: vec2<f32>;
+var<private> a_pos_1: vec2<f32>;
var<private> gl_Position: vec4<f32>;
-fn main1() {
- let e5: vec2<f32> = a_pos1;
+fn main_1() {
+ let e5: vec2<f32> = a_pos_1;
gl_Position = vec4<f32>(clamp(e5, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0, 1.0);
return;
}
[[stage(vertex)]]
fn main([[location(0)]] a_pos: vec2<f32>) -> VertexOutput {
- a_pos1 = a_pos;
- main1();
+ a_pos_1 = a_pos;
+ main_1();
let e5: vec4<f32> = gl_Position;
return VertexOutput(e5);
}
diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl
--- a/tests/out/wgsl/constant-array-size-vert.wgsl
+++ b/tests/out/wgsl/constant-array-size-vert.wgsl
@@ -6,7 +6,7 @@ struct Data {
[[group(1), binding(0)]]
var<uniform> global: Data;
-fn function1() -> vec4<f32> {
+fn function_() -> vec4<f32> {
var sum: vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 0.0);
var i: i32 = 0;
diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl
--- a/tests/out/wgsl/constant-array-size-vert.wgsl
+++ b/tests/out/wgsl/constant-array-size-vert.wgsl
@@ -30,12 +30,12 @@ fn function1() -> vec4<f32> {
return e20;
}
-fn main1() {
+fn main_1() {
return;
}
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/empty-global-name.wgsl b/tests/out/wgsl/empty-global-name.wgsl
--- a/tests/out/wgsl/empty-global-name.wgsl
+++ b/tests/out/wgsl/empty-global-name.wgsl
@@ -1,18 +1,18 @@
[[block]]
-struct type2 {
+struct type_1 {
member: i32;
};
[[group(0), binding(0)]]
-var<storage, read_write> global: type2;
+var<storage, read_write> unnamed: type_1;
-fn function1() {
- let e8: i32 = global.member;
- global.member = (e8 + 1);
+fn function_() {
+ let e8: i32 = unnamed.member;
+ unnamed.member = (e8 + 1);
return;
}
[[stage(compute), workgroup_size(64, 1, 1)]]
fn main() {
- function1();
+ function_();
}
diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl
--- a/tests/out/wgsl/expressions-frag.wgsl
+++ b/tests/out/wgsl/expressions-frag.wgsl
@@ -6,172 +6,172 @@ var<private> global: f32;
var<private> o_color: vec4<f32>;
fn testBinOpVecFloat(a: vec4<f32>, b: f32) {
- var a1: vec4<f32>;
- var b1: f32;
+ var a_1: vec4<f32>;
+ var b_1: f32;
var v: vec4<f32>;
- a1 = a;
- b1 = b;
- let e5: vec4<f32> = a1;
+ a_1 = a;
+ b_1 = b;
+ let e5: vec4<f32> = a_1;
v = (e5 * 2.0);
- let e8: vec4<f32> = a1;
+ let e8: vec4<f32> = a_1;
v = (e8 / vec4<f32>(2.0));
- let e12: vec4<f32> = a1;
+ let e12: vec4<f32> = a_1;
v = (e12 + vec4<f32>(2.0));
- let e16: vec4<f32> = a1;
+ let e16: vec4<f32> = a_1;
v = (e16 - vec4<f32>(2.0));
return;
}
-fn testBinOpFloatVec(a2: vec4<f32>, b2: f32) {
- var a3: vec4<f32>;
- var b3: f32;
- var v1: vec4<f32>;
-
- a3 = a2;
- b3 = b2;
- let e5: vec4<f32> = a3;
- let e6: f32 = b3;
- v1 = (e5 * e6);
- let e8: vec4<f32> = a3;
- let e9: f32 = b3;
- v1 = (e8 / vec4<f32>(e9));
- let e12: vec4<f32> = a3;
- let e13: f32 = b3;
- v1 = (e12 + vec4<f32>(e13));
- let e16: vec4<f32> = a3;
- let e17: f32 = b3;
- v1 = (e16 - vec4<f32>(e17));
+fn testBinOpFloatVec(a_2: vec4<f32>, b_2: f32) {
+ var a_3: vec4<f32>;
+ var b_3: f32;
+ var v_1: vec4<f32>;
+
+ a_3 = a_2;
+ b_3 = b_2;
+ let e5: vec4<f32> = a_3;
+ let e6: f32 = b_3;
+ v_1 = (e5 * e6);
+ let e8: vec4<f32> = a_3;
+ let e9: f32 = b_3;
+ v_1 = (e8 / vec4<f32>(e9));
+ let e12: vec4<f32> = a_3;
+ let e13: f32 = b_3;
+ v_1 = (e12 + vec4<f32>(e13));
+ let e16: vec4<f32> = a_3;
+ let e17: f32 = b_3;
+ v_1 = (e16 - vec4<f32>(e17));
return;
}
-fn testBinOpIVecInt(a4: vec4<i32>, b4: i32) {
- var a5: vec4<i32>;
- var b5: i32;
- var v2: vec4<i32>;
-
- a5 = a4;
- b5 = b4;
- let e5: vec4<i32> = a5;
- let e6: i32 = b5;
- v2 = (e5 * e6);
- let e8: vec4<i32> = a5;
- let e9: i32 = b5;
- v2 = (e8 / vec4<i32>(e9));
- let e12: vec4<i32> = a5;
- let e13: i32 = b5;
- v2 = (e12 + vec4<i32>(e13));
- let e16: vec4<i32> = a5;
- let e17: i32 = b5;
- v2 = (e16 - vec4<i32>(e17));
- let e20: vec4<i32> = a5;
- let e21: i32 = b5;
- v2 = (e20 & vec4<i32>(e21));
- let e24: vec4<i32> = a5;
- let e25: i32 = b5;
- v2 = (e24 | vec4<i32>(e25));
- let e28: vec4<i32> = a5;
- let e29: i32 = b5;
- v2 = (e28 ^ vec4<i32>(e29));
- let e32: vec4<i32> = a5;
- let e33: i32 = b5;
- v2 = (e32 >> vec4<u32>(u32(e33)));
- let e37: vec4<i32> = a5;
- let e38: i32 = b5;
- v2 = (e37 << vec4<u32>(u32(e38)));
+fn testBinOpIVecInt(a_4: vec4<i32>, b_4: i32) {
+ var a_5: vec4<i32>;
+ var b_5: i32;
+ var v_2: vec4<i32>;
+
+ a_5 = a_4;
+ b_5 = b_4;
+ let e5: vec4<i32> = a_5;
+ let e6: i32 = b_5;
+ v_2 = (e5 * e6);
+ let e8: vec4<i32> = a_5;
+ let e9: i32 = b_5;
+ v_2 = (e8 / vec4<i32>(e9));
+ let e12: vec4<i32> = a_5;
+ let e13: i32 = b_5;
+ v_2 = (e12 + vec4<i32>(e13));
+ let e16: vec4<i32> = a_5;
+ let e17: i32 = b_5;
+ v_2 = (e16 - vec4<i32>(e17));
+ let e20: vec4<i32> = a_5;
+ let e21: i32 = b_5;
+ v_2 = (e20 & vec4<i32>(e21));
+ let e24: vec4<i32> = a_5;
+ let e25: i32 = b_5;
+ v_2 = (e24 | vec4<i32>(e25));
+ let e28: vec4<i32> = a_5;
+ let e29: i32 = b_5;
+ v_2 = (e28 ^ vec4<i32>(e29));
+ let e32: vec4<i32> = a_5;
+ let e33: i32 = b_5;
+ v_2 = (e32 >> vec4<u32>(u32(e33)));
+ let e37: vec4<i32> = a_5;
+ let e38: i32 = b_5;
+ v_2 = (e37 << vec4<u32>(u32(e38)));
return;
}
-fn testBinOpIntIVec(a6: i32, b6: vec4<i32>) {
- var a7: i32;
- var b7: vec4<i32>;
- var v3: vec4<i32>;
-
- a7 = a6;
- b7 = b6;
- let e5: i32 = a7;
- let e6: vec4<i32> = b7;
- v3 = (e5 * e6);
- let e8: i32 = a7;
- let e9: vec4<i32> = b7;
- v3 = (vec4<i32>(e8) + e9);
- let e12: i32 = a7;
- let e13: vec4<i32> = b7;
- v3 = (vec4<i32>(e12) - e13);
- let e16: i32 = a7;
- let e17: vec4<i32> = b7;
- v3 = (vec4<i32>(e16) & e17);
- let e20: i32 = a7;
- let e21: vec4<i32> = b7;
- v3 = (vec4<i32>(e20) | e21);
- let e24: i32 = a7;
- let e25: vec4<i32> = b7;
- v3 = (vec4<i32>(e24) ^ e25);
+fn testBinOpIntIVec(a_6: i32, b_6: vec4<i32>) {
+ var a_7: i32;
+ var b_7: vec4<i32>;
+ var v_3: vec4<i32>;
+
+ a_7 = a_6;
+ b_7 = b_6;
+ let e5: i32 = a_7;
+ let e6: vec4<i32> = b_7;
+ v_3 = (e5 * e6);
+ let e8: i32 = a_7;
+ let e9: vec4<i32> = b_7;
+ v_3 = (vec4<i32>(e8) + e9);
+ let e12: i32 = a_7;
+ let e13: vec4<i32> = b_7;
+ v_3 = (vec4<i32>(e12) - e13);
+ let e16: i32 = a_7;
+ let e17: vec4<i32> = b_7;
+ v_3 = (vec4<i32>(e16) & e17);
+ let e20: i32 = a_7;
+ let e21: vec4<i32> = b_7;
+ v_3 = (vec4<i32>(e20) | e21);
+ let e24: i32 = a_7;
+ let e25: vec4<i32> = b_7;
+ v_3 = (vec4<i32>(e24) ^ e25);
return;
}
-fn testBinOpUVecUint(a8: vec4<u32>, b8: u32) {
- var a9: vec4<u32>;
- var b9: u32;
- var v4: vec4<u32>;
-
- a9 = a8;
- b9 = b8;
- let e5: vec4<u32> = a9;
- let e6: u32 = b9;
- v4 = (e5 * e6);
- let e8: vec4<u32> = a9;
- let e9: u32 = b9;
- v4 = (e8 / vec4<u32>(e9));
- let e12: vec4<u32> = a9;
- let e13: u32 = b9;
- v4 = (e12 + vec4<u32>(e13));
- let e16: vec4<u32> = a9;
- let e17: u32 = b9;
- v4 = (e16 - vec4<u32>(e17));
- let e20: vec4<u32> = a9;
- let e21: u32 = b9;
- v4 = (e20 & vec4<u32>(e21));
- let e24: vec4<u32> = a9;
- let e25: u32 = b9;
- v4 = (e24 | vec4<u32>(e25));
- let e28: vec4<u32> = a9;
- let e29: u32 = b9;
- v4 = (e28 ^ vec4<u32>(e29));
- let e32: vec4<u32> = a9;
- let e33: u32 = b9;
- v4 = (e32 >> vec4<u32>(e33));
- let e36: vec4<u32> = a9;
- let e37: u32 = b9;
- v4 = (e36 << vec4<u32>(e37));
+fn testBinOpUVecUint(a_8: vec4<u32>, b_8: u32) {
+ var a_9: vec4<u32>;
+ var b_9: u32;
+ var v_4: vec4<u32>;
+
+ a_9 = a_8;
+ b_9 = b_8;
+ let e5: vec4<u32> = a_9;
+ let e6: u32 = b_9;
+ v_4 = (e5 * e6);
+ let e8: vec4<u32> = a_9;
+ let e9: u32 = b_9;
+ v_4 = (e8 / vec4<u32>(e9));
+ let e12: vec4<u32> = a_9;
+ let e13: u32 = b_9;
+ v_4 = (e12 + vec4<u32>(e13));
+ let e16: vec4<u32> = a_9;
+ let e17: u32 = b_9;
+ v_4 = (e16 - vec4<u32>(e17));
+ let e20: vec4<u32> = a_9;
+ let e21: u32 = b_9;
+ v_4 = (e20 & vec4<u32>(e21));
+ let e24: vec4<u32> = a_9;
+ let e25: u32 = b_9;
+ v_4 = (e24 | vec4<u32>(e25));
+ let e28: vec4<u32> = a_9;
+ let e29: u32 = b_9;
+ v_4 = (e28 ^ vec4<u32>(e29));
+ let e32: vec4<u32> = a_9;
+ let e33: u32 = b_9;
+ v_4 = (e32 >> vec4<u32>(e33));
+ let e36: vec4<u32> = a_9;
+ let e37: u32 = b_9;
+ v_4 = (e36 << vec4<u32>(e37));
return;
}
-fn testBinOpUintUVec(a10: u32, b10: vec4<u32>) {
- var a11: u32;
- var b11: vec4<u32>;
- var v5: vec4<u32>;
-
- a11 = a10;
- b11 = b10;
- let e5: u32 = a11;
- let e6: vec4<u32> = b11;
- v5 = (e5 * e6);
- let e8: u32 = a11;
- let e9: vec4<u32> = b11;
- v5 = (vec4<u32>(e8) + e9);
- let e12: u32 = a11;
- let e13: vec4<u32> = b11;
- v5 = (vec4<u32>(e12) - e13);
- let e16: u32 = a11;
- let e17: vec4<u32> = b11;
- v5 = (vec4<u32>(e16) & e17);
- let e20: u32 = a11;
- let e21: vec4<u32> = b11;
- v5 = (vec4<u32>(e20) | e21);
- let e24: u32 = a11;
- let e25: vec4<u32> = b11;
- v5 = (vec4<u32>(e24) ^ e25);
+fn testBinOpUintUVec(a_10: u32, b_10: vec4<u32>) {
+ var a_11: u32;
+ var b_11: vec4<u32>;
+ var v_5: vec4<u32>;
+
+ a_11 = a_10;
+ b_11 = b_10;
+ let e5: u32 = a_11;
+ let e6: vec4<u32> = b_11;
+ v_5 = (e5 * e6);
+ let e8: u32 = a_11;
+ let e9: vec4<u32> = b_11;
+ v_5 = (vec4<u32>(e8) + e9);
+ let e12: u32 = a_11;
+ let e13: vec4<u32> = b_11;
+ v_5 = (vec4<u32>(e12) - e13);
+ let e16: u32 = a_11;
+ let e17: vec4<u32> = b_11;
+ v_5 = (vec4<u32>(e16) & e17);
+ let e20: u32 = a_11;
+ let e21: vec4<u32> = b_11;
+ v_5 = (vec4<u32>(e20) | e21);
+ let e24: u32 = a_11;
+ let e25: vec4<u32> = b_11;
+ v_5 = (vec4<u32>(e24) ^ e25);
return;
}
diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl
--- a/tests/out/wgsl/expressions-frag.wgsl
+++ b/tests/out/wgsl/expressions-frag.wgsl
@@ -181,15 +181,15 @@ fn testStructConstructor() {
}
fn testArrayConstructor() {
- var tree1: array<f32,1u> = array<f32,1u>(0.0);
+ var tree_1: array<f32,1u> = array<f32,1u>(0.0);
}
-fn privatePointer(a12: ptr<function, f32>) {
+fn privatePointer(a_12: ptr<function, f32>) {
return;
}
-fn main1() {
+fn main_1() {
var local: f32;
let e3: f32 = global;
diff --git a/tests/out/wgsl/expressions-frag.wgsl b/tests/out/wgsl/expressions-frag.wgsl
--- a/tests/out/wgsl/expressions-frag.wgsl
+++ b/tests/out/wgsl/expressions-frag.wgsl
@@ -208,6 +208,6 @@ fn main1() {
[[stage(fragment)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl
--- a/tests/out/wgsl/fma-frag.wgsl
+++ b/tests/out/wgsl/fma-frag.wgsl
@@ -1,4 +1,4 @@
-struct Mat4x3 {
+struct Mat4x3_ {
mx: vec4<f32>;
my: vec4<f32>;
mz: vec4<f32>;
diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl
--- a/tests/out/wgsl/fma-frag.wgsl
+++ b/tests/out/wgsl/fma-frag.wgsl
@@ -6,28 +6,28 @@ struct Mat4x3 {
var<private> o_color: vec4<f32>;
-fn Fma(d: ptr<function, Mat4x3>, m: Mat4x3, s: f32) {
- var m1: Mat4x3;
- var s1: f32;
+fn Fma(d: ptr<function, Mat4x3_>, m: Mat4x3_, s: f32) {
+ var m_1: Mat4x3_;
+ var s_1: f32;
- m1 = m;
- s1 = s;
- let e6: Mat4x3 = (*d);
- let e8: Mat4x3 = m1;
- let e10: f32 = s1;
+ m_1 = m;
+ s_1 = s;
+ let e6: Mat4x3_ = (*d);
+ let e8: Mat4x3_ = m_1;
+ let e10: f32 = s_1;
(*d).mx = (e6.mx + (e8.mx * e10));
- let e14: Mat4x3 = (*d);
- let e16: Mat4x3 = m1;
- let e18: f32 = s1;
+ let e14: Mat4x3_ = (*d);
+ let e16: Mat4x3_ = m_1;
+ let e18: f32 = s_1;
(*d).my = (e14.my + (e16.my * e18));
- let e22: Mat4x3 = (*d);
- let e24: Mat4x3 = m1;
- let e26: f32 = s1;
+ let e22: Mat4x3_ = (*d);
+ let e24: Mat4x3_ = m_1;
+ let e26: f32 = s_1;
(*d).mz = (e22.mz + (e24.mz * e26));
return;
}
-fn main1() {
+fn main_1() {
let e1: vec4<f32> = o_color;
let e4: vec4<f32> = vec4<f32>(1.0);
o_color.x = e4.x;
diff --git a/tests/out/wgsl/fma-frag.wgsl b/tests/out/wgsl/fma-frag.wgsl
--- a/tests/out/wgsl/fma-frag.wgsl
+++ b/tests/out/wgsl/fma-frag.wgsl
@@ -39,6 +39,6 @@ fn main1() {
[[stage(fragment)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl
--- a/tests/out/wgsl/global-constant-array-vert.wgsl
+++ b/tests/out/wgsl/global-constant-array-vert.wgsl
@@ -1,6 +1,6 @@
var<private> i: u32;
-fn main1() {
+fn main_1() {
var local: array<f32,2u> = array<f32,2u>(1.0, 2.0);
let e2: u32 = i;
diff --git a/tests/out/wgsl/global-constant-array-vert.wgsl b/tests/out/wgsl/global-constant-array-vert.wgsl
--- a/tests/out/wgsl/global-constant-array-vert.wgsl
+++ b/tests/out/wgsl/global-constant-array-vert.wgsl
@@ -8,6 +8,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl
--- a/tests/out/wgsl/image.wgsl
+++ b/tests/out/wgsl/image.wgsl
@@ -37,20 +37,20 @@ var image_2d_depth: texture_depth_2d;
fn main([[builtin(local_invocation_id)]] local_id: vec3<u32>) {
let dim: vec2<i32> = textureDimensions(image_storage_src);
let itc: vec2<i32> = ((dim * vec2<i32>(local_id.xy)) % vec2<i32>(10, 20));
- let value1: vec4<u32> = textureLoad(image_mipmapped_src, itc, i32(local_id.z));
- let value2: vec4<u32> = textureLoad(image_multisampled_src, itc, i32(local_id.z));
- let value4: vec4<u32> = textureLoad(image_storage_src, itc);
- let value5: vec4<u32> = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1));
- textureStore(image_dst, itc.x, (((value1 + value2) + value4) + value5));
+ let value1_: vec4<u32> = textureLoad(image_mipmapped_src, itc, i32(local_id.z));
+ let value2_: vec4<u32> = textureLoad(image_multisampled_src, itc, i32(local_id.z));
+ let value4_: vec4<u32> = textureLoad(image_storage_src, itc);
+ let value5_: vec4<u32> = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1));
+ textureStore(image_dst, itc.x, (((value1_ + value2_) + value4_) + value5_));
return;
}
[[stage(compute), workgroup_size(16, 1, 1)]]
-fn depth_load([[builtin(local_invocation_id)]] local_id1: vec3<u32>) {
- let dim1: vec2<i32> = textureDimensions(image_storage_src);
- let itc1: vec2<i32> = ((dim1 * vec2<i32>(local_id1.xy)) % vec2<i32>(10, 20));
- let val: f32 = textureLoad(image_depth_multisampled_src, itc1, i32(local_id1.z));
- textureStore(image_dst, itc1.x, vec4<u32>(u32(val)));
+fn depth_load([[builtin(local_invocation_id)]] local_id_1: vec3<u32>) {
+ let dim_1: vec2<i32> = textureDimensions(image_storage_src);
+ let itc_1: vec2<i32> = ((dim_1 * vec2<i32>(local_id_1.xy)) % vec2<i32>(10, 20));
+ let val: f32 = textureLoad(image_depth_multisampled_src, itc_1, i32(local_id_1.z));
+ textureStore(image_dst, itc_1.x, vec4<u32>(u32(val)));
return;
}
diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl
--- a/tests/out/wgsl/image.wgsl
+++ b/tests/out/wgsl/image.wgsl
@@ -81,8 +81,8 @@ fn levels_queries() -> [[builtin(position)]] vec4<f32> {
let num_layers_cube: i32 = textureNumLayers(image_cube_array);
let num_levels_3d: i32 = textureNumLevels(image_3d);
let num_samples_aa: i32 = textureNumSamples(image_aa);
- let sum1: i32 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array);
- return vec4<f32>(f32(sum1));
+ let sum_1: i32 = (((((((num_layers_2d + num_layers_cube) + num_samples_aa) + num_levels_2d) + num_levels_2d_array) + num_levels_3d) + num_levels_cube) + num_levels_cube_array);
+ return vec4<f32>(f32(sum_1));
}
[[stage(fragment)]]
diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl
--- a/tests/out/wgsl/image.wgsl
+++ b/tests/out/wgsl/image.wgsl
@@ -98,8 +98,8 @@ fn sample() -> [[location(0)]] vec4<f32> {
[[stage(fragment)]]
fn sample_comparison() -> [[location(0)]] f32 {
- let tc1: vec2<f32> = vec2<f32>(0.5);
- let s2d_depth: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, tc1, 0.5);
- let s2d_depth_level: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc1, 0.5);
+ let tc_1: vec2<f32> = vec2<f32>(0.5);
+ let s2d_depth: f32 = textureSampleCompare(image_2d_depth, sampler_cmp, tc_1, 0.5);
+ let s2d_depth_level: f32 = textureSampleCompareLevel(image_2d_depth, sampler_cmp, tc_1, 0.5);
return (s2d_depth + s2d_depth_level);
}
diff --git a/tests/out/wgsl/interface.wgsl b/tests/out/wgsl/interface.wgsl
--- a/tests/out/wgsl/interface.wgsl
+++ b/tests/out/wgsl/interface.wgsl
@@ -20,8 +20,8 @@ fn vertex([[builtin(vertex_index)]] vertex_index: u32, [[builtin(instance_index)
[[stage(fragment)]]
fn fragment(in: VertexOutput, [[builtin(front_facing)]] front_facing: bool, [[builtin(sample_index)]] sample_index: u32, [[builtin(sample_mask)]] sample_mask: u32) -> FragmentOutput {
let mask: u32 = (sample_mask & (1u << sample_index));
- let color1: f32 = select(0.0, 1.0, front_facing);
- return FragmentOutput(in.varying, mask, color1);
+ let color_1: f32 = select(0.0, 1.0, front_facing);
+ return FragmentOutput(in.varying, mask, color_1);
}
[[stage(compute), workgroup_size(1, 1, 1)]]
diff --git a/tests/out/wgsl/interpolate.wgsl b/tests/out/wgsl/interpolate.wgsl
--- a/tests/out/wgsl/interpolate.wgsl
+++ b/tests/out/wgsl/interpolate.wgsl
@@ -26,6 +26,6 @@ fn main() -> FragmentInput {
}
[[stage(fragment)]]
-fn main1(val: FragmentInput) {
+fn main_1(val: FragmentInput) {
return;
}
diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
--- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
+++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
@@ -1,6 +1,6 @@
var<private> a: f32;
-fn main1() {
+fn main_1() {
var b: f32;
var c: f32;
var d: f32;
diff --git a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
--- a/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
+++ b/tests/out/wgsl/inv-hyperbolic-trig-functions.wgsl
@@ -16,5 +16,5 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
}
diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl
--- a/tests/out/wgsl/long-form-matrix-vert.wgsl
+++ b/tests/out/wgsl/long-form-matrix-vert.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var splat: mat2x2<f32> = mat2x2<f32>(vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0));
var normal: mat2x2<f32> = mat2x2<f32>(vec2<f32>(1.0, 1.0), vec2<f32>(2.0, 2.0));
var a: mat2x2<f32> = mat2x2<f32>(vec2<f32>(1.0, 2.0), vec2<f32>(3.0, 4.0));
diff --git a/tests/out/wgsl/long-form-matrix-vert.wgsl b/tests/out/wgsl/long-form-matrix-vert.wgsl
--- a/tests/out/wgsl/long-form-matrix-vert.wgsl
+++ b/tests/out/wgsl/long-form-matrix-vert.wgsl
@@ -25,6 +25,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl
--- a/tests/out/wgsl/math-functions-vert.wgsl
+++ b/tests/out/wgsl/math-functions-vert.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var a: vec4<f32> = vec4<f32>(1.0, 1.0, 1.0, 1.0);
var b: vec4<f32> = vec4<f32>(2.0, 2.0, 2.0, 2.0);
var m: mat4x4<f32>;
diff --git a/tests/out/wgsl/math-functions-vert.wgsl b/tests/out/wgsl/math-functions-vert.wgsl
--- a/tests/out/wgsl/math-functions-vert.wgsl
+++ b/tests/out/wgsl/math-functions-vert.wgsl
@@ -149,6 +149,6 @@ fn main1() {
[[stage(vertex)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl
--- a/tests/out/wgsl/operators.wgsl
+++ b/tests/out/wgsl/operators.wgsl
@@ -8,15 +8,15 @@ let v_f32_zero: vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 0.0);
let v_f32_half: vec4<f32> = vec4<f32>(0.5, 0.5, 0.5, 0.5);
let v_i32_one: vec4<i32> = vec4<i32>(1, 1, 1, 1);
fn builtins() -> vec4<f32> {
- let s1: i32 = select(0, 1, true);
- let s2: vec4<f32> = select(vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(1.0, 1.0, 1.0, 1.0), true);
- let s3: vec4<f32> = select(vec4<f32>(1.0, 1.0, 1.0, 1.0), vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<bool>(false, false, false, false));
- let m1: vec4<f32> = mix(vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(1.0, 1.0, 1.0, 1.0), vec4<f32>(0.5, 0.5, 0.5, 0.5));
- let m2: vec4<f32> = mix(vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(1.0, 1.0, 1.0, 1.0), 0.10000000149011612);
- let b1: f32 = bitcast<f32>(vec4<i32>(1, 1, 1, 1).x);
- let b2: vec4<f32> = bitcast<vec4<f32>>(vec4<i32>(1, 1, 1, 1));
+ let s1_: i32 = select(0, 1, true);
+ let s2_: vec4<f32> = select(vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(1.0, 1.0, 1.0, 1.0), true);
+ let s3_: vec4<f32> = select(vec4<f32>(1.0, 1.0, 1.0, 1.0), vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<bool>(false, false, false, false));
+ let m1_: vec4<f32> = mix(vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(1.0, 1.0, 1.0, 1.0), vec4<f32>(0.5, 0.5, 0.5, 0.5));
+ let m2_: vec4<f32> = mix(vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(1.0, 1.0, 1.0, 1.0), 0.10000000149011612);
+ let b1_: f32 = bitcast<f32>(vec4<i32>(1, 1, 1, 1).x);
+ let b2_: vec4<f32> = bitcast<vec4<f32>>(vec4<i32>(1, 1, 1, 1));
let v_i32_zero: vec4<i32> = vec4<i32>(vec4<f32>(0.0, 0.0, 0.0, 0.0));
- return (((((vec4<f32>((vec4<i32>(s1) + v_i32_zero)) + s2) + m1) + m2) + vec4<f32>(b1)) + b2);
+ return (((((vec4<f32>((vec4<i32>(s1_) + v_i32_zero)) + s2_) + m1_) + m2_) + vec4<f32>(b1_)) + b2_);
}
fn splat() -> vec4<f32> {
diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl
--- a/tests/out/wgsl/operators.wgsl
+++ b/tests/out/wgsl/operators.wgsl
@@ -47,8 +47,8 @@ fn constructors() -> f32 {
}
fn modulo() {
- let a1: i32 = (1 % 1);
- let b1: f32 = (1.0 % 1.0);
+ let a_1: i32 = (1 % 1);
+ let b_1: f32 = (1.0 % 1.0);
let c: vec3<i32> = (vec3<i32>(1) % vec3<i32>(1));
let d: vec3<f32> = (vec3<f32>(1.0) % vec3<f32>(1.0));
}
diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl
--- a/tests/out/wgsl/pointers.wgsl
+++ b/tests/out/wgsl/pointers.wgsl
@@ -1,6 +1,6 @@
[[block]]
struct DynamicArray {
- array1: [[stride(4)]] array<u32>;
+ array_: [[stride(4)]] array<u32>;
};
fn f() {
diff --git a/tests/out/wgsl/pointers.wgsl b/tests/out/wgsl/pointers.wgsl
--- a/tests/out/wgsl/pointers.wgsl
+++ b/tests/out/wgsl/pointers.wgsl
@@ -11,9 +11,9 @@ fn f() {
return;
}
-fn index_dynamic_array(p: ptr<workgroup, DynamicArray>, i: i32, v1: u32) -> u32 {
- let old: u32 = (*p).array1[i];
- (*p).array1[i] = v1;
+fn index_dynamic_array(p: ptr<workgroup, DynamicArray>, i: i32, v_1: u32) -> u32 {
+ let old: u32 = (*p).array_[i];
+ (*p).array_[i] = v_1;
return old;
}
diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl
--- a/tests/out/wgsl/prepostfix-frag.wgsl
+++ b/tests/out/wgsl/prepostfix-frag.wgsl
@@ -1,10 +1,10 @@
-fn main1() {
+fn main_1() {
var scalar_target: i32;
var scalar: i32 = 1;
var vec_target: vec2<u32>;
- var vec1: vec2<u32> = vec2<u32>(1u, 1u);
+ var vec_: vec2<u32> = vec2<u32>(1u, 1u);
var mat_target: mat4x3<f32>;
- var mat1: mat4x3<f32> = mat4x3<f32>(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(0.0, 0.0, 1.0), vec3<f32>(0.0, 0.0, 0.0));
+ var mat_: mat4x3<f32> = mat4x3<f32>(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(0.0, 0.0, 1.0), vec3<f32>(0.0, 0.0, 0.0));
let e3: i32 = scalar;
scalar = (e3 + 1);
diff --git a/tests/out/wgsl/prepostfix-frag.wgsl b/tests/out/wgsl/prepostfix-frag.wgsl
--- a/tests/out/wgsl/prepostfix-frag.wgsl
+++ b/tests/out/wgsl/prepostfix-frag.wgsl
@@ -13,28 +13,28 @@ fn main1() {
let e8: i32 = (e6 - 1);
scalar = e8;
scalar_target = e8;
- let e14: vec2<u32> = vec1;
- vec1 = (e14 - vec2<u32>(1u));
+ let e14: vec2<u32> = vec_;
+ vec_ = (e14 - vec2<u32>(1u));
vec_target = e14;
- let e18: vec2<u32> = vec1;
+ let e18: vec2<u32> = vec_;
let e21: vec2<u32> = (e18 + vec2<u32>(1u));
- vec1 = e21;
+ vec_ = e21;
vec_target = e21;
let e24: f32 = f32(1);
- let e32: mat4x3<f32> = mat1;
+ let e32: mat4x3<f32> = mat_;
let e34: vec3<f32> = vec3<f32>(1.0);
- mat1 = (e32 + mat4x3<f32>(e34, e34, e34, e34));
+ mat_ = (e32 + mat4x3<f32>(e34, e34, e34, e34));
mat_target = e32;
- let e37: mat4x3<f32> = mat1;
+ let e37: mat4x3<f32> = mat_;
let e39: vec3<f32> = vec3<f32>(1.0);
let e41: mat4x3<f32> = (e37 - mat4x3<f32>(e39, e39, e39, e39));
- mat1 = e41;
+ mat_ = e41;
mat_target = e41;
return;
}
[[stage(fragment)]]
fn main() {
- main1();
+ main_1();
return;
}
diff --git a/tests/out/wgsl/quad-vert.wgsl b/tests/out/wgsl/quad-vert.wgsl
--- a/tests/out/wgsl/quad-vert.wgsl
+++ b/tests/out/wgsl/quad-vert.wgsl
@@ -9,23 +9,23 @@ struct VertexOutput {
};
var<private> v_uv: vec2<f32>;
-var<private> a_uv1: vec2<f32>;
+var<private> a_uv_1: vec2<f32>;
var<private> perVertexStruct: gl_PerVertex = gl_PerVertex(vec4<f32>(0.0, 0.0, 0.0, 1.0), );
-var<private> a_pos1: vec2<f32>;
+var<private> a_pos_1: vec2<f32>;
-fn main1() {
- let e12: vec2<f32> = a_uv1;
+fn main_1() {
+ let e12: vec2<f32> = a_uv_1;
v_uv = e12;
- let e13: vec2<f32> = a_pos1;
+ let e13: vec2<f32> = a_pos_1;
perVertexStruct.gl_Position = vec4<f32>(e13.x, e13.y, 0.0, 1.0);
return;
}
[[stage(vertex)]]
fn main([[location(1)]] a_uv: vec2<f32>, [[location(0)]] a_pos: vec2<f32>) -> VertexOutput {
- a_uv1 = a_uv;
- a_pos1 = a_pos;
- main1();
+ a_uv_1 = a_uv;
+ a_pos_1 = a_pos;
+ main_1();
let e7: vec2<f32> = v_uv;
let e8: vec4<f32> = perVertexStruct.gl_Position;
return VertexOutput(e7, e8);
diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl
--- a/tests/out/wgsl/quad.wgsl
+++ b/tests/out/wgsl/quad.wgsl
@@ -16,8 +16,8 @@ fn main([[location(0)]] pos: vec2<f32>, [[location(1)]] uv: vec2<f32>) -> Vertex
}
[[stage(fragment)]]
-fn main1([[location(0)]] uv1: vec2<f32>) -> [[location(0)]] vec4<f32> {
- let color: vec4<f32> = textureSample(u_texture, u_sampler, uv1);
+fn main_1([[location(0)]] uv_1: vec2<f32>) -> [[location(0)]] vec4<f32> {
+ let color: vec4<f32> = textureSample(u_texture, u_sampler, uv_1);
if ((color.w == 0.0)) {
discard;
}
diff --git a/tests/out/wgsl/quad_glsl-frag.wgsl b/tests/out/wgsl/quad_glsl-frag.wgsl
--- a/tests/out/wgsl/quad_glsl-frag.wgsl
+++ b/tests/out/wgsl/quad_glsl-frag.wgsl
@@ -2,18 +2,18 @@ struct FragmentOutput {
[[location(0)]] o_color: vec4<f32>;
};
-var<private> v_uv1: vec2<f32>;
+var<private> v_uv_1: vec2<f32>;
var<private> o_color: vec4<f32>;
-fn main1() {
+fn main_1() {
o_color = vec4<f32>(1.0, 1.0, 1.0, 1.0);
return;
}
[[stage(fragment)]]
fn main([[location(0)]] v_uv: vec2<f32>) -> FragmentOutput {
- v_uv1 = v_uv;
- main1();
+ v_uv_1 = v_uv;
+ main_1();
let e7: vec4<f32> = o_color;
return FragmentOutput(e7);
}
diff --git a/tests/out/wgsl/quad_glsl-vert.wgsl b/tests/out/wgsl/quad_glsl-vert.wgsl
--- a/tests/out/wgsl/quad_glsl-vert.wgsl
+++ b/tests/out/wgsl/quad_glsl-vert.wgsl
@@ -3,24 +3,24 @@ struct VertexOutput {
[[builtin(position)]] member: vec4<f32>;
};
-var<private> a_pos1: vec2<f32>;
-var<private> a_uv1: vec2<f32>;
+var<private> a_pos_1: vec2<f32>;
+var<private> a_uv_1: vec2<f32>;
var<private> v_uv: vec2<f32>;
var<private> gl_Position: vec4<f32>;
-fn main1() {
- let e4: vec2<f32> = a_uv1;
+fn main_1() {
+ let e4: vec2<f32> = a_uv_1;
v_uv = e4;
- let e6: vec2<f32> = a_pos1;
+ let e6: vec2<f32> = a_pos_1;
gl_Position = vec4<f32>((1.2000000476837158 * e6), 0.0, 1.0);
return;
}
[[stage(vertex)]]
fn main([[location(0)]] a_pos: vec2<f32>, [[location(1)]] a_uv: vec2<f32>) -> VertexOutput {
- a_pos1 = a_pos;
- a_uv1 = a_uv;
- main1();
+ a_pos_1 = a_pos;
+ a_uv_1 = a_uv;
+ main_1();
let e14: vec2<f32> = v_uv;
let e16: vec4<f32> = gl_Position;
return VertexOutput(e14, e16);
diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl
--- a/tests/out/wgsl/samplers-frag.wgsl
+++ b/tests/out/wgsl/samplers-frag.wgsl
@@ -26,331 +26,331 @@ var texCubeArrayShadow: texture_depth_cube_array;
var tex3DShadow: texture_3d<f32>;
[[group(1), binding(17)]]
var sampShadow: sampler_comparison;
-var<private> texcoord1: vec4<f32>;
+var<private> texcoord_1: vec4<f32>;
fn testTex1D(coord: f32) {
- var coord1: f32;
+ var coord_1: f32;
var c: vec4<f32>;
- coord1 = coord;
- let e18: f32 = coord1;
+ coord_1 = coord;
+ let e18: f32 = coord_1;
let e19: vec4<f32> = textureSample(tex1D, samp, e18);
c = e19;
- let e22: f32 = coord1;
+ let e22: f32 = coord_1;
let e24: vec4<f32> = textureSampleBias(tex1D, samp, e22, 2.0);
c = e24;
- let e28: f32 = coord1;
+ let e28: f32 = coord_1;
let e31: vec4<f32> = textureSampleGrad(tex1D, samp, e28, 4.0, 4.0);
c = e31;
- let e36: f32 = coord1;
+ let e36: f32 = coord_1;
let e40: vec4<f32> = textureSampleGrad(tex1D, samp, e36, 4.0, 4.0, 5);
c = e40;
- let e43: f32 = coord1;
+ let e43: f32 = coord_1;
let e45: vec4<f32> = textureSampleLevel(tex1D, samp, e43, 3.0);
c = e45;
- let e49: f32 = coord1;
+ let e49: f32 = coord_1;
let e52: vec4<f32> = textureSampleLevel(tex1D, samp, e49, 3.0, 5);
c = e52;
- let e55: f32 = coord1;
+ let e55: f32 = coord_1;
let e57: vec4<f32> = textureSample(tex1D, samp, e55, 5);
c = e57;
- let e61: f32 = coord1;
+ let e61: f32 = coord_1;
let e64: vec4<f32> = textureSampleBias(tex1D, samp, e61, 2.0, 5);
c = e64;
- let e65: f32 = coord1;
- let e68: f32 = coord1;
+ let e65: f32 = coord_1;
+ let e68: f32 = coord_1;
let e70: vec2<f32> = vec2<f32>(e68, 6.0);
let e74: vec4<f32> = textureSample(tex1D, samp, (e70.x / e70.y));
c = e74;
- let e75: f32 = coord1;
- let e80: f32 = coord1;
+ let e75: f32 = coord_1;
+ let e80: f32 = coord_1;
let e84: vec4<f32> = vec4<f32>(e80, 0.0, 0.0, 6.0);
let e90: vec4<f32> = textureSample(tex1D, samp, (e84.xyz / vec3<f32>(e84.w)).x);
c = e90;
- let e91: f32 = coord1;
- let e95: f32 = coord1;
+ let e91: f32 = coord_1;
+ let e95: f32 = coord_1;
let e97: vec2<f32> = vec2<f32>(e95, 6.0);
let e102: vec4<f32> = textureSampleBias(tex1D, samp, (e97.x / e97.y), 2.0);
c = e102;
- let e103: f32 = coord1;
- let e109: f32 = coord1;
+ let e103: f32 = coord_1;
+ let e109: f32 = coord_1;
let e113: vec4<f32> = vec4<f32>(e109, 0.0, 0.0, 6.0);
let e120: vec4<f32> = textureSampleBias(tex1D, samp, (e113.xyz / vec3<f32>(e113.w)).x, 2.0);
c = e120;
- let e121: f32 = coord1;
- let e126: f32 = coord1;
+ let e121: f32 = coord_1;
+ let e126: f32 = coord_1;
let e128: vec2<f32> = vec2<f32>(e126, 6.0);
let e134: vec4<f32> = textureSampleGrad(tex1D, samp, (e128.x / e128.y), 4.0, 4.0);
c = e134;
- let e135: f32 = coord1;
- let e142: f32 = coord1;
+ let e135: f32 = coord_1;
+ let e142: f32 = coord_1;
let e146: vec4<f32> = vec4<f32>(e142, 0.0, 0.0, 6.0);
let e154: vec4<f32> = textureSampleGrad(tex1D, samp, (e146.xyz / vec3<f32>(e146.w)).x, 4.0, 4.0);
c = e154;
- let e155: f32 = coord1;
- let e161: f32 = coord1;
+ let e155: f32 = coord_1;
+ let e161: f32 = coord_1;
let e163: vec2<f32> = vec2<f32>(e161, 6.0);
let e170: vec4<f32> = textureSampleGrad(tex1D, samp, (e163.x / e163.y), 4.0, 4.0, 5);
c = e170;
- let e171: f32 = coord1;
- let e179: f32 = coord1;
+ let e171: f32 = coord_1;
+ let e179: f32 = coord_1;
let e183: vec4<f32> = vec4<f32>(e179, 0.0, 0.0, 6.0);
let e192: vec4<f32> = textureSampleGrad(tex1D, samp, (e183.xyz / vec3<f32>(e183.w)).x, 4.0, 4.0, 5);
c = e192;
- let e193: f32 = coord1;
- let e197: f32 = coord1;
+ let e193: f32 = coord_1;
+ let e197: f32 = coord_1;
let e199: vec2<f32> = vec2<f32>(e197, 6.0);
let e204: vec4<f32> = textureSampleLevel(tex1D, samp, (e199.x / e199.y), 3.0);
c = e204;
- let e205: f32 = coord1;
- let e211: f32 = coord1;
+ let e205: f32 = coord_1;
+ let e211: f32 = coord_1;
let e215: vec4<f32> = vec4<f32>(e211, 0.0, 0.0, 6.0);
let e222: vec4<f32> = textureSampleLevel(tex1D, samp, (e215.xyz / vec3<f32>(e215.w)).x, 3.0);
c = e222;
- let e223: f32 = coord1;
- let e228: f32 = coord1;
+ let e223: f32 = coord_1;
+ let e228: f32 = coord_1;
let e230: vec2<f32> = vec2<f32>(e228, 6.0);
let e236: vec4<f32> = textureSampleLevel(tex1D, samp, (e230.x / e230.y), 3.0, 5);
c = e236;
- let e237: f32 = coord1;
- let e244: f32 = coord1;
+ let e237: f32 = coord_1;
+ let e244: f32 = coord_1;
let e248: vec4<f32> = vec4<f32>(e244, 0.0, 0.0, 6.0);
let e256: vec4<f32> = textureSampleLevel(tex1D, samp, (e248.xyz / vec3<f32>(e248.w)).x, 3.0, 5);
c = e256;
- let e257: f32 = coord1;
- let e261: f32 = coord1;
+ let e257: f32 = coord_1;
+ let e261: f32 = coord_1;
let e263: vec2<f32> = vec2<f32>(e261, 6.0);
let e268: vec4<f32> = textureSample(tex1D, samp, (e263.x / e263.y), 5);
c = e268;
- let e269: f32 = coord1;
- let e275: f32 = coord1;
+ let e269: f32 = coord_1;
+ let e275: f32 = coord_1;
let e279: vec4<f32> = vec4<f32>(e275, 0.0, 0.0, 6.0);
let e286: vec4<f32> = textureSample(tex1D, samp, (e279.xyz / vec3<f32>(e279.w)).x, 5);
c = e286;
- let e287: f32 = coord1;
- let e292: f32 = coord1;
+ let e287: f32 = coord_1;
+ let e292: f32 = coord_1;
let e294: vec2<f32> = vec2<f32>(e292, 6.0);
let e300: vec4<f32> = textureSampleBias(tex1D, samp, (e294.x / e294.y), 2.0, 5);
c = e300;
- let e301: f32 = coord1;
- let e308: f32 = coord1;
+ let e301: f32 = coord_1;
+ let e308: f32 = coord_1;
let e312: vec4<f32> = vec4<f32>(e308, 0.0, 0.0, 6.0);
let e320: vec4<f32> = textureSampleBias(tex1D, samp, (e312.xyz / vec3<f32>(e312.w)).x, 2.0, 5);
c = e320;
return;
}
-fn testTex1DArray(coord2: vec2<f32>) {
- var coord3: vec2<f32>;
- var c1: vec4<f32>;
+fn testTex1DArray(coord_2: vec2<f32>) {
+ var coord_3: vec2<f32>;
+ var c_1: vec4<f32>;
- coord3 = coord2;
- let e18: vec2<f32> = coord3;
+ coord_3 = coord_2;
+ let e18: vec2<f32> = coord_3;
let e22: vec4<f32> = textureSample(tex1DArray, samp, e18.x, i32(e18.y));
- c1 = e22;
- let e25: vec2<f32> = coord3;
+ c_1 = e22;
+ let e25: vec2<f32> = coord_3;
let e30: vec4<f32> = textureSampleBias(tex1DArray, samp, e25.x, i32(e25.y), 2.0);
- c1 = e30;
- let e34: vec2<f32> = coord3;
+ c_1 = e30;
+ let e34: vec2<f32> = coord_3;
let e40: vec4<f32> = textureSampleGrad(tex1DArray, samp, e34.x, i32(e34.y), 4.0, 4.0);
- c1 = e40;
- let e45: vec2<f32> = coord3;
+ c_1 = e40;
+ let e45: vec2<f32> = coord_3;
let e52: vec4<f32> = textureSampleGrad(tex1DArray, samp, e45.x, i32(e45.y), 4.0, 4.0, 5);
- c1 = e52;
- let e55: vec2<f32> = coord3;
+ c_1 = e52;
+ let e55: vec2<f32> = coord_3;
let e60: vec4<f32> = textureSampleLevel(tex1DArray, samp, e55.x, i32(e55.y), 3.0);
- c1 = e60;
- let e64: vec2<f32> = coord3;
+ c_1 = e60;
+ let e64: vec2<f32> = coord_3;
let e70: vec4<f32> = textureSampleLevel(tex1DArray, samp, e64.x, i32(e64.y), 3.0, 5);
- c1 = e70;
- let e73: vec2<f32> = coord3;
+ c_1 = e70;
+ let e73: vec2<f32> = coord_3;
let e78: vec4<f32> = textureSample(tex1DArray, samp, e73.x, i32(e73.y), 5);
- c1 = e78;
- let e82: vec2<f32> = coord3;
+ c_1 = e78;
+ let e82: vec2<f32> = coord_3;
let e88: vec4<f32> = textureSampleBias(tex1DArray, samp, e82.x, i32(e82.y), 2.0, 5);
- c1 = e88;
+ c_1 = e88;
return;
}
-fn testTex2D(coord4: vec2<f32>) {
- var coord5: vec2<f32>;
- var c2: vec4<f32>;
+fn testTex2D(coord_4: vec2<f32>) {
+ var coord_5: vec2<f32>;
+ var c_2: vec4<f32>;
- coord5 = coord4;
- let e18: vec2<f32> = coord5;
+ coord_5 = coord_4;
+ let e18: vec2<f32> = coord_5;
let e19: vec4<f32> = textureSample(tex2D, samp, e18);
- c2 = e19;
- let e22: vec2<f32> = coord5;
+ c_2 = e19;
+ let e22: vec2<f32> = coord_5;
let e24: vec4<f32> = textureSampleBias(tex2D, samp, e22, 2.0);
- c2 = e24;
- let e30: vec2<f32> = coord5;
+ c_2 = e24;
+ let e30: vec2<f32> = coord_5;
let e35: vec4<f32> = textureSampleGrad(tex2D, samp, e30, vec2<f32>(4.0), vec2<f32>(4.0));
- c2 = e35;
- let e43: vec2<f32> = coord5;
+ c_2 = e35;
+ let e43: vec2<f32> = coord_5;
let e50: vec4<f32> = textureSampleGrad(tex2D, samp, e43, vec2<f32>(4.0), vec2<f32>(4.0), vec2<i32>(5, 5));
- c2 = e50;
- let e53: vec2<f32> = coord5;
+ c_2 = e50;
+ let e53: vec2<f32> = coord_5;
let e55: vec4<f32> = textureSampleLevel(tex2D, samp, e53, 3.0);
- c2 = e55;
- let e60: vec2<f32> = coord5;
+ c_2 = e55;
+ let e60: vec2<f32> = coord_5;
let e64: vec4<f32> = textureSampleLevel(tex2D, samp, e60, 3.0, vec2<i32>(5, 5));
- c2 = e64;
- let e68: vec2<f32> = coord5;
+ c_2 = e64;
+ let e68: vec2<f32> = coord_5;
let e71: vec4<f32> = textureSample(tex2D, samp, e68, vec2<i32>(5, 5));
- c2 = e71;
- let e76: vec2<f32> = coord5;
+ c_2 = e71;
+ let e76: vec2<f32> = coord_5;
let e80: vec4<f32> = textureSampleBias(tex2D, samp, e76, 2.0, vec2<i32>(5, 5));
- c2 = e80;
- let e81: vec2<f32> = coord5;
- let e84: vec2<f32> = coord5;
+ c_2 = e80;
+ let e81: vec2<f32> = coord_5;
+ let e84: vec2<f32> = coord_5;
let e86: vec3<f32> = vec3<f32>(e84, 6.0);
let e91: vec4<f32> = textureSample(tex2D, samp, (e86.xy / vec2<f32>(e86.z)));
- c2 = e91;
- let e92: vec2<f32> = coord5;
- let e96: vec2<f32> = coord5;
+ c_2 = e91;
+ let e92: vec2<f32> = coord_5;
+ let e96: vec2<f32> = coord_5;
let e99: vec4<f32> = vec4<f32>(e96, 0.0, 6.0);
let e105: vec4<f32> = textureSample(tex2D, samp, (e99.xyz / vec3<f32>(e99.w)).xy);
- c2 = e105;
- let e106: vec2<f32> = coord5;
- let e110: vec2<f32> = coord5;
+ c_2 = e105;
+ let e106: vec2<f32> = coord_5;
+ let e110: vec2<f32> = coord_5;
let e112: vec3<f32> = vec3<f32>(e110, 6.0);
let e118: vec4<f32> = textureSampleBias(tex2D, samp, (e112.xy / vec2<f32>(e112.z)), 2.0);
- c2 = e118;
- let e119: vec2<f32> = coord5;
- let e124: vec2<f32> = coord5;
+ c_2 = e118;
+ let e119: vec2<f32> = coord_5;
+ let e124: vec2<f32> = coord_5;
let e127: vec4<f32> = vec4<f32>(e124, 0.0, 6.0);
let e134: vec4<f32> = textureSampleBias(tex2D, samp, (e127.xyz / vec3<f32>(e127.w)).xy, 2.0);
- c2 = e134;
- let e135: vec2<f32> = coord5;
- let e142: vec2<f32> = coord5;
+ c_2 = e134;
+ let e135: vec2<f32> = coord_5;
+ let e142: vec2<f32> = coord_5;
let e144: vec3<f32> = vec3<f32>(e142, 6.0);
let e153: vec4<f32> = textureSampleGrad(tex2D, samp, (e144.xy / vec2<f32>(e144.z)), vec2<f32>(4.0), vec2<f32>(4.0));
- c2 = e153;
- let e154: vec2<f32> = coord5;
- let e162: vec2<f32> = coord5;
+ c_2 = e153;
+ let e154: vec2<f32> = coord_5;
+ let e162: vec2<f32> = coord_5;
let e165: vec4<f32> = vec4<f32>(e162, 0.0, 6.0);
let e175: vec4<f32> = textureSampleGrad(tex2D, samp, (e165.xyz / vec3<f32>(e165.w)).xy, vec2<f32>(4.0), vec2<f32>(4.0));
- c2 = e175;
- let e176: vec2<f32> = coord5;
- let e185: vec2<f32> = coord5;
+ c_2 = e175;
+ let e176: vec2<f32> = coord_5;
+ let e185: vec2<f32> = coord_5;
let e187: vec3<f32> = vec3<f32>(e185, 6.0);
let e198: vec4<f32> = textureSampleGrad(tex2D, samp, (e187.xy / vec2<f32>(e187.z)), vec2<f32>(4.0), vec2<f32>(4.0), vec2<i32>(5, 5));
- c2 = e198;
- let e199: vec2<f32> = coord5;
- let e209: vec2<f32> = coord5;
+ c_2 = e198;
+ let e199: vec2<f32> = coord_5;
+ let e209: vec2<f32> = coord_5;
let e212: vec4<f32> = vec4<f32>(e209, 0.0, 6.0);
let e224: vec4<f32> = textureSampleGrad(tex2D, samp, (e212.xyz / vec3<f32>(e212.w)).xy, vec2<f32>(4.0), vec2<f32>(4.0), vec2<i32>(5, 5));
- c2 = e224;
- let e225: vec2<f32> = coord5;
- let e229: vec2<f32> = coord5;
+ c_2 = e224;
+ let e225: vec2<f32> = coord_5;
+ let e229: vec2<f32> = coord_5;
let e231: vec3<f32> = vec3<f32>(e229, 6.0);
let e237: vec4<f32> = textureSampleLevel(tex2D, samp, (e231.xy / vec2<f32>(e231.z)), 3.0);
- c2 = e237;
- let e238: vec2<f32> = coord5;
- let e243: vec2<f32> = coord5;
+ c_2 = e237;
+ let e238: vec2<f32> = coord_5;
+ let e243: vec2<f32> = coord_5;
let e246: vec4<f32> = vec4<f32>(e243, 0.0, 6.0);
let e253: vec4<f32> = textureSampleLevel(tex2D, samp, (e246.xyz / vec3<f32>(e246.w)).xy, 3.0);
- c2 = e253;
- let e254: vec2<f32> = coord5;
- let e260: vec2<f32> = coord5;
+ c_2 = e253;
+ let e254: vec2<f32> = coord_5;
+ let e260: vec2<f32> = coord_5;
let e262: vec3<f32> = vec3<f32>(e260, 6.0);
let e270: vec4<f32> = textureSampleLevel(tex2D, samp, (e262.xy / vec2<f32>(e262.z)), 3.0, vec2<i32>(5, 5));
- c2 = e270;
- let e271: vec2<f32> = coord5;
- let e278: vec2<f32> = coord5;
+ c_2 = e270;
+ let e271: vec2<f32> = coord_5;
+ let e278: vec2<f32> = coord_5;
let e281: vec4<f32> = vec4<f32>(e278, 0.0, 6.0);
let e290: vec4<f32> = textureSampleLevel(tex2D, samp, (e281.xyz / vec3<f32>(e281.w)).xy, 3.0, vec2<i32>(5, 5));
- c2 = e290;
- let e291: vec2<f32> = coord5;
- let e296: vec2<f32> = coord5;
+ c_2 = e290;
+ let e291: vec2<f32> = coord_5;
+ let e296: vec2<f32> = coord_5;
let e298: vec3<f32> = vec3<f32>(e296, 6.0);
let e305: vec4<f32> = textureSample(tex2D, samp, (e298.xy / vec2<f32>(e298.z)), vec2<i32>(5, 5));
- c2 = e305;
- let e306: vec2<f32> = coord5;
- let e312: vec2<f32> = coord5;
+ c_2 = e305;
+ let e306: vec2<f32> = coord_5;
+ let e312: vec2<f32> = coord_5;
let e315: vec4<f32> = vec4<f32>(e312, 0.0, 6.0);
let e323: vec4<f32> = textureSample(tex2D, samp, (e315.xyz / vec3<f32>(e315.w)).xy, vec2<i32>(5, 5));
- c2 = e323;
- let e324: vec2<f32> = coord5;
- let e330: vec2<f32> = coord5;
+ c_2 = e323;
+ let e324: vec2<f32> = coord_5;
+ let e330: vec2<f32> = coord_5;
let e332: vec3<f32> = vec3<f32>(e330, 6.0);
let e340: vec4<f32> = textureSampleBias(tex2D, samp, (e332.xy / vec2<f32>(e332.z)), 2.0, vec2<i32>(5, 5));
- c2 = e340;
- let e341: vec2<f32> = coord5;
- let e348: vec2<f32> = coord5;
+ c_2 = e340;
+ let e341: vec2<f32> = coord_5;
+ let e348: vec2<f32> = coord_5;
let e351: vec4<f32> = vec4<f32>(e348, 0.0, 6.0);
let e360: vec4<f32> = textureSampleBias(tex2D, samp, (e351.xyz / vec3<f32>(e351.w)).xy, 2.0, vec2<i32>(5, 5));
- c2 = e360;
+ c_2 = e360;
return;
}
-fn testTex2DShadow(coord6: vec2<f32>) {
- var coord7: vec2<f32>;
+fn testTex2DShadow(coord_6: vec2<f32>) {
+ var coord_7: vec2<f32>;
var d: f32;
- coord7 = coord6;
- let e17: vec2<f32> = coord7;
- let e20: vec2<f32> = coord7;
+ coord_7 = coord_6;
+ let e17: vec2<f32> = coord_7;
+ let e20: vec2<f32> = coord_7;
let e22: vec3<f32> = vec3<f32>(e20, 1.0);
let e25: f32 = textureSampleCompare(tex2DShadow, sampShadow, e22.xy, e22.z);
d = e25;
- let e26: vec2<f32> = coord7;
- let e33: vec2<f32> = coord7;
+ let e26: vec2<f32> = coord_7;
+ let e33: vec2<f32> = coord_7;
let e35: vec3<f32> = vec3<f32>(e33, 1.0);
let e42: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e35.xy, e35.z);
d = e42;
- let e43: vec2<f32> = coord7;
- let e52: vec2<f32> = coord7;
+ let e43: vec2<f32> = coord_7;
+ let e52: vec2<f32> = coord_7;
let e54: vec3<f32> = vec3<f32>(e52, 1.0);
let e63: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e54.xy, e54.z, vec2<i32>(5, 5));
d = e63;
- let e64: vec2<f32> = coord7;
- let e68: vec2<f32> = coord7;
+ let e64: vec2<f32> = coord_7;
+ let e68: vec2<f32> = coord_7;
let e70: vec3<f32> = vec3<f32>(e68, 1.0);
let e74: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e70.xy, e70.z);
d = e74;
- let e75: vec2<f32> = coord7;
- let e81: vec2<f32> = coord7;
+ let e75: vec2<f32> = coord_7;
+ let e81: vec2<f32> = coord_7;
let e83: vec3<f32> = vec3<f32>(e81, 1.0);
let e89: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e83.xy, e83.z, vec2<i32>(5, 5));
d = e89;
- let e90: vec2<f32> = coord7;
- let e95: vec2<f32> = coord7;
+ let e90: vec2<f32> = coord_7;
+ let e95: vec2<f32> = coord_7;
let e97: vec3<f32> = vec3<f32>(e95, 1.0);
let e102: f32 = textureSampleCompare(tex2DShadow, sampShadow, e97.xy, e97.z, vec2<i32>(5, 5));
d = e102;
- let e103: vec2<f32> = coord7;
- let e107: vec2<f32> = coord7;
+ let e103: vec2<f32> = coord_7;
+ let e107: vec2<f32> = coord_7;
let e110: vec4<f32> = vec4<f32>(e107, 1.0, 6.0);
let e114: vec3<f32> = (e110.xyz / vec3<f32>(e110.w));
let e117: f32 = textureSampleCompare(tex2DShadow, sampShadow, e114.xy, e114.z);
d = e117;
- let e118: vec2<f32> = coord7;
- let e126: vec2<f32> = coord7;
+ let e118: vec2<f32> = coord_7;
+ let e126: vec2<f32> = coord_7;
let e129: vec4<f32> = vec4<f32>(e126, 1.0, 6.0);
let e137: vec3<f32> = (e129.xyz / vec3<f32>(e129.w));
let e140: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e137.xy, e137.z);
d = e140;
- let e141: vec2<f32> = coord7;
- let e151: vec2<f32> = coord7;
+ let e141: vec2<f32> = coord_7;
+ let e151: vec2<f32> = coord_7;
let e154: vec4<f32> = vec4<f32>(e151, 1.0, 6.0);
let e164: vec3<f32> = (e154.xyz / vec3<f32>(e154.w));
let e167: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e164.xy, e164.z, vec2<i32>(5, 5));
d = e167;
- let e168: vec2<f32> = coord7;
- let e173: vec2<f32> = coord7;
+ let e168: vec2<f32> = coord_7;
+ let e173: vec2<f32> = coord_7;
let e176: vec4<f32> = vec4<f32>(e173, 1.0, 6.0);
let e181: vec3<f32> = (e176.xyz / vec3<f32>(e176.w));
let e184: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e181.xy, e181.z);
d = e184;
- let e185: vec2<f32> = coord7;
- let e192: vec2<f32> = coord7;
+ let e185: vec2<f32> = coord_7;
+ let e192: vec2<f32> = coord_7;
let e195: vec4<f32> = vec4<f32>(e192, 1.0, 6.0);
let e202: vec3<f32> = (e195.xyz / vec3<f32>(e195.w));
let e205: f32 = textureSampleCompareLevel(tex2DShadow, sampShadow, e202.xy, e202.z, vec2<i32>(5, 5));
d = e205;
- let e206: vec2<f32> = coord7;
- let e212: vec2<f32> = coord7;
+ let e206: vec2<f32> = coord_7;
+ let e212: vec2<f32> = coord_7;
let e215: vec4<f32> = vec4<f32>(e212, 1.0, 6.0);
let e221: vec3<f32> = (e215.xyz / vec3<f32>(e215.w));
let e224: f32 = textureSampleCompare(tex2DShadow, sampShadow, e221.xy, e221.z, vec2<i32>(5, 5));
diff --git a/tests/out/wgsl/samplers-frag.wgsl b/tests/out/wgsl/samplers-frag.wgsl
--- a/tests/out/wgsl/samplers-frag.wgsl
+++ b/tests/out/wgsl/samplers-frag.wgsl
@@ -358,217 +358,217 @@ fn testTex2DShadow(coord6: vec2<f32>) {
return;
}
-fn testTex2DArray(coord8: vec3<f32>) {
- var coord9: vec3<f32>;
- var c3: vec4<f32>;
+fn testTex2DArray(coord_8: vec3<f32>) {
+ var coord_9: vec3<f32>;
+ var c_3: vec4<f32>;
- coord9 = coord8;
- let e18: vec3<f32> = coord9;
+ coord_9 = coord_8;
+ let e18: vec3<f32> = coord_9;
let e22: vec4<f32> = textureSample(tex2DArray, samp, e18.xy, i32(e18.z));
- c3 = e22;
- let e25: vec3<f32> = coord9;
+ c_3 = e22;
+ let e25: vec3<f32> = coord_9;
let e30: vec4<f32> = textureSampleBias(tex2DArray, samp, e25.xy, i32(e25.z), 2.0);
- c3 = e30;
- let e36: vec3<f32> = coord9;
+ c_3 = e30;
+ let e36: vec3<f32> = coord_9;
let e44: vec4<f32> = textureSampleGrad(tex2DArray, samp, e36.xy, i32(e36.z), vec2<f32>(4.0), vec2<f32>(4.0));
- c3 = e44;
- let e52: vec3<f32> = coord9;
+ c_3 = e44;
+ let e52: vec3<f32> = coord_9;
let e62: vec4<f32> = textureSampleGrad(tex2DArray, samp, e52.xy, i32(e52.z), vec2<f32>(4.0), vec2<f32>(4.0), vec2<i32>(5, 5));
- c3 = e62;
- let e65: vec3<f32> = coord9;
+ c_3 = e62;
+ let e65: vec3<f32> = coord_9;
let e70: vec4<f32> = textureSampleLevel(tex2DArray, samp, e65.xy, i32(e65.z), 3.0);
- c3 = e70;
- let e75: vec3<f32> = coord9;
+ c_3 = e70;
+ let e75: vec3<f32> = coord_9;
let e82: vec4<f32> = textureSampleLevel(tex2DArray, samp, e75.xy, i32(e75.z), 3.0, vec2<i32>(5, 5));
- c3 = e82;
- let e86: vec3<f32> = coord9;
+ c_3 = e82;
+ let e86: vec3<f32> = coord_9;
let e92: vec4<f32> = textureSample(tex2DArray, samp, e86.xy, i32(e86.z), vec2<i32>(5, 5));
- c3 = e92;
- let e97: vec3<f32> = coord9;
+ c_3 = e92;
+ let e97: vec3<f32> = coord_9;
let e104: vec4<f32> = textureSampleBias(tex2DArray, samp, e97.xy, i32(e97.z), 2.0, vec2<i32>(5, 5));
- c3 = e104;
+ c_3 = e104;
return;
}
-fn testTex2DArrayShadow(coord10: vec3<f32>) {
- var coord11: vec3<f32>;
- var d1: f32;
+fn testTex2DArrayShadow(coord_10: vec3<f32>) {
+ var coord_11: vec3<f32>;
+ var d_1: f32;
- coord11 = coord10;
- let e17: vec3<f32> = coord11;
- let e20: vec3<f32> = coord11;
+ coord_11 = coord_10;
+ let e17: vec3<f32> = coord_11;
+ let e20: vec3<f32> = coord_11;
let e22: vec4<f32> = vec4<f32>(e20, 1.0);
let e27: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, e22.xy, i32(e22.z), e22.w);
- d1 = e27;
- let e28: vec3<f32> = coord11;
- let e35: vec3<f32> = coord11;
+ d_1 = e27;
+ let e28: vec3<f32> = coord_11;
+ let e35: vec3<f32> = coord_11;
let e37: vec4<f32> = vec4<f32>(e35, 1.0);
let e46: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e37.xy, i32(e37.z), e37.w);
- d1 = e46;
- let e47: vec3<f32> = coord11;
- let e56: vec3<f32> = coord11;
+ d_1 = e46;
+ let e47: vec3<f32> = coord_11;
+ let e56: vec3<f32> = coord_11;
let e58: vec4<f32> = vec4<f32>(e56, 1.0);
let e69: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e58.xy, i32(e58.z), e58.w, vec2<i32>(5, 5));
- d1 = e69;
- let e70: vec3<f32> = coord11;
- let e74: vec3<f32> = coord11;
+ d_1 = e69;
+ let e70: vec3<f32> = coord_11;
+ let e74: vec3<f32> = coord_11;
let e76: vec4<f32> = vec4<f32>(e74, 1.0);
let e82: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e76.xy, i32(e76.z), e76.w);
- d1 = e82;
- let e83: vec3<f32> = coord11;
- let e89: vec3<f32> = coord11;
+ d_1 = e82;
+ let e83: vec3<f32> = coord_11;
+ let e89: vec3<f32> = coord_11;
let e91: vec4<f32> = vec4<f32>(e89, 1.0);
let e99: f32 = textureSampleCompareLevel(tex2DArrayShadow, sampShadow, e91.xy, i32(e91.z), e91.w, vec2<i32>(5, 5));
- d1 = e99;
- let e100: vec3<f32> = coord11;
- let e105: vec3<f32> = coord11;
+ d_1 = e99;
+ let e100: vec3<f32> = coord_11;
+ let e105: vec3<f32> = coord_11;
let e107: vec4<f32> = vec4<f32>(e105, 1.0);
let e114: f32 = textureSampleCompare(tex2DArrayShadow, sampShadow, e107.xy, i32(e107.z), e107.w, vec2<i32>(5, 5));
- d1 = e114;
+ d_1 = e114;
return;
}
-fn testTexCube(coord12: vec3<f32>) {
- var coord13: vec3<f32>;
- var c4: vec4<f32>;
+fn testTexCube(coord_12: vec3<f32>) {
+ var coord_13: vec3<f32>;
+ var c_4: vec4<f32>;
- coord13 = coord12;
- let e18: vec3<f32> = coord13;
+ coord_13 = coord_12;
+ let e18: vec3<f32> = coord_13;
let e19: vec4<f32> = textureSample(texCube, samp, e18);
- c4 = e19;
- let e22: vec3<f32> = coord13;
+ c_4 = e19;
+ let e22: vec3<f32> = coord_13;
let e24: vec4<f32> = textureSampleBias(texCube, samp, e22, 2.0);
- c4 = e24;
- let e30: vec3<f32> = coord13;
+ c_4 = e24;
+ let e30: vec3<f32> = coord_13;
let e35: vec4<f32> = textureSampleGrad(texCube, samp, e30, vec3<f32>(4.0), vec3<f32>(4.0));
- c4 = e35;
- let e38: vec3<f32> = coord13;
+ c_4 = e35;
+ let e38: vec3<f32> = coord_13;
let e40: vec4<f32> = textureSampleLevel(texCube, samp, e38, 3.0);
- c4 = e40;
- let e45: vec3<f32> = coord13;
+ c_4 = e40;
+ let e45: vec3<f32> = coord_13;
let e49: vec4<f32> = textureSampleLevel(texCube, samp, e45, 3.0, vec3<i32>(5, 5, 5));
- c4 = e49;
- let e53: vec3<f32> = coord13;
+ c_4 = e49;
+ let e53: vec3<f32> = coord_13;
let e56: vec4<f32> = textureSample(texCube, samp, e53, vec3<i32>(5, 5, 5));
- c4 = e56;
- let e61: vec3<f32> = coord13;
+ c_4 = e56;
+ let e61: vec3<f32> = coord_13;
let e65: vec4<f32> = textureSampleBias(texCube, samp, e61, 2.0, vec3<i32>(5, 5, 5));
- c4 = e65;
+ c_4 = e65;
return;
}
-fn testTexCubeShadow(coord14: vec3<f32>) {
- var coord15: vec3<f32>;
- var d2: f32;
+fn testTexCubeShadow(coord_14: vec3<f32>) {
+ var coord_15: vec3<f32>;
+ var d_2: f32;
- coord15 = coord14;
- let e17: vec3<f32> = coord15;
- let e20: vec3<f32> = coord15;
+ coord_15 = coord_14;
+ let e17: vec3<f32> = coord_15;
+ let e20: vec3<f32> = coord_15;
let e22: vec4<f32> = vec4<f32>(e20, 1.0);
let e25: f32 = textureSampleCompare(texCubeShadow, sampShadow, e22.xyz, e22.w);
- d2 = e25;
- let e26: vec3<f32> = coord15;
- let e33: vec3<f32> = coord15;
+ d_2 = e25;
+ let e26: vec3<f32> = coord_15;
+ let e33: vec3<f32> = coord_15;
let e35: vec4<f32> = vec4<f32>(e33, 1.0);
let e42: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e35.xyz, e35.w);
- d2 = e42;
- let e43: vec3<f32> = coord15;
- let e47: vec3<f32> = coord15;
+ d_2 = e42;
+ let e43: vec3<f32> = coord_15;
+ let e47: vec3<f32> = coord_15;
let e49: vec4<f32> = vec4<f32>(e47, 1.0);
let e53: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e49.xyz, e49.w);
- d2 = e53;
- let e54: vec3<f32> = coord15;
- let e60: vec3<f32> = coord15;
+ d_2 = e53;
+ let e54: vec3<f32> = coord_15;
+ let e60: vec3<f32> = coord_15;
let e62: vec4<f32> = vec4<f32>(e60, 1.0);
let e68: f32 = textureSampleCompareLevel(texCubeShadow, sampShadow, e62.xyz, e62.w, vec3<i32>(5, 5, 5));
- d2 = e68;
- let e69: vec3<f32> = coord15;
- let e74: vec3<f32> = coord15;
+ d_2 = e68;
+ let e69: vec3<f32> = coord_15;
+ let e74: vec3<f32> = coord_15;
let e76: vec4<f32> = vec4<f32>(e74, 1.0);
let e81: f32 = textureSampleCompare(texCubeShadow, sampShadow, e76.xyz, e76.w, vec3<i32>(5, 5, 5));
- d2 = e81;
+ d_2 = e81;
return;
}
-fn testTexCubeArray(coord16: vec4<f32>) {
- var coord17: vec4<f32>;
- var c5: vec4<f32>;
+fn testTexCubeArray(coord_16: vec4<f32>) {
+ var coord_17: vec4<f32>;
+ var c_5: vec4<f32>;
- coord17 = coord16;
- let e18: vec4<f32> = coord17;
+ coord_17 = coord_16;
+ let e18: vec4<f32> = coord_17;
let e22: vec4<f32> = textureSample(texCubeArray, samp, e18.xyz, i32(e18.w));
- c5 = e22;
- let e25: vec4<f32> = coord17;
+ c_5 = e22;
+ let e25: vec4<f32> = coord_17;
let e30: vec4<f32> = textureSampleBias(texCubeArray, samp, e25.xyz, i32(e25.w), 2.0);
- c5 = e30;
- let e36: vec4<f32> = coord17;
+ c_5 = e30;
+ let e36: vec4<f32> = coord_17;
let e44: vec4<f32> = textureSampleGrad(texCubeArray, samp, e36.xyz, i32(e36.w), vec3<f32>(4.0), vec3<f32>(4.0));
- c5 = e44;
- let e47: vec4<f32> = coord17;
+ c_5 = e44;
+ let e47: vec4<f32> = coord_17;
let e52: vec4<f32> = textureSampleLevel(texCubeArray, samp, e47.xyz, i32(e47.w), 3.0);
- c5 = e52;
- let e57: vec4<f32> = coord17;
+ c_5 = e52;
+ let e57: vec4<f32> = coord_17;
let e64: vec4<f32> = textureSampleLevel(texCubeArray, samp, e57.xyz, i32(e57.w), 3.0, vec3<i32>(5, 5, 5));
- c5 = e64;
- let e68: vec4<f32> = coord17;
+ c_5 = e64;
+ let e68: vec4<f32> = coord_17;
let e74: vec4<f32> = textureSample(texCubeArray, samp, e68.xyz, i32(e68.w), vec3<i32>(5, 5, 5));
- c5 = e74;
- let e79: vec4<f32> = coord17;
+ c_5 = e74;
+ let e79: vec4<f32> = coord_17;
let e86: vec4<f32> = textureSampleBias(texCubeArray, samp, e79.xyz, i32(e79.w), 2.0, vec3<i32>(5, 5, 5));
- c5 = e86;
+ c_5 = e86;
return;
}
-fn testTexCubeArrayShadow(coord18: vec4<f32>) {
- var coord19: vec4<f32>;
- var d3: f32;
+fn testTexCubeArrayShadow(coord_18: vec4<f32>) {
+ var coord_19: vec4<f32>;
+ var d_3: f32;
- coord19 = coord18;
- let e19: vec4<f32> = coord19;
+ coord_19 = coord_18;
+ let e19: vec4<f32> = coord_19;
let e24: f32 = textureSampleCompare(texCubeArrayShadow, sampShadow, e19.xyz, i32(e19.w), 1.0);
- d3 = e24;
+ d_3 = e24;
return;
}
-fn testTex3D(coord20: vec3<f32>) {
- var coord21: vec3<f32>;
- var c6: vec4<f32>;
+fn testTex3D(coord_20: vec3<f32>) {
+ var coord_21: vec3<f32>;
+ var c_6: vec4<f32>;
- coord21 = coord20;
- let e18: vec3<f32> = coord21;
+ coord_21 = coord_20;
+ let e18: vec3<f32> = coord_21;
let e19: vec4<f32> = textureSample(tex3D, samp, e18);
- c6 = e19;
- let e22: vec3<f32> = coord21;
+ c_6 = e19;
+ let e22: vec3<f32> = coord_21;
let e24: vec4<f32> = textureSampleBias(tex3D, samp, e22, 2.0);
- c6 = e24;
- let e30: vec3<f32> = coord21;
+ c_6 = e24;
+ let e30: vec3<f32> = coord_21;
let e35: vec4<f32> = textureSampleGrad(tex3D, samp, e30, vec3<f32>(4.0), vec3<f32>(4.0));
- c6 = e35;
- let e43: vec3<f32> = coord21;
+ c_6 = e35;
+ let e43: vec3<f32> = coord_21;
let e50: vec4<f32> = textureSampleGrad(tex3D, samp, e43, vec3<f32>(4.0), vec3<f32>(4.0), vec3<i32>(5, 5, 5));
- c6 = e50;
- let e53: vec3<f32> = coord21;
+ c_6 = e50;
+ let e53: vec3<f32> = coord_21;
let e55: vec4<f32> = textureSampleLevel(tex3D, samp, e53, 3.0);
- c6 = e55;
- let e60: vec3<f32> = coord21;
+ c_6 = e55;
+ let e60: vec3<f32> = coord_21;
let e64: vec4<f32> = textureSampleLevel(tex3D, samp, e60, 3.0, vec3<i32>(5, 5, 5));
- c6 = e64;
- let e68: vec3<f32> = coord21;
+ c_6 = e64;
+ let e68: vec3<f32> = coord_21;
let e71: vec4<f32> = textureSample(tex3D, samp, e68, vec3<i32>(5, 5, 5));
- c6 = e71;
- let e76: vec3<f32> = coord21;
+ c_6 = e71;
+ let e76: vec3<f32> = coord_21;
let e80: vec4<f32> = textureSampleBias(tex3D, samp, e76, 2.0, vec3<i32>(5, 5, 5));
- c6 = e80;
+ c_6 = e80;
return;
}
-fn main1() {
+fn main_1() {
return;
}
[[stage(fragment)]]
fn main([[location(0)]] texcoord: vec4<f32>) {
- texcoord1 = texcoord;
- main1();
+ texcoord_1 = texcoord;
+ main_1();
return;
}
diff --git a/tests/out/wgsl/skybox.wgsl b/tests/out/wgsl/skybox.wgsl
--- a/tests/out/wgsl/skybox.wgsl
+++ b/tests/out/wgsl/skybox.wgsl
@@ -18,13 +18,13 @@ var r_sampler: sampler;
[[stage(vertex)]]
fn vs_main([[builtin(vertex_index)]] vertex_index: u32) -> VertexOutput {
- var tmp1: i32;
- var tmp2: i32;
+ var tmp1_: i32;
+ var tmp2_: i32;
- tmp1 = (i32(vertex_index) / 2);
- tmp2 = (i32(vertex_index) & 1);
- let e10: i32 = tmp1;
- let e16: i32 = tmp2;
+ tmp1_ = (i32(vertex_index) / 2);
+ tmp2_ = (i32(vertex_index) & 1);
+ let e10: i32 = tmp1_;
+ let e16: i32 = tmp2_;
let pos: vec4<f32> = vec4<f32>(((f32(e10) * 4.0) - 1.0), ((f32(e16) * 4.0) - 1.0), 0.0, 1.0);
let e27: vec4<f32> = r_data.view[0];
let e31: vec4<f32> = r_data.view[1];
diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl
--- a/tests/out/wgsl/swizzle_write-frag.wgsl
+++ b/tests/out/wgsl/swizzle_write-frag.wgsl
@@ -1,4 +1,4 @@
-fn main1() {
+fn main_1() {
var x: vec3<f32> = vec3<f32>(2.0, 2.0, 2.0);
let e3: vec3<f32> = x;
diff --git a/tests/out/wgsl/swizzle_write-frag.wgsl b/tests/out/wgsl/swizzle_write-frag.wgsl
--- a/tests/out/wgsl/swizzle_write-frag.wgsl
+++ b/tests/out/wgsl/swizzle_write-frag.wgsl
@@ -15,6 +15,6 @@ fn main1() {
[[stage(fragment)]]
fn main() {
- main1();
+ main_1();
return;
}
|
water example triggers shader compiler error
On a M1 MacBook, doing `cargo run --example water` results in the following.
```
Finished dev [unoptimized + debuginfo] target(s) in 0.15s
Running `target/debug/examples/water`
Using Apple M1 (Metal)
[2021-11-02T03:41:04Z ERROR wgpu::backend::direct] Handling wgpu errors as fatal by default
thread 'main' panicked at 'wgpu error: Validation Error
Caused by:
In Device::create_render_pipeline
note: label = `water`
Internal error in VERTEX shader: Metal: Compilation failed:
program_source:65:19: error: redefinition of 'x1' with a different type: 'metal::float3' (aka 'float3') vs 'metal::float4' (aka 'float4')
metal::float3 x1 = (x0 - i1) + C.xxx;
^
program_source:46:19: note: previous definition is here
metal::float4 x1;
^
program_source:128:81: error: no matching function for call to 'dot'
return 9.0 * metal::dot(_e213 * _e214, metal::float4(metal::dot(_e216, x0), metal::dot(_e218, x1), metal::dot(_e220, x2), metal::dot(_e222, x3)));
^~~~~~~~~~
/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/31001/Libraries/lib/clang/31001.192/include/metal/metal_geometric:104:18: note: candidate function not viable: no known conversion from 'metal::float4' (aka 'float4') to 'metal::float3' (aka 'float3') for 2nd argument
METAL_FUNC float dot(float3 x, float3 y)
^
/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/31001/Libraries/lib/clang/31001.192/include/metal/metal_geometric:112:18: note: candidate function not viable: no known conversion from 'metal::float3' (aka 'float3') to 'metal::float4' (aka 'float4') for 1st argument
METAL_FUNC float dot(float4 x, float4 y)
^
/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/31001/Libraries/lib/clang/31001.192/include/metal/metal_geometric:52:17: note: candidate function not viable: no known conversion from 'metal::float3' (aka 'float3') to 'metal::half2' (aka 'half2') for 1st argument
METAL_FUNC half dot(half2 x, half2 y)
^
/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/31001/Libraries/lib/clang/31001.192/include/metal/metal_geometric:60:17: note: candidate function not viable: no known conversion from 'metal::float3' (aka 'float3') to 'metal::half3' (aka 'half3') for 1st argument
METAL_FUNC half dot(half3 x, half3 y)
^
/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/31001/Libraries/lib/clang/31001.192/include/metal/metal_geometric:68:17: note: candidate function not viable: no known conversion from 'metal::float3' (aka 'float3') to 'metal::half4' (aka 'half4') for 1st argument
METAL_FUNC half dot(half4 x, half4 y)
^
/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/31001/Libraries/lib/clang/31001.192/include/metal/metal_geometric:96:18: note: candidate function not viable: no known conversion from 'metal::float3' (aka 'float3') to 'metal::float2' (aka 'float2') for 1st argument
METAL_FUNC float dot(float2 x, float2 y)
^
', wgpu/src/backend/direct.rs:2211:5
```
|
Looks like we are spewing the shader code that uses variable shadowing. We shouldn't be doing this.
|
2021-11-04T02:08:36Z
|
0.7
|
2021-12-02T03:19:49Z
|
33c1daeceef9268a9502df0720d69c9aa9b464da
|
[
"proc::namer::test"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::spv::test::parse",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::expressions",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_decimal_floats",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_statement",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_hex_floats",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_postfix",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_texture_query",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"proc::test_matrix_size",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_inference",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_spv_inverse_hyperbolic_trig_functions",
"convert_spv_empty_global_name",
"convert_spv_quad_vert",
"convert_spv_shadow",
"convert_glsl_folder",
"convert_wgsl",
"cube_array",
"geometry",
"sampler1d",
"storage1d",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"bad_for_initializer",
"function_without_identifier",
"bad_texture_sample_type",
"inconsistent_binding",
"invalid_integer",
"invalid_float",
"bad_type_cast",
"dead_code",
"invalid_arrays",
"let_type_mismatch",
"invalid_runtime_sized_arrays",
"invalid_functions",
"invalid_structs",
"invalid_texture_sample_type",
"last_case_falltrough",
"invalid_access",
"local_var_missing_type",
"bad_texture",
"invalid_local_vars",
"struct_member_zero_size",
"struct_member_zero_align",
"local_var_type_mismatch",
"unknown_access",
"unknown_attribute",
"unknown_built_in",
"unknown_conservative_depth",
"unknown_scalar_type",
"pointer_type_equivalence",
"unknown_ident",
"unknown_shader_stage",
"unknown_local_function",
"negative_index",
"unknown_storage_format",
"unknown_storage_class",
"unknown_type",
"zero_array_stride",
"unknown_identifier",
"missing_bindings",
"postfix_pointers",
"select",
"valid_access",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
gfx-rs/naga
| 1,139
|
gfx-rs__naga-1139
|
[
"1138"
] |
e97c8f944121a58bbc908ecb64bdf97d4ada039d
|
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -101,11 +101,15 @@ impl super::TypeInner {
kind: _,
width,
} => (size as u8 * width) as u32,
+ // matrices are treated as arrays of aligned columns
Self::Matrix {
columns,
rows,
width,
- } => (columns as u8 * rows as u8 * width) as u32,
+ } => {
+ let aligned_rows = if rows > crate::VectorSize::Bi { 4 } else { 2 };
+ columns as u32 * aligned_rows * width as u32
+ }
Self::Pointer { .. } | Self::ValuePointer { .. } => POINTER_SPAN,
Self::Array {
base: _,
|
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -318,3 +322,17 @@ impl super::SwizzleComponent {
}
}
}
+
+#[test]
+fn test_matrix_size() {
+ let constants = crate::Arena::new();
+ assert_eq!(
+ crate::TypeInner::Matrix {
+ columns: crate::VectorSize::Tri,
+ rows: crate::VectorSize::Tri,
+ width: 4
+ }
+ .span(&constants),
+ 48
+ );
+}
|
[wgsl-in] Size of nx3 matrices is not to spec, resulting in overlapping fields
This struct declaration:
```
struct Foo {
m: mat3x3<f32>;
f: f32;
};
```
Produces this spir-v:
```
; SPIR-V
; Version: 1.0
; Generator: Khronos; 28
; Bound: 7
; Schema: 0
OpCapability Shader
OpCapability Linkage
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpSource GLSL 450
OpName %Foo "Foo"
OpMemberName %Foo 0 "m"
OpMemberName %Foo 1 "f"
OpMemberDecorate %Foo 0 Offset 0
OpMemberDecorate %Foo 0 ColMajor
OpMemberDecorate %Foo 0 MatrixStride 16
OpMemberDecorate %Foo 1 Offset 36
%void = OpTypeVoid
%float = OpTypeFloat 32
%v3float = OpTypeVector %float 3
%mat3v3float = OpTypeMatrix %v3float 3
%Foo = OpTypeStruct %mat3v3float %float
```
`f` has been given offset 36 in the struct, but [per the spec](https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size) the size of `m` should be 48. Since the stride of `m` has correctly been set to 16, it does actually have a size of 48 and so `f` overlaps with `m`.
|
2021-07-26T22:37:50Z
|
0.5
|
2021-07-26T14:40:50Z
|
c39810233274b0973fe0fcbfedb3ced8c9f685b6
|
[
"proc::test_matrix_size"
] |
[
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"back::msl::test_error_size",
"arena::tests::fetch_or_append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"back::msl::writer::test_stack_size",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::vector_indexing",
"front::glsl::parser_tests::control_flow",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_struct_instantiation",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_store",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::lexer::test_variable_decl",
"valid::analyzer::uniform_control_flow",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_spv_pointer_access",
"convert_spv_shadow",
"convert_spv_quad_vert",
"convert_glsl_folder",
"convert_wgsl",
"function_without_identifier",
"bad_for_initializer",
"inconsistent_binding",
"bad_texture_sample_type",
"invalid_float",
"invalid_integer",
"invalid_scalar_width",
"bad_type_cast",
"invalid_arrays",
"invalid_functions",
"invalid_structs",
"local_var_missing_type",
"let_type_mismatch",
"invalid_texture_sample_type",
"invalid_access",
"invalid_local_vars",
"bad_texture",
"unknown_attribute",
"struct_member_zero_align",
"struct_member_zero_size",
"unknown_access",
"local_var_type_mismatch",
"unknown_shader_stage",
"unknown_conservative_depth",
"unknown_built_in",
"unknown_storage_class",
"unknown_scalar_type",
"unknown_type",
"unknown_storage_format",
"unknown_local_function",
"unknown_ident",
"negative_index",
"unknown_identifier",
"zero_array_stride",
"missing_bindings",
"valid_access"
] |
[] |
[] |
|
gfx-rs/naga
| 1,006
|
gfx-rs__naga-1006
|
[
"1003"
] |
3a4d6fa29584228e206ecb1d0eeac6dd565cdb1c
|
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -955,6 +955,7 @@ pub enum TypeQualifier {
WorkGroupSize(usize, u32),
Sampling(Sampling),
Layout(StructLayout),
+ Precision(Precision),
EarlyFragmentTests,
}
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -984,6 +985,14 @@ pub enum StructLayout {
Std430,
}
+// TODO: Encode precision hints in the IR
+#[derive(Debug, Clone, PartialEq, Copy)]
+pub enum Precision {
+ Low,
+ Medium,
+ High,
+}
+
#[derive(Debug, Clone, PartialEq, Copy)]
pub enum ParameterQualifier {
In,
diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs
--- a/src/front/glsl/lex.rs
+++ b/src/front/glsl/lex.rs
@@ -1,4 +1,5 @@
use super::{
+ ast::Precision,
token::{SourceMetadata, Token, TokenValue},
types::parse_type,
};
diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs
--- a/src/front/glsl/lex.rs
+++ b/src/front/glsl/lex.rs
@@ -58,6 +59,7 @@ impl<'a> Iterator for Lexer<'a> {
PPTokenValue::Float(float) => TokenValue::FloatConstant(float),
PPTokenValue::Ident(ident) => {
match ident.as_str() {
+ // Qualifiers
"layout" => TokenValue::Layout,
"in" => TokenValue::In,
"out" => TokenValue::Out,
diff --git a/src/front/glsl/lex.rs b/src/front/glsl/lex.rs
--- a/src/front/glsl/lex.rs
+++ b/src/front/glsl/lex.rs
@@ -70,6 +72,10 @@ impl<'a> Iterator for Lexer<'a> {
"sample" => TokenValue::Sampling(crate::Sampling::Sample),
"const" => TokenValue::Const,
"inout" => TokenValue::InOut,
+ "precision" => TokenValue::Precision,
+ "highp" => TokenValue::PrecisionQualifier(Precision::High),
+ "mediump" => TokenValue::PrecisionQualifier(Precision::Medium),
+ "lowp" => TokenValue::PrecisionQualifier(Precision::Low),
// values
"true" => TokenValue::BoolConstant(true),
"false" => TokenValue::BoolConstant(false),
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -10,9 +10,11 @@ use super::{
Program,
};
use crate::{
- arena::Handle, front::glsl::error::ExpectedToken, Arena, ArraySize, BinaryOperator, Block,
- Constant, ConstantInner, Expression, Function, FunctionResult, ResourceBinding, ScalarValue,
- Statement, StorageClass, StructMember, SwitchCase, Type, TypeInner, UnaryOperator,
+ arena::Handle,
+ front::glsl::{ast::Precision, error::ExpectedToken},
+ Arena, ArraySize, BinaryOperator, Block, Constant, ConstantInner, Expression, Function,
+ FunctionResult, ResourceBinding, ScalarKind, ScalarValue, Statement, StorageClass,
+ StructMember, SwitchCase, Type, TypeInner, UnaryOperator,
};
use core::convert::TryFrom;
use std::{iter::Peekable, mem};
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -206,6 +208,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
self.lexer.peek().map_or(false, |t| match t.value {
TokenValue::Interpolation(_)
| TokenValue::Sampling(_)
+ | TokenValue::PrecisionQualifier(_)
| TokenValue::Const
| TokenValue::In
| TokenValue::Out
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -241,7 +244,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
StorageQualifier::StorageClass(StorageClass::Storage),
),
TokenValue::Sampling(s) => TypeQualifier::Sampling(s),
-
+ TokenValue::PrecisionQualifier(p) => TypeQualifier::Precision(p),
_ => unreachable!(),
},
token.meta,
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -829,7 +832,51 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
}
}
} else {
- Ok(false)
+ match self.lexer.peek().map(|t| &t.value) {
+ Some(&TokenValue::Precision) => {
+ // PRECISION precision_qualifier type_specifier SEMICOLON
+ self.bump()?;
+
+ let token = self.bump()?;
+ let _ = match token.value {
+ TokenValue::PrecisionQualifier(p) => p,
+ _ => {
+ return Err(ErrorKind::InvalidToken(
+ token,
+ vec![
+ TokenValue::PrecisionQualifier(Precision::High).into(),
+ TokenValue::PrecisionQualifier(Precision::Medium).into(),
+ TokenValue::PrecisionQualifier(Precision::Low).into(),
+ ],
+ ))
+ }
+ };
+
+ let (ty, meta) = self.parse_type_non_void()?;
+
+ match self.program.module.types[ty].inner {
+ TypeInner::Scalar {
+ kind: ScalarKind::Float,
+ ..
+ }
+ | TypeInner::Scalar {
+ kind: ScalarKind::Sint,
+ ..
+ } => {}
+ _ => {
+ return Err(ErrorKind::SemanticError(
+ meta,
+ "Precision statement can only work on floats and ints".into(),
+ ))
+ }
+ }
+
+ self.expect(TokenValue::Semicolon)?;
+
+ Ok(true)
+ }
+ _ => Ok(false),
+ }
}
}
diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs
--- a/src/front/glsl/token.rs
+++ b/src/front/glsl/token.rs
@@ -1,5 +1,6 @@
pub use pp_rs::token::{Float, Integer, PreprocessorError};
+use super::ast::Precision;
use crate::{Interpolation, Sampling, Type};
use std::{fmt, ops::Range};
diff --git a/src/front/glsl/token.rs b/src/front/glsl/token.rs
--- a/src/front/glsl/token.rs
+++ b/src/front/glsl/token.rs
@@ -57,6 +58,8 @@ pub enum TokenValue {
Const,
Interpolation(Interpolation),
Sampling(Sampling),
+ Precision,
+ PrecisionQualifier(Precision),
Continue,
Break,
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -8,6 +8,16 @@ use super::ast::*;
use super::error::ErrorKind;
use super::token::SourceMetadata;
+macro_rules! qualifier_arm {
+ ($src:expr, $tgt:expr, $meta:expr, $msg:literal $(,)?) => {{
+ if $tgt.is_some() {
+ return Err(ErrorKind::SemanticError($meta, $msg.into()));
+ }
+
+ $tgt = Some($src);
+ }};
+}
+
pub struct VarDeclaration<'a> {
pub qualifiers: &'a [(TypeQualifier, SourceMetadata)],
pub ty: Handle<Type>,
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -94,7 +104,7 @@ impl Program<'_> {
),
"gl_VertexIndex" => add_builtin(
TypeInner::Scalar {
- kind: ScalarKind::Sint,
+ kind: ScalarKind::Uint,
width: 4,
},
BuiltIn::VertexIndex,
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -103,7 +113,7 @@ impl Program<'_> {
),
"gl_InstanceIndex" => add_builtin(
TypeInner::Scalar {
- kind: ScalarKind::Sint,
+ kind: ScalarKind::Uint,
width: 4,
},
BuiltIn::InstanceIndex,
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -123,7 +133,7 @@ impl Program<'_> {
"gl_FrontFacing" => add_builtin(
TypeInner::Scalar {
kind: ScalarKind::Bool,
- width: 1,
+ width: crate::BOOL_WIDTH,
},
BuiltIn::FrontFacing,
false,
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -292,6 +302,7 @@ impl Program<'_> {
let mut location = None;
let mut sampling = None;
let mut layout = None;
+ let mut precision = None;
for &(ref qualifier, meta) in qualifiers {
match *qualifier {
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -310,57 +321,42 @@ impl Program<'_> {
storage = s;
}
- TypeQualifier::Interpolation(i) => {
- if interpolation.is_some() {
- return Err(ErrorKind::SemanticError(
- meta,
- "Cannot use more than one interpolation qualifier per declaration"
- .into(),
- ));
- }
-
- interpolation = Some(i);
- }
- TypeQualifier::ResourceBinding(ref r) => {
- if binding.is_some() {
- return Err(ErrorKind::SemanticError(
- meta,
- "Cannot use more than one binding per declaration".into(),
- ));
- }
-
- binding = Some(r.clone());
- }
- TypeQualifier::Location(l) => {
- if location.is_some() {
- return Err(ErrorKind::SemanticError(
- meta,
- "Cannot use more than one binding per declaration".into(),
- ));
- }
-
- location = Some(l);
- }
- TypeQualifier::Sampling(s) => {
- if sampling.is_some() {
- return Err(ErrorKind::SemanticError(
- meta,
- "Cannot use more than one sampling qualifier per declaration".into(),
- ));
- }
-
- sampling = Some(s);
- }
- TypeQualifier::Layout(ref l) => {
- if layout.is_some() {
- return Err(ErrorKind::SemanticError(
- meta,
- "Cannot use more than one layout qualifier per declaration".into(),
- ));
- }
-
- layout = Some(l);
- }
+ TypeQualifier::Interpolation(i) => qualifier_arm!(
+ i,
+ interpolation,
+ meta,
+ "Cannot use more than one interpolation qualifier per declaration"
+ ),
+ TypeQualifier::ResourceBinding(ref r) => qualifier_arm!(
+ r.clone(),
+ binding,
+ meta,
+ "Cannot use more than one binding per declaration"
+ ),
+ TypeQualifier::Location(l) => qualifier_arm!(
+ l,
+ location,
+ meta,
+ "Cannot use more than one binding per declaration"
+ ),
+ TypeQualifier::Sampling(s) => qualifier_arm!(
+ s,
+ sampling,
+ meta,
+ "Cannot use more than one sampling qualifier per declaration"
+ ),
+ TypeQualifier::Layout(ref l) => qualifier_arm!(
+ l,
+ layout,
+ meta,
+ "Cannot use more than one layout qualifier per declaration"
+ ),
+ TypeQualifier::Precision(ref p) => qualifier_arm!(
+ p,
+ precision,
+ meta,
+ "Cannot use more than one precision qualifier per declaration"
+ ),
_ => {
return Err(ErrorKind::SemanticError(
meta,
|
diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs
--- a/src/front/glsl/parser_tests.rs
+++ b/src/front/glsl/parser_tests.rs
@@ -246,6 +246,15 @@ fn declarations() {
&entry_points,
)
.unwrap();
+
+ let _program = parse_program(
+ r#"
+ #version 450
+ precision highp float;
+ "#,
+ &entry_points,
+ )
+ .unwrap();
}
#[test]
|
[glsl-in] precision statement is not parsed
As a statement, `precision highp float;` shouldn't cause an error.
|
2021-06-22T04:33:55Z
|
0.5
|
2021-06-21T20:37:09Z
|
c39810233274b0973fe0fcbfedb3ced8c9f685b6
|
[
"front::glsl::parser_tests::declarations"
] |
[
"arena::tests::fetch_or_append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::layout::test_logical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_types",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_query",
"front::glsl::parser_tests::control_flow",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_spv_pointer_access",
"convert_spv_quad_vert",
"convert_glsl_folder",
"convert_spv_shadow",
"convert_wgsl",
"function_without_identifier",
"invalid_float",
"invalid_integer",
"invalid_scalar_width",
"invalid_texture_sample_type",
"invalid_arrays",
"invalid_structs",
"invalid_local_vars",
"unknown_identifier",
"invalid_functions",
"invalid_access",
"negative_index",
"valid_access",
"missing_bindings"
] |
[] |
[] |
|
gfx-rs/naga
| 933
|
gfx-rs__naga-933
|
[
"931"
] |
61bfb29963fba9a7e8807bdd7ca1c5e5a8b76fec
|
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -12,11 +12,17 @@ use crate::{
};
#[derive(Debug, Clone, Copy)]
-pub enum GlobalLookup {
+pub enum GlobalLookupKind {
Variable(Handle<GlobalVariable>),
BlockSelect(Handle<GlobalVariable>, u32),
}
+#[derive(Debug, Clone, Copy)]
+pub struct GlobalLookup {
+ pub kind: GlobalLookupKind,
+ pub entry_arg: Option<usize>,
+}
+
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct FunctionSignature {
pub name: String,
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -33,6 +39,13 @@ pub struct FunctionDeclaration {
pub void: bool,
}
+bitflags::bitflags! {
+ pub struct EntryArgUse: u32 {
+ const READ = 0x1;
+ const WRITE = 0x2;
+ }
+}
+
#[derive(Debug)]
pub struct Program<'a> {
pub version: u16,
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -45,8 +58,10 @@ pub struct Program<'a> {
pub global_variables: Vec<(String, GlobalLookup)>,
pub constants: Vec<(String, Handle<Constant>)>,
- pub entry_args: Vec<(Binding, bool, Handle<GlobalVariable>)>,
+ pub entry_args: Vec<(Binding, Handle<GlobalVariable>)>,
pub entries: Vec<(String, ShaderStage, Handle<Function>)>,
+ // TODO: More efficient representation
+ pub function_arg_use: Vec<Vec<EntryArgUse>>,
pub module: Module,
}
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -65,6 +80,7 @@ impl<'a> Program<'a> {
entry_args: Vec::new(),
entries: Vec::new(),
+ function_arg_use: Vec::new(),
module: Module::default(),
}
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -150,6 +166,7 @@ pub struct Context<'function> {
expressions: &'function mut Arena<Expression>,
pub locals: &'function mut Arena<LocalVariable>,
pub arguments: &'function mut Vec<FunctionArgument>,
+ pub arg_use: Vec<EntryArgUse>,
//TODO: Find less allocation heavy representation
pub scopes: Vec<FastHashMap<String, VariableReference>>,
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -173,6 +190,7 @@ impl<'function> Context<'function> {
expressions,
locals,
arguments,
+ arg_use: vec![EntryArgUse::empty(); program.entry_args.len()],
scopes: vec![FastHashMap::default()],
lookup_global_var_exps: FastHashMap::with_capacity_and_hasher(
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -186,36 +204,44 @@ impl<'function> Context<'function> {
emitter: Emitter::default(),
};
- this.emit_start();
-
for &(ref name, handle) in program.constants.iter() {
let expr = this.expressions.append(Expression::Constant(handle));
let var = VariableReference {
expr,
load: None,
mutable: false,
+ entry_arg: None,
};
this.lookup_global_var_exps.insert(name.into(), var);
}
+ this.emit_start();
+
for &(ref name, lookup) in program.global_variables.iter() {
this.emit_flush(body);
- let (expr, load) = match lookup {
- GlobalLookup::Variable(v) => (
- Expression::GlobalVariable(v),
- program.module.global_variables[v].class != StorageClass::Handle,
- ),
- GlobalLookup::BlockSelect(handle, index) => {
+ let GlobalLookup { kind, entry_arg } = lookup;
+ let (expr, load) = match kind {
+ GlobalLookupKind::Variable(v) => {
+ let res = (
+ this.expressions.append(Expression::GlobalVariable(v)),
+ program.module.global_variables[v].class != StorageClass::Handle,
+ );
+ this.emit_start();
+
+ res
+ }
+ GlobalLookupKind::BlockSelect(handle, index) => {
let base = this.expressions.append(Expression::GlobalVariable(handle));
+ this.emit_start();
+ let expr = this
+ .expressions
+ .append(Expression::AccessIndex { base, index });
- (Expression::AccessIndex { base, index }, true)
+ (expr, true)
}
};
- let expr = this.expressions.append(expr);
- this.emit_start();
-
let var = VariableReference {
expr,
load: if load {
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -225,6 +251,7 @@ impl<'function> Context<'function> {
},
// TODO: respect constant qualifier
mutable: true,
+ entry_arg,
};
this.lookup_global_var_exps.insert(name.into(), var);
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -285,6 +312,7 @@ impl<'function> Context<'function> {
expr,
load: Some(load),
mutable,
+ entry_arg: None,
},
);
}
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -336,6 +364,7 @@ impl<'function> Context<'function> {
expr,
load,
mutable,
+ entry_arg: None,
},
);
}
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -455,8 +484,16 @@ impl<'function> Context<'function> {
));
}
+ if let Some(idx) = var.entry_arg {
+ self.arg_use[idx] |= EntryArgUse::WRITE
+ }
+
var.expr
} else {
+ if let Some(idx) = var.entry_arg {
+ self.arg_use[idx] |= EntryArgUse::READ
+ }
+
var.load.unwrap_or(var.expr)
}
}
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -617,6 +654,7 @@ pub struct VariableReference {
pub expr: Handle<Expression>,
pub load: Option<Handle<Expression>>,
pub mutable: bool,
+ pub entry_arg: Option<usize>,
}
#[derive(Debug, Clone)]
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -1,8 +1,7 @@
use crate::{
- proc::ensure_block_returns, Arena, BinaryOperator, Binding, Block, BuiltIn, EntryPoint,
- Expression, Function, FunctionArgument, FunctionResult, Handle, MathFunction,
- RelationalFunction, SampleLevel, ScalarKind, ShaderStage, Statement, StructMember,
- SwizzleComponent, Type, TypeInner,
+ proc::ensure_block_returns, Arena, BinaryOperator, Block, EntryPoint, Expression, Function,
+ FunctionArgument, FunctionResult, Handle, MathFunction, RelationalFunction, SampleLevel,
+ ScalarKind, Statement, StructMember, SwizzleComponent, Type, TypeInner,
};
use super::{ast::*, error::ErrorKind, SourceMetadata};
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -392,13 +391,15 @@ impl Program<'_> {
sig: FunctionSignature,
qualifiers: Vec<ParameterQualifier>,
meta: SourceMetadata,
- ) -> Result<(), ErrorKind> {
+ ) -> Result<Handle<Function>, ErrorKind> {
ensure_block_returns(&mut function.body);
let stage = self.entry_points.get(&sig.name);
- if let Some(&stage) = stage {
+ Ok(if let Some(&stage) = stage {
let handle = self.module.functions.append(function);
self.entries.push((sig.name, stage, handle));
+ self.function_arg_use.push(Vec::new());
+ handle
} else {
let void = function.result.is_none();
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -412,7 +413,9 @@ impl Program<'_> {
decl.defined = true;
*self.module.functions.get_mut(decl.handle) = function;
+ decl.handle
} else {
+ self.function_arg_use.push(Vec::new());
let handle = self.module.functions.append(function);
self.lookup_function.insert(
sig,
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -423,10 +426,9 @@ impl Program<'_> {
void,
},
);
+ handle
}
- }
-
- Ok(())
+ })
}
pub fn add_prototype(
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -438,6 +440,7 @@ impl Program<'_> {
) -> Result<(), ErrorKind> {
let void = function.result.is_none();
+ self.function_arg_use.push(Vec::new());
let handle = self.module.functions.append(function);
if self
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -462,17 +465,86 @@ impl Program<'_> {
Ok(())
}
+ fn check_call_global(
+ &self,
+ caller: Handle<Function>,
+ function_arg_use: &mut [Vec<EntryArgUse>],
+ stmt: &Statement,
+ ) {
+ match *stmt {
+ Statement::Block(ref block) => {
+ for stmt in block {
+ self.check_call_global(caller, function_arg_use, stmt)
+ }
+ }
+ Statement::If {
+ ref accept,
+ ref reject,
+ ..
+ } => {
+ for stmt in accept.iter().chain(reject.iter()) {
+ self.check_call_global(caller, function_arg_use, stmt)
+ }
+ }
+ Statement::Switch {
+ ref cases,
+ ref default,
+ ..
+ } => {
+ for stmt in cases
+ .iter()
+ .flat_map(|c| c.body.iter())
+ .chain(default.iter())
+ {
+ self.check_call_global(caller, function_arg_use, stmt)
+ }
+ }
+ Statement::Loop {
+ ref body,
+ ref continuing,
+ } => {
+ for stmt in body.iter().chain(continuing.iter()) {
+ self.check_call_global(caller, function_arg_use, stmt)
+ }
+ }
+ Statement::Call { function, .. } => {
+ let callee_len = function_arg_use[function.index()].len();
+ let caller_len = function_arg_use[caller.index()].len();
+ function_arg_use[caller.index()].extend(
+ std::iter::repeat(EntryArgUse::empty())
+ .take(callee_len.saturating_sub(caller_len)),
+ );
+
+ for i in 0..callee_len.max(caller_len) {
+ let callee_use = function_arg_use[function.index()][i];
+ function_arg_use[caller.index()][i] |= callee_use
+ }
+ }
+ _ => {}
+ }
+ }
+
pub fn add_entry_points(&mut self) {
+ let mut function_arg_use = Vec::new();
+ std::mem::swap(&mut self.function_arg_use, &mut function_arg_use);
+
+ for (handle, function) in self.module.functions.iter() {
+ for stmt in function.body.iter() {
+ self.check_call_global(handle, &mut function_arg_use, stmt)
+ }
+ }
+
for (name, stage, function) in self.entries.iter().cloned() {
let mut arguments = Vec::new();
let mut expressions = Arena::new();
let mut body = Vec::new();
- for (binding, input, handle) in self.entry_args.iter().cloned() {
- match binding {
- Binding::Location { .. } if !input => continue,
- Binding::BuiltIn(builtin) if !should_read(builtin, stage) => continue,
- _ => {}
+ for (i, (binding, handle)) in self.entry_args.iter().cloned().enumerate() {
+ if function_arg_use[function.index()]
+ .get(i)
+ .map_or(true, |u| !u.contains(EntryArgUse::READ))
+ {
+ continue;
}
let ty = self.module.global_variables[handle].ty;
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -500,11 +572,12 @@ impl Program<'_> {
let mut members = Vec::new();
let mut components = Vec::new();
- for (binding, input, handle) in self.entry_args.iter().cloned() {
- match binding {
- Binding::Location { .. } if input => continue,
- Binding::BuiltIn(builtin) if !should_write(builtin, stage) => continue,
- _ => {}
+ for (i, (binding, handle)) in self.entry_args.iter().cloned().enumerate() {
+ if function_arg_use[function.index()]
+ .get(i)
+ .map_or(true, |u| !u.contains(EntryArgUse::WRITE))
+ {
+ continue;
}
let ty = self.module.global_variables[handle].ty;
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -556,40 +629,3 @@ impl Program<'_> {
}
}
}
-
-// FIXME: Both of the functions below should be removed they are a temporary solution
-//
-// The fix should analyze the entry point and children function calls
-// (recursively) and store something like `GlobalUse` and then later only read
-// or store the globals that need to be read or written in that stage
-
-fn should_read(built_in: BuiltIn, stage: ShaderStage) -> bool {
- match (built_in, stage) {
- (BuiltIn::Position, ShaderStage::Fragment)
- | (BuiltIn::BaseInstance, ShaderStage::Vertex)
- | (BuiltIn::BaseVertex, ShaderStage::Vertex)
- | (BuiltIn::ClipDistance, ShaderStage::Fragment)
- | (BuiltIn::InstanceIndex, ShaderStage::Vertex)
- | (BuiltIn::VertexIndex, ShaderStage::Vertex)
- | (BuiltIn::FrontFacing, ShaderStage::Fragment)
- | (BuiltIn::SampleIndex, ShaderStage::Fragment)
- | (BuiltIn::SampleMask, ShaderStage::Fragment)
- | (BuiltIn::GlobalInvocationId, ShaderStage::Compute)
- | (BuiltIn::LocalInvocationId, ShaderStage::Compute)
- | (BuiltIn::LocalInvocationIndex, ShaderStage::Compute)
- | (BuiltIn::WorkGroupId, ShaderStage::Compute)
- | (BuiltIn::WorkGroupSize, ShaderStage::Compute) => true,
- _ => false,
- }
-}
-
-fn should_write(built_in: BuiltIn, stage: ShaderStage) -> bool {
- match (built_in, stage) {
- (BuiltIn::Position, ShaderStage::Vertex)
- | (BuiltIn::ClipDistance, ShaderStage::Vertex)
- | (BuiltIn::PointSize, ShaderStage::Vertex)
- | (BuiltIn::FragDepth, ShaderStage::Fragment)
- | (BuiltIn::SampleMask, ShaderStage::Fragment) => true,
- _ => false,
- }
-}
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -1,7 +1,8 @@
use super::{
ast::{
- Context, FunctionCall, FunctionCallKind, FunctionSignature, GlobalLookup, HirExpr,
- HirExprKind, ParameterQualifier, Profile, StorageQualifier, StructLayout, TypeQualifier,
+ Context, FunctionCall, FunctionCallKind, FunctionSignature, GlobalLookup, GlobalLookupKind,
+ HirExpr, HirExprKind, ParameterQualifier, Profile, StorageQualifier, StructLayout,
+ TypeQualifier,
},
error::ErrorKind,
lex::Lexer,
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -623,7 +624,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
// parse the body
self.parse_compound_statement(&mut context, &mut body)?;
- self.program.add_function(
+ let Context { arg_use, .. } = context;
+ let handle = self.program.add_function(
Function {
name: Some(name),
result,
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -637,6 +639,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
meta,
)?;
+ self.program.function_arg_use[handle.index()] = arg_use;
+
Ok(true)
}
_ => Err(ErrorKind::InvalidToken(token)),
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -800,9 +804,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
});
if let Some(k) = name {
- self.program
- .global_variables
- .push((k, GlobalLookup::Variable(handle)));
+ self.program.global_variables.push((
+ k,
+ GlobalLookup {
+ kind: GlobalLookupKind::Variable(handle),
+ entry_arg: None,
+ },
+ ));
}
for (i, k) in members
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -810,9 +818,13 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
.enumerate()
.filter_map(|(i, m)| m.name.map(|s| (i as u32, s)))
{
- self.program
- .global_variables
- .push((k, GlobalLookup::BlockSelect(handle, i)));
+ self.program.global_variables.push((
+ k,
+ GlobalLookup {
+ kind: GlobalLookupKind::BlockSelect(handle, i),
+ entry_arg: None,
+ },
+ ));
}
Ok(true)
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -45,11 +45,17 @@ impl Program<'_> {
storage_access: StorageAccess::empty(),
});
- self.entry_args
- .push((Binding::BuiltIn(builtin), true, handle));
+ let idx = self.entry_args.len();
+ self.entry_args.push((Binding::BuiltIn(builtin), handle));
- self.global_variables
- .push((name.into(), GlobalLookup::Variable(handle)));
+ self.global_variables.push((
+ name.into(),
+ GlobalLookup {
+ kind: GlobalLookupKind::Variable(handle),
+ entry_arg: Some(idx),
+ },
+ ));
+ ctx.arg_use.push(EntryArgUse::empty());
let expr = ctx.add_expression(Expression::GlobalVariable(handle), body);
let load = ctx.add_expression(Expression::Load { pointer: expr }, body);
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -59,6 +65,7 @@ impl Program<'_> {
expr,
load: Some(load),
mutable,
+ entry_arg: Some(idx),
},
);
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -297,7 +304,6 @@ impl Program<'_> {
}
if let Some(location) = location {
- let input = StorageQualifier::Input == storage;
let interpolation = self.module.types[ty].inner.scalar_kind().map(|kind| {
if let ScalarKind::Float = kind {
Interpolation::Perspective
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -315,18 +321,23 @@ impl Program<'_> {
storage_access: StorageAccess::empty(),
});
+ let idx = self.entry_args.len();
self.entry_args.push((
Binding::Location {
location,
interpolation,
sampling,
},
- input,
handle,
));
- self.global_variables
- .push((name, GlobalLookup::Variable(handle)));
+ self.global_variables.push((
+ name,
+ GlobalLookup {
+ kind: GlobalLookupKind::Variable(handle),
+ entry_arg: Some(idx),
+ },
+ ));
return Ok(ctx.add_expression(Expression::GlobalVariable(handle), body));
} else if let StorageQualifier::Const = storage {
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -369,8 +380,13 @@ impl Program<'_> {
storage_access,
});
- self.global_variables
- .push((name, GlobalLookup::Variable(handle)));
+ self.global_variables.push((
+ name,
+ GlobalLookup {
+ kind: GlobalLookupKind::Variable(handle),
+ entry_arg: None,
+ },
+ ));
Ok(ctx.add_expression(Expression::GlobalVariable(handle), body))
}
|
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -348,15 +348,13 @@ fn convert_spv_shadow() {
}
#[cfg(feature = "glsl-in")]
-// TODO: Reenable tests later
-#[allow(dead_code)]
fn convert_glsl(
name: &str,
entry_points: naga::FastHashMap<String, naga::ShaderStage>,
- _targets: Targets,
+ targets: Targets,
) {
let root = env!("CARGO_MANIFEST_DIR");
- let _module = naga::front::glsl::parse_str(
+ let module = naga::front::glsl::parse_str(
&fs::read_to_string(format!("{}/{}/{}.glsl", root, DIR_IN, name))
.expect("Couldn't find glsl file"),
&naga::front::glsl::Options {
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -365,16 +363,16 @@ fn convert_glsl(
},
)
.unwrap();
- //TODO
- //check_targets(&module, name, targets);
+ println!("{:#?}", module);
+
+ check_targets(&module, name, targets);
}
#[cfg(feature = "glsl-in")]
#[test]
fn convert_glsl_quad() {
- // TODO: Reenable tests later
- // let mut entry_points = naga::FastHashMap::default();
- // entry_points.insert("vert_main".to_string(), naga::ShaderStage::Vertex);
- // entry_points.insert("frag_main".to_string(), naga::ShaderStage::Fragment);
- // convert_glsl("quad-glsl", entry_points, Targets::SPIRV | Targets::IR);
+ let mut entry_points = naga::FastHashMap::default();
+ entry_points.insert("vert_main".to_string(), naga::ShaderStage::Vertex);
+ entry_points.insert("frag_main".to_string(), naga::ShaderStage::Fragment);
+ convert_glsl("quad-glsl", entry_points, Targets::SPIRV | Targets::IR);
}
|
[glsl-in] expression already in scope with constant above function
```glsl
#version 450
const int constant = 10;
float function() {
return 0.0;
}
```
fails to validate with the following error:
```
Function [1] 'function' is invalid:
Expression [1] can't be introduced - it's already in scope
```
Changing the `function` to return `void` or moving the constant below the function "fixes" the error.
This is the module it generates:
```rust
Module {
types: {
[1]: Type {
name: None,
inner: Scalar {
kind: Sint,
width: 4,
},
},
[2]: Type {
name: None,
inner: Scalar {
kind: Float,
width: 4,
},
},
},
constants: {
[1]: Constant {
name: None,
specialization: None,
inner: Scalar {
width: 4,
value: Sint(
10,
),
},
},
[2]: Constant {
name: None,
specialization: None,
inner: Scalar {
width: 4,
value: Float(
0.0,
),
},
},
},
global_variables: {},
functions: {
[1]: Function {
name: Some(
"function",
),
arguments: [],
result: Some(
FunctionResult {
ty: [2],
binding: None,
},
),
local_variables: {},
expressions: {
[1]: Constant(
[1],
),
[2]: Constant(
[2],
),
},
body: [
Emit(
[1..1],
),
Return {
value: Some(
[2],
),
},
],
},
},
entry_points: [],
}
```
|
Thank you for your report, this is an issue with emitting that I have already fixed in my local fork and will make a PR soon
|
2021-06-02T02:31:43Z
|
0.4
|
2021-07-05T11:13:04Z
|
575304a50c102f2e2a3a622b4be567c0ccf6e6c0
|
[
"convert_glsl_quad"
] |
[
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"back::spv::layout::test_logical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::constants",
"front::spv::test::parse",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::control_flow",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_switch",
"front::glsl::parser_tests::declarations",
"front::glsl::parser_tests::functions",
"convert_spv_quad_vert",
"convert_spv_shadow",
"convert_wgsl",
"function_without_identifier",
"invalid_float",
"invalid_scalar_width",
"invalid_integer",
"invalid_texture_sample_type",
"invalid_functions",
"invalid_structs",
"unknown_identifier",
"invalid_arrays",
"missing_bindings"
] |
[] |
[] |
gfx-rs/naga
| 929
|
gfx-rs__naga-929
|
[
"865"
] |
e384bce771db1d7dd156e9e29afe9d9235984924
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## TBD
- API:
+ - atomic types and functions
- WGSL `select()` order of true/false is swapped
## v0.5 (2021-06-18)
diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs
--- a/src/back/dot/mod.rs
+++ b/src/back/dot/mod.rs
@@ -9,7 +9,10 @@ use crate::{
valid::{FunctionInfo, ModuleInfo},
};
-use std::fmt::{Error as FmtError, Write as _};
+use std::{
+ borrow::Cow,
+ fmt::{Error as FmtError, Write as _},
+};
#[derive(Default)]
struct StatementGraph {
diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs
--- a/src/back/dot/mod.rs
+++ b/src/back/dot/mod.rs
@@ -120,6 +123,20 @@ impl StatementGraph {
self.calls.push((id, function));
"Call"
}
+ S::Atomic {
+ pointer,
+ ref fun,
+ value,
+ result,
+ } => {
+ self.emits.push((id, result));
+ self.dependencies.push((id, pointer, "pointer"));
+ self.dependencies.push((id, value, "value"));
+ if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun {
+ self.dependencies.push((id, cmp, "cmp"));
+ }
+ "Atomic"
+ }
};
}
root
diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs
--- a/src/back/dot/mod.rs
+++ b/src/back/dot/mod.rs
@@ -267,9 +284,9 @@ fn write_fun(
if let Some(expr) = level {
edges.insert("level", expr);
}
- std::borrow::Cow::from("ImageSize")
+ Cow::from("ImageSize")
}
- _ => format!("{:?}", query).into(),
+ _ => Cow::Owned(format!("{:?}", query)),
};
(args, 7)
}
diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs
--- a/src/back/dot/mod.rs
+++ b/src/back/dot/mod.rs
@@ -327,7 +344,8 @@ fn write_fun(
};
(string.into(), 3)
}
- E::Call(_function) => ("Call".into(), 4),
+ E::CallResult(_function) => ("CallResult".into(), 4),
+ E::AtomicResult { .. } => ("AtomicResult".into(), 4),
E::ArrayLength(expr) => {
edges.insert("", expr);
("ArrayLength".into(), 7)
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -66,8 +66,26 @@ pub const SUPPORTED_CORE_VERSIONS: &[u16] = &[330, 400, 410, 420, 430, 440, 450]
/// List of supported es glsl versions
pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320];
+//TODO: use `super::BAKE_PREFIX` instead
+const BAKE_PREFIX: &str = "_expr";
+
pub type BindingMap = std::collections::BTreeMap<crate::ResourceBinding, u8>;
+impl crate::AtomicFunction {
+ fn to_glsl(self) -> &'static str {
+ match self {
+ Self::Add => "Add",
+ Self::And => "And",
+ Self::InclusiveOr => "Or",
+ Self::ExclusiveOr => "Xor",
+ Self::Min => "Min",
+ Self::Max => "Max",
+ Self::Exchange { compare: None } => "Exchange",
+ Self::Exchange { compare: Some(_) } => "", //TODO
+ }
+ }
+}
+
/// glsl version
#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -653,6 +671,7 @@ impl<'a, W: Write> Writer<'a, W> {
match *inner {
// Scalars are simple we just get the full name from `glsl_scalar`
TypeInner::Scalar { kind, width }
+ | TypeInner::Atomic { kind, width }
| TypeInner::ValuePointer {
size: None,
kind,
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1326,7 +1345,7 @@ impl<'a, W: Write> Writer<'a, W> {
} else {
let min_ref_count = ctx.expressions[handle].bake_ref_count();
if min_ref_count <= ctx.info[handle].ref_count {
- Some(format!("_expr{}", handle.index()))
+ Some(format!("{}{}", BAKE_PREFIX, handle.index()))
} else {
None
}
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1658,7 +1677,7 @@ impl<'a, W: Write> Writer<'a, W> {
} => {
write!(self.out, "{}", INDENT.repeat(indent))?;
if let Some(expr) = result {
- let name = format!("_expr{}", expr.index());
+ let name = format!("{}{}", BAKE_PREFIX, expr.index());
let result = self.module.functions[function].result.as_ref().unwrap();
self.write_type(result.ty)?;
write!(self.out, " {} = ", name)?;
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1679,6 +1698,31 @@ impl<'a, W: Write> Writer<'a, W> {
self.write_slice(&arguments, |this, _, arg| this.write_expr(*arg, ctx))?;
writeln!(self.out, ");")?
}
+ Statement::Atomic {
+ pointer,
+ ref fun,
+ value,
+ result,
+ } => {
+ write!(self.out, "{}", INDENT.repeat(indent))?;
+ let res_name = format!("{}{}", BAKE_PREFIX, result.index());
+ let res_ty = ctx.info[result].ty.inner_with(&self.module.types);
+ self.write_value_type(res_ty)?;
+ write!(self.out, " {} = ", res_name)?;
+ self.named_expressions.insert(result, res_name);
+
+ let fun_str = fun.to_glsl();
+ write!(self.out, "atomic{}(", fun_str)?;
+ self.write_expr(pointer, ctx)?;
+ if let crate::AtomicFunction::Exchange { compare: Some(_) } = *fun {
+ return Err(Error::Custom(
+ "atomic CompareExchange is not implemented".to_string(),
+ ));
+ }
+ write!(self.out, ", ")?;
+ self.write_expr(value, ctx)?;
+ writeln!(self.out, ");")?;
+ }
}
Ok(())
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -2319,7 +2363,8 @@ impl<'a, W: Write> Writer<'a, W> {
}
}
}
- Expression::Call(_function) => unreachable!(),
+ // These expressions never show up in `Emit`.
+ Expression::CallResult(_) | Expression::AtomicResult { .. } => unreachable!(),
// `ArrayLength` is written as `expr.length()` and we convert it to a uint
Expression::ArrayLength(expr) => {
write!(self.out, "uint(")?;
diff --git a/src/back/hlsl/conv.rs b/src/back/hlsl/conv.rs
--- a/src/back/hlsl/conv.rs
+++ b/src/back/hlsl/conv.rs
@@ -122,3 +122,19 @@ impl crate::Sampling {
}
}
}
+
+impl crate::AtomicFunction {
+ /// Return the HLSL suffix for the `InterlockedXxx` method.
+ pub(super) fn to_hlsl_suffix(self) -> &'static str {
+ match self {
+ Self::Add => "Add",
+ Self::And => "And",
+ Self::InclusiveOr => "Or",
+ Self::ExclusiveOr => "Xor",
+ Self::Min => "Min",
+ Self::Max => "Max",
+ Self::Exchange { compare: None } => "Exchange",
+ Self::Exchange { .. } => "", //TODO
+ }
+ }
+}
diff --git a/src/back/hlsl/storage.rs b/src/back/hlsl/storage.rs
--- a/src/back/hlsl/storage.rs
+++ b/src/back/hlsl/storage.rs
@@ -40,7 +40,7 @@ pub(super) enum StoreValue {
}
impl<W: fmt::Write> super::Writer<'_, W> {
- fn write_storage_address(
+ pub(super) fn write_storage_address(
&mut self,
module: &crate::Module,
chain: &[SubAccess],
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -8,7 +8,7 @@ use crate::{
proc::{self, NameKey},
valid, Handle, Module, ShaderStage, TypeInner,
};
-use std::fmt;
+use std::{fmt, mem};
const LOCATION_SEMANTIC: &str = "LOC";
const SPECIAL_CBUF_TYPE: &str = "NagaConstants";
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -992,38 +992,6 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
writeln!(self.out, ";")?
}
}
- Statement::Call {
- function,
- ref arguments,
- result,
- } => {
- write!(self.out, "{}", INDENT.repeat(indent))?;
- if let Some(expr) = result {
- write!(self.out, "const ")?;
- let name = format!("{}{}", back::BAKE_PREFIX, expr.index());
- let expr_ty = &func_ctx.info[expr].ty;
- match *expr_ty {
- proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?,
- proc::TypeResolution::Value(ref value) => {
- self.write_value_type(module, value)?
- }
- };
- write!(self.out, " {} = ", name)?;
- self.write_expr(module, expr, func_ctx)?;
- self.named_expressions.insert(expr, name);
- }
- let func_name = &self.names[&NameKey::Function(function)];
- write!(self.out, "{}(", func_name)?;
- for (index, argument) in arguments.iter().enumerate() {
- self.write_expr(module, *argument, func_ctx)?;
- // Only write a comma if isn't the last element
- if index != arguments.len().saturating_sub(1) {
- // The leading space is for readability only
- write!(self.out, ", ")?;
- }
- }
- writeln!(self.out, ");")?
- }
Statement::Loop {
ref body,
ref continuing,
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -1107,7 +1075,76 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
self.write_expr(module, value, func_ctx)?;
writeln!(self.out, ";")?;
}
- _ => return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt))),
+ Statement::Call {
+ function,
+ ref arguments,
+ result,
+ } => {
+ write!(self.out, "{}", INDENT.repeat(indent))?;
+ if let Some(expr) = result {
+ write!(self.out, "const ")?;
+ let name = format!("{}{}", back::BAKE_PREFIX, expr.index());
+ let expr_ty = &func_ctx.info[expr].ty;
+ match *expr_ty {
+ proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?,
+ proc::TypeResolution::Value(ref value) => {
+ self.write_value_type(module, value)?
+ }
+ };
+ write!(self.out, " {} = ", name)?;
+ self.named_expressions.insert(expr, name);
+ }
+ let func_name = &self.names[&NameKey::Function(function)];
+ write!(self.out, "{}(", func_name)?;
+ for (index, argument) in arguments.iter().enumerate() {
+ self.write_expr(module, *argument, func_ctx)?;
+ // Only write a comma if isn't the last element
+ if index != arguments.len().saturating_sub(1) {
+ // The leading space is for readability only
+ write!(self.out, ", ")?;
+ }
+ }
+ writeln!(self.out, ");")?
+ }
+ Statement::Atomic {
+ pointer,
+ ref fun,
+ value,
+ result,
+ } => {
+ write!(self.out, "{}", INDENT.repeat(indent))?;
+ let res_name = format!("{}{}", back::BAKE_PREFIX, result.index());
+ match func_ctx.info[result].ty {
+ proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?,
+ proc::TypeResolution::Value(ref value) => {
+ self.write_value_type(module, value)?
+ }
+ };
+
+ let var_handle = self.fill_access_chain(module, pointer, func_ctx)?;
+ // working around the borrow checker in `self.write_expr`
+ let chain = mem::take(&mut self.temp_access_chain);
+ let var_name = &self.names[&NameKey::GlobalVariable(var_handle)];
+
+ let fun_str = fun.to_hlsl_suffix();
+ write!(
+ self.out,
+ " {}; {}.Interlocked{}(",
+ res_name, var_name, fun_str
+ )?;
+ self.write_storage_address(module, &chain, func_ctx)?;
+ if let crate::AtomicFunction::Exchange { compare: Some(_) } = *fun {
+ return Err(Error::Unimplemented("atomic CompareExchange".to_string()));
+ }
+ write!(self.out, ", ")?;
+ self.write_expr(module, value, func_ctx)?;
+ writeln!(self.out, ", {});", res_name)?;
+ self.temp_access_chain = chain;
+ self.named_expressions.insert(result, res_name);
+ }
+ Statement::Switch { .. } => {
+ return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt)))
+ }
}
Ok(())
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -1667,7 +1704,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
write!(self.out, ")")?
}
// Nothing to do here, since call expression already cached
- Expression::Call(_) => {}
+ Expression::CallResult(_) | Expression::AtomicResult { .. } => {}
_ => return Err(Error::Unimplemented(format!("write_expr {:?}", expression))),
}
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -15,6 +15,10 @@ type BackendResult = Result<(), Error>;
const NAMESPACE: &str = "metal";
const WRAPPED_ARRAY_FIELD: &str = "inner";
+// This is a hack: we need to pass a pointer to an atomic,
+// but generally the backend isn't putting "&" in front of every pointer.
+// Some more general handling of pointers is needed to be implemented here.
+const ATOMIC_REFERENCE: &str = "&";
#[derive(Clone)]
struct Level(usize);
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -46,15 +50,18 @@ impl<'a> Display for TypeContext<'a> {
}
match ty.inner {
- // work around Metal toolchain bug with `uint` typedef
- crate::TypeInner::Scalar {
- kind: crate::ScalarKind::Uint,
- ..
- } => {
- write!(out, "metal::uint")
- }
crate::TypeInner::Scalar { kind, .. } => {
- write!(out, "{}", scalar_kind_string(kind))
+ match kind {
+ // work around Metal toolchain bug with `uint` typedef
+ crate::ScalarKind::Uint => write!(out, "{}::uint", NAMESPACE),
+ _ => {
+ let kind_str = scalar_kind_string(kind);
+ write!(out, "{}", kind_str)
+ }
+ }
+ }
+ crate::TypeInner::Atomic { kind, .. } => {
+ write!(out, "{}::atomic_{}", NAMESPACE, scalar_kind_string(kind))
}
crate::TypeInner::Vector { size, kind, .. } => {
write!(
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -409,6 +416,7 @@ impl crate::Type {
Ti::Scalar { .. }
| Ti::Vector { .. }
| Ti::Matrix { .. }
+ | Ti::Atomic { .. }
| Ti::Pointer { .. }
| Ti::ValuePointer { .. } => self.name.is_some(),
// composite types are better to be aliased, regardless of the name
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -709,6 +717,25 @@ impl<W: Write> Writer<W> {
}
}
+ fn put_atomic_fetch(
+ &mut self,
+ pointer: Handle<crate::Expression>,
+ key: &str,
+ value: Handle<crate::Expression>,
+ context: &ExpressionContext,
+ ) -> BackendResult {
+ write!(
+ self.out,
+ "{}::atomic_fetch_{}_explicit({}",
+ NAMESPACE, key, ATOMIC_REFERENCE
+ )?;
+ self.put_expression(pointer, context, true)?;
+ write!(self.out, ", ")?;
+ self.put_expression(value, context, true)?;
+ write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?;
+ Ok(())
+ }
+
fn put_expression(
&mut self,
expr_handle: Handle<crate::Expression>,
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -850,13 +877,11 @@ impl<W: Write> Writer<W> {
// matrices, we wrap them with `float3` on load.
let wrap_packed_vec_scalar_kind = match context.function.expressions[pointer] {
crate::Expression::AccessIndex { base, index } => {
- let ty = match context.resolve_type(base) {
- &crate::TypeInner::Pointer { base, .. } => {
+ let ty = match *context.resolve_type(base) {
+ crate::TypeInner::Pointer { base, .. } => {
&context.module.types[base].inner
}
- // This path is unexpected and shouldn't happen, but it's easier
- // to leave in.
- ty => ty,
+ ref ty => ty,
};
match *ty {
crate::TypeInner::Struct {
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -872,6 +897,15 @@ impl<W: Write> Writer<W> {
}
_ => None,
};
+ let is_atomic = match *context.resolve_type(pointer) {
+ crate::TypeInner::Pointer { base, .. } => {
+ match context.module.types[base].inner {
+ crate::TypeInner::Atomic { .. } => true,
+ _ => false,
+ }
+ }
+ _ => false,
+ };
if let Some(scalar_kind) = wrap_packed_vec_scalar_kind {
write!(
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -882,6 +916,14 @@ impl<W: Write> Writer<W> {
)?;
self.put_expression(pointer, context, true)?;
write!(self.out, ")")?;
+ } else if is_atomic {
+ write!(
+ self.out,
+ "{}::atomic_load_explicit({}",
+ NAMESPACE, ATOMIC_REFERENCE
+ )?;
+ self.put_expression(pointer, context, true)?;
+ write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?;
} else {
// We don't do any dereferencing with `*` here as pointer arguments to functions
// are done by `&` references and not `*` pointers. These do not need to be
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -1167,7 +1209,9 @@ impl<W: Write> Writer<W> {
write!(self.out, ")")?;
}
// has to be a named expression
- crate::Expression::Call(_) => unreachable!(),
+ crate::Expression::CallResult(_) | crate::Expression::AtomicResult { .. } => {
+ unreachable!()
+ }
crate::Expression::ArrayLength(expr) => {
self.put_array_length(expr, context)?;
}
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -1459,39 +1503,48 @@ impl<W: Write> Writer<W> {
}
}
crate::Statement::Store { pointer, value } => {
- // we can't assign fixed-size arrays
let pointer_info = &context.expression.info[pointer];
- let array_size =
+ let (array_size, is_atomic) =
match *pointer_info.ty.inner_with(&context.expression.module.types) {
crate::TypeInner::Pointer { base, .. } => {
match context.expression.module.types[base].inner {
crate::TypeInner::Array {
size: crate::ArraySize::Constant(ch),
..
- } => Some(ch),
- _ => None,
+ } => (Some(ch), false),
+ crate::TypeInner::Atomic { .. } => (None, true),
+ _ => (None, false),
}
}
- _ => None,
+ _ => (None, false),
};
- match array_size {
- Some(const_handle) => {
- let size = context.expression.module.constants[const_handle]
- .to_array_length()
- .unwrap();
- write!(self.out, "{}for(int _i=0; _i<{}; ++_i) ", level, size)?;
- self.put_expression(pointer, &context.expression, true)?;
- write!(self.out, ".{}[_i] = ", WRAPPED_ARRAY_FIELD)?;
- self.put_expression(value, &context.expression, true)?;
- writeln!(self.out, ".{}[_i];", WRAPPED_ARRAY_FIELD)?;
- }
- None => {
- write!(self.out, "{}", level)?;
- self.put_expression(pointer, &context.expression, true)?;
- write!(self.out, " = ")?;
- self.put_expression(value, &context.expression, true)?;
- writeln!(self.out, ";")?;
- }
+
+ // we can't assign fixed-size arrays
+ if let Some(const_handle) = array_size {
+ let size = context.expression.module.constants[const_handle]
+ .to_array_length()
+ .unwrap();
+ write!(self.out, "{}for(int _i=0; _i<{}; ++_i) ", level, size)?;
+ self.put_expression(pointer, &context.expression, true)?;
+ write!(self.out, ".{}[_i] = ", WRAPPED_ARRAY_FIELD)?;
+ self.put_expression(value, &context.expression, true)?;
+ writeln!(self.out, ".{}[_i];", WRAPPED_ARRAY_FIELD)?;
+ } else if is_atomic {
+ write!(
+ self.out,
+ "{}{}::atomic_store_explicit({}",
+ level, NAMESPACE, ATOMIC_REFERENCE
+ )?;
+ self.put_expression(pointer, &context.expression, true)?;
+ write!(self.out, ", ")?;
+ self.put_expression(value, &context.expression, true)?;
+ writeln!(self.out, ", {}::memory_order_relaxed);", NAMESPACE)?;
+ } else {
+ write!(self.out, "{}", level)?;
+ self.put_expression(pointer, &context.expression, true)?;
+ write!(self.out, " = ")?;
+ self.put_expression(value, &context.expression, true)?;
+ writeln!(self.out, ";")?;
}
}
crate::Statement::ImageStore {
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -1562,6 +1615,55 @@ impl<W: Write> Writer<W> {
// done
writeln!(self.out, ");")?;
}
+ crate::Statement::Atomic {
+ pointer,
+ ref fun,
+ value,
+ result,
+ } => {
+ write!(self.out, "{}", level)?;
+ let res_name = format!("{}{}", back::BAKE_PREFIX, result.index());
+ self.start_baking_expression(result, &context.expression, &res_name)?;
+ self.named_expressions.insert(result, res_name);
+ match *fun {
+ crate::AtomicFunction::Add => {
+ self.put_atomic_fetch(pointer, "add", value, &context.expression)?;
+ }
+ crate::AtomicFunction::And => {
+ self.put_atomic_fetch(pointer, "and", value, &context.expression)?;
+ }
+ crate::AtomicFunction::InclusiveOr => {
+ self.put_atomic_fetch(pointer, "or", value, &context.expression)?;
+ }
+ crate::AtomicFunction::ExclusiveOr => {
+ self.put_atomic_fetch(pointer, "xor", value, &context.expression)?;
+ }
+ crate::AtomicFunction::Min => {
+ self.put_atomic_fetch(pointer, "min", value, &context.expression)?;
+ }
+ crate::AtomicFunction::Max => {
+ self.put_atomic_fetch(pointer, "max", value, &context.expression)?;
+ }
+ crate::AtomicFunction::Exchange { compare: None } => {
+ write!(
+ self.out,
+ "{}::atomic_exchange_explicit({}",
+ NAMESPACE, ATOMIC_REFERENCE,
+ )?;
+ self.put_expression(pointer, &context.expression, true)?;
+ write!(self.out, ", ")?;
+ self.put_expression(value, &context.expression, true)?;
+ write!(self.out, ", {}::memory_order_relaxed)", NAMESPACE)?;
+ }
+ crate::AtomicFunction::Exchange { .. } => {
+ return Err(Error::FeatureNotImplemented(
+ "atomic CompareExchange".to_string(),
+ ));
+ }
+ }
+ // done
+ writeln!(self.out, ";")?;
+ }
}
}
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -663,12 +663,35 @@ impl<'w> BlockContext<'w> {
match self.write_expression_pointer(pointer, block)? {
ExpressionPointer::Ready { pointer_id } => {
let id = self.gen_id();
- block
- .body
- .push(Instruction::load(result_type_id, id, pointer_id, None));
+ let atomic_class =
+ match *self.fun_info[pointer].ty.inner_with(&self.ir_module.types) {
+ crate::TypeInner::Pointer { base, class } => {
+ match self.ir_module.types[base].inner {
+ crate::TypeInner::Atomic { .. } => Some(class),
+ _ => None,
+ }
+ }
+ _ => None,
+ };
+ let instruction = if let Some(class) = atomic_class {
+ let (semantics, scope) = class.to_spirv_semantics_and_scope();
+ let scope_constant_id = self.get_scope_constant(scope as u32)?;
+ let semantics_id = self.get_index_constant(semantics.bits())?;
+ Instruction::atomic_load(
+ result_type_id,
+ id,
+ pointer_id,
+ scope_constant_id,
+ semantics_id,
+ )
+ } else {
+ Instruction::load(result_type_id, id, pointer_id, None)
+ };
+ block.body.push(instruction);
id
}
ExpressionPointer::Conditional { condition, access } => {
+ //TODO: support atomics?
self.write_conditional_indexed_load(
result_type_id,
condition,
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -691,7 +714,9 @@ impl<'w> BlockContext<'w> {
}
}
crate::Expression::FunctionArgument(index) => self.function.parameter_id(index),
- crate::Expression::Call(_function) => self.writer.lookup_function_call[&expr_handle],
+ crate::Expression::CallResult(_) | crate::Expression::AtomicResult { .. } => {
+ self.cached[expr_handle]
+ }
crate::Expression::As {
expr,
kind,
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1577,9 +1602,32 @@ impl<'w> BlockContext<'w> {
let value_id = self.cached[value];
match self.write_expression_pointer(pointer, &mut block)? {
ExpressionPointer::Ready { pointer_id } => {
- block
- .body
- .push(Instruction::store(pointer_id, value_id, None));
+ let atomic_class = match *self.fun_info[pointer]
+ .ty
+ .inner_with(&self.ir_module.types)
+ {
+ crate::TypeInner::Pointer { base, class } => {
+ match self.ir_module.types[base].inner {
+ crate::TypeInner::Atomic { .. } => Some(class),
+ _ => None,
+ }
+ }
+ _ => None,
+ };
+ let instruction = if let Some(class) = atomic_class {
+ let (semantics, scope) = class.to_spirv_semantics_and_scope();
+ let scope_constant_id = self.get_scope_constant(scope as u32)?;
+ let semantics_id = self.get_index_constant(semantics.bits())?;
+ Instruction::atomic_store(
+ pointer_id,
+ scope_constant_id,
+ semantics_id,
+ value_id,
+ )
+ } else {
+ Instruction::store(pointer_id, value_id, None)
+ };
+ block.body.push(instruction);
}
ExpressionPointer::Conditional { condition, access } => {
let merge_block = self.gen_id();
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1644,13 +1692,7 @@ impl<'w> BlockContext<'w> {
let type_id = match result {
Some(expr) => {
self.cached[expr] = id;
- self.writer.lookup_function_call.insert(expr, id);
- let ty_handle = self.ir_module.functions[local_function]
- .result
- .as_ref()
- .unwrap()
- .ty;
- self.get_type_id(LookupType::Handle(ty_handle))?
+ self.get_expression_type_id(&self.fun_info[expr].ty)?
}
None => self.writer.void_type,
};
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1662,6 +1704,135 @@ impl<'w> BlockContext<'w> {
&self.temp_list,
));
}
+ crate::Statement::Atomic {
+ pointer,
+ ref fun,
+ value,
+ result,
+ } => {
+ let id = self.gen_id();
+ let result_type_id = self.get_expression_type_id(&self.fun_info[result].ty)?;
+
+ self.cached[result] = id;
+
+ let pointer_id = match self.write_expression_pointer(pointer, &mut block)? {
+ ExpressionPointer::Ready { pointer_id } => pointer_id,
+ ExpressionPointer::Conditional { .. } => {
+ return Err(Error::FeatureNotImplemented(
+ "Atomics out-of-bounds handling",
+ ));
+ }
+ };
+
+ let class = match *self.fun_info[pointer].ty.inner_with(&self.ir_module.types) {
+ crate::TypeInner::Pointer { base: _, class } => class,
+ _ => unimplemented!(),
+ };
+ let (semantics, scope) = class.to_spirv_semantics_and_scope();
+ let scope_constant_id = self.get_scope_constant(scope as u32)?;
+ let semantics_id = self.get_index_constant(semantics.bits())?;
+ let value_id = self.cached[value];
+ let value_inner = self.fun_info[value].ty.inner_with(&self.ir_module.types);
+
+ let instruction = match *fun {
+ crate::AtomicFunction::Add => Instruction::atomic_binary(
+ spirv::Op::AtomicIAdd,
+ result_type_id,
+ id,
+ pointer_id,
+ scope_constant_id,
+ semantics_id,
+ value_id,
+ ),
+ crate::AtomicFunction::And => Instruction::atomic_binary(
+ spirv::Op::AtomicAnd,
+ result_type_id,
+ id,
+ pointer_id,
+ scope_constant_id,
+ semantics_id,
+ value_id,
+ ),
+ crate::AtomicFunction::InclusiveOr => Instruction::atomic_binary(
+ spirv::Op::AtomicOr,
+ result_type_id,
+ id,
+ pointer_id,
+ scope_constant_id,
+ semantics_id,
+ value_id,
+ ),
+ crate::AtomicFunction::ExclusiveOr => Instruction::atomic_binary(
+ spirv::Op::AtomicXor,
+ result_type_id,
+ id,
+ pointer_id,
+ scope_constant_id,
+ semantics_id,
+ value_id,
+ ),
+ crate::AtomicFunction::Min => {
+ let spirv_op = match *value_inner {
+ crate::TypeInner::Scalar {
+ kind: crate::ScalarKind::Sint,
+ width: _,
+ } => spirv::Op::AtomicSMin,
+ crate::TypeInner::Scalar {
+ kind: crate::ScalarKind::Uint,
+ width: _,
+ } => spirv::Op::AtomicUMin,
+ _ => unimplemented!(),
+ };
+ Instruction::atomic_binary(
+ spirv_op,
+ result_type_id,
+ id,
+ pointer_id,
+ scope_constant_id,
+ semantics_id,
+ value_id,
+ )
+ }
+ crate::AtomicFunction::Max => {
+ let spirv_op = match *value_inner {
+ crate::TypeInner::Scalar {
+ kind: crate::ScalarKind::Sint,
+ width: _,
+ } => spirv::Op::AtomicSMax,
+ crate::TypeInner::Scalar {
+ kind: crate::ScalarKind::Uint,
+ width: _,
+ } => spirv::Op::AtomicUMax,
+ _ => unimplemented!(),
+ };
+ Instruction::atomic_binary(
+ spirv_op,
+ result_type_id,
+ id,
+ pointer_id,
+ scope_constant_id,
+ semantics_id,
+ value_id,
+ )
+ }
+ crate::AtomicFunction::Exchange { compare: None } => {
+ Instruction::atomic_binary(
+ spirv::Op::AtomicExchange,
+ result_type_id,
+ id,
+ pointer_id,
+ scope_constant_id,
+ semantics_id,
+ value_id,
+ )
+ }
+ crate::AtomicFunction::Exchange { compare: Some(_) } => {
+ return Err(Error::FeatureNotImplemented("atomic CompareExchange"));
+ }
+ };
+
+ block.body.push(instruction);
+ }
}
}
diff --git a/src/back/spv/helpers.rs b/src/back/spv/helpers.rs
--- a/src/back/spv/helpers.rs
+++ b/src/back/spv/helpers.rs
@@ -48,3 +48,16 @@ pub(super) fn contains_builtin(
false // unreachable
}
}
+
+impl crate::StorageClass {
+ pub(super) fn to_spirv_semantics_and_scope(self) -> (spirv::MemorySemantics, spirv::Scope) {
+ match self {
+ Self::Storage { .. } => (spirv::MemorySemantics::UNIFORM_MEMORY, spirv::Scope::Device),
+ Self::WorkGroup => (
+ spirv::MemorySemantics::WORKGROUP_MEMORY,
+ spirv::Scope::Workgroup,
+ ),
+ _ => (spirv::MemorySemantics::empty(), spirv::Scope::Invocation),
+ }
+ }
+}
diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs
--- a/src/back/spv/instructions.rs
+++ b/src/back/spv/instructions.rs
@@ -439,14 +439,30 @@ impl super::Instruction {
instruction
}
+ pub(super) fn atomic_load(
+ result_type_id: Word,
+ id: Word,
+ pointer_id: Word,
+ scope_id: Word,
+ semantics_id: Word,
+ ) -> Self {
+ let mut instruction = Self::new(Op::AtomicLoad);
+ instruction.set_type(result_type_id);
+ instruction.set_result(id);
+ instruction.add_operand(pointer_id);
+ instruction.add_operand(scope_id);
+ instruction.add_operand(semantics_id);
+ instruction
+ }
+
pub(super) fn store(
pointer_id: Word,
- object_id: Word,
+ value_id: Word,
memory_access: Option<spirv::MemoryAccess>,
) -> Self {
let mut instruction = Self::new(Op::Store);
instruction.add_operand(pointer_id);
- instruction.add_operand(object_id);
+ instruction.add_operand(value_id);
if let Some(memory_access) = memory_access {
instruction.add_operand(memory_access.bits());
diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs
--- a/src/back/spv/instructions.rs
+++ b/src/back/spv/instructions.rs
@@ -455,6 +471,20 @@ impl super::Instruction {
instruction
}
+ pub(super) fn atomic_store(
+ pointer_id: Word,
+ scope_id: Word,
+ semantics_id: Word,
+ value_id: Word,
+ ) -> Self {
+ let mut instruction = Self::new(Op::AtomicStore);
+ instruction.add_operand(pointer_id);
+ instruction.add_operand(scope_id);
+ instruction.add_operand(semantics_id);
+ instruction.add_operand(value_id);
+ instruction
+ }
+
pub(super) fn access_chain(
result_type_id: Word,
id: Word,
diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs
--- a/src/back/spv/instructions.rs
+++ b/src/back/spv/instructions.rs
@@ -734,6 +764,25 @@ impl super::Instruction {
instruction
}
+ pub(super) fn atomic_binary(
+ op: Op,
+ result_type_id: Word,
+ id: Word,
+ pointer: Word,
+ scope_id: Word,
+ semantics_id: Word,
+ value: Word,
+ ) -> Self {
+ let mut instruction = Self::new(op);
+ instruction.set_type(result_type_id);
+ instruction.set_result(id);
+ instruction.add_operand(pointer);
+ instruction.add_operand(scope_id);
+ instruction.add_operand(semantics_id);
+ instruction.add_operand(value);
+ instruction
+ }
+
//
// Bit Instructions
//
diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs
--- a/src/back/spv/mod.rs
+++ b/src/back/spv/mod.rs
@@ -211,12 +211,14 @@ struct LookupFunctionType {
fn make_local(inner: &crate::TypeInner) -> Option<LocalType> {
Some(match *inner {
- crate::TypeInner::Scalar { kind, width } => LocalType::Value {
- vector_size: None,
- kind,
- width,
- pointer_class: None,
- },
+ crate::TypeInner::Scalar { kind, width } | crate::TypeInner::Atomic { kind, width } => {
+ LocalType::Value {
+ vector_size: None,
+ kind,
+ width,
+ pointer_class: None,
+ }
+ }
crate::TypeInner::Vector { size, kind, width } => LocalType::Value {
vector_size: Some(size),
kind,
diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs
--- a/src/back/spv/mod.rs
+++ b/src/back/spv/mod.rs
@@ -366,6 +368,11 @@ impl BlockContext<'_> {
self.writer
.get_constant_scalar(crate::ScalarValue::Uint(index as _), 4)
}
+
+ fn get_scope_constant(&mut self, scope: Word) -> Result<Word, Error> {
+ self.writer
+ .get_constant_scalar(crate::ScalarValue::Sint(scope as _), 4)
+ }
}
#[derive(Clone, Copy, Default)]
diff --git a/src/back/spv/mod.rs b/src/back/spv/mod.rs
--- a/src/back/spv/mod.rs
+++ b/src/back/spv/mod.rs
@@ -389,7 +396,6 @@ pub struct Writer {
lookup_type: crate::FastHashMap<LookupType, Word>,
lookup_function: crate::FastHashMap<Handle<crate::Function>, Word>,
lookup_function_type: crate::FastHashMap<LookupFunctionType, Word>,
- lookup_function_call: crate::FastHashMap<Handle<crate::Expression>, Word>,
constant_ids: Vec<Word>,
cached_constants: crate::FastHashMap<(crate::ScalarValue, crate::Bytes), Word>,
global_variables: Vec<GlobalVariable>,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -78,7 +78,6 @@ impl Writer {
lookup_type: crate::FastHashMap::default(),
lookup_function: crate::FastHashMap::default(),
lookup_function_type: crate::FastHashMap::default(),
- lookup_function_call: crate::FastHashMap::default(),
constant_ids: Vec::new(),
cached_constants: crate::FastHashMap::default(),
global_variables: Vec::new(),
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -127,7 +126,6 @@ impl Writer {
lookup_type: take(&mut self.lookup_type).recycle(),
lookup_function: take(&mut self.lookup_function).recycle(),
lookup_function_type: take(&mut self.lookup_function_type).recycle(),
- lookup_function_call: take(&mut self.lookup_function_call).recycle(),
constant_ids: take(&mut self.constant_ids).recycle(),
cached_constants: take(&mut self.cached_constants).recycle(),
global_variables: take(&mut self.global_variables).recycle(),
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -671,7 +669,9 @@ impl Writer {
use spirv::Decoration;
let instruction = match ty.inner {
- crate::TypeInner::Scalar { kind, width } => self.make_scalar(id, kind, width),
+ crate::TypeInner::Scalar { kind, width } | crate::TypeInner::Atomic { kind, width } => {
+ self.make_scalar(id, kind, width)
+ }
crate::TypeInner::Vector { size, kind, width } => {
let scalar_id = self.get_type_id(LookupType::Local(LocalType::Value {
vector_size: None,
diff --git a/src/back/wgsl/mod.rs b/src/back/wgsl/mod.rs
--- a/src/back/wgsl/mod.rs
+++ b/src/back/wgsl/mod.rs
@@ -26,3 +26,18 @@ pub fn write_string(
let output = w.finish();
Ok(output)
}
+
+impl crate::AtomicFunction {
+ fn to_wgsl(self) -> &'static str {
+ match self {
+ Self::Add => "Add",
+ Self::And => "And",
+ Self::InclusiveOr => "Or",
+ Self::ExclusiveOr => "Xor",
+ Self::Min => "Min",
+ Self::Max => "Max",
+ Self::Exchange { compare: None } => "Exchange",
+ Self::Exchange { .. } => "CompareExchangeWeak",
+ }
+ }
+}
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -6,6 +6,11 @@ use crate::{
};
use std::fmt::Write;
+// This is a hack: we need to pass a pointer to an atomic,
+// but generally the backend isn't putting "&" in front of every pointer.
+// Some more general handling of pointers is needed to be implemented here.
+const ATOMIC_REFERENCE: &str = "&";
+
/// Shorthand result used internally by the backend
type BackendResult = Result<(), Error>;
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -498,6 +503,9 @@ impl<W: Write> Writer<W> {
TypeInner::Scalar { kind, .. } => {
write!(self.out, "{}", scalar_kind_str(kind))?;
}
+ TypeInner::Atomic { kind, .. } => {
+ write!(self.out, "atomic<{}>", scalar_kind_str(kind))?;
+ }
TypeInner::Array { base, size, .. } => {
// More info https://gpuweb.github.io/gpuweb/wgsl/#array-types
// array<A, 3> -- Constant array
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -664,9 +672,25 @@ impl<W: Write> Writer<W> {
}
}
write!(self.out, "{}", INDENT.repeat(indent))?;
- self.write_expr(module, pointer, func_ctx)?;
- write!(self.out, " = ")?;
- self.write_expr(module, value, func_ctx)?;
+
+ let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) {
+ crate::TypeInner::Pointer { base, .. } => match module.types[base].inner {
+ crate::TypeInner::Atomic { .. } => true,
+ _ => false,
+ },
+ _ => false,
+ };
+ if is_atomic {
+ write!(self.out, "atomicStore({}", ATOMIC_REFERENCE)?;
+ self.write_expr(module, pointer, func_ctx)?;
+ write!(self.out, ", ")?;
+ self.write_expr(module, value, func_ctx)?;
+ write!(self.out, ")")?;
+ } else {
+ self.write_expr(module, pointer, func_ctx)?;
+ write!(self.out, " = ")?;
+ self.write_expr(module, value, func_ctx)?;
+ }
writeln!(self.out, ";")?
}
Statement::Call {
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -678,7 +702,6 @@ impl<W: Write> Writer<W> {
if let Some(expr) = result {
let name = format!("{}{}", back::BAKE_PREFIX, expr.index());
self.start_named_expr(module, expr, func_ctx, &name)?;
- self.write_expr(module, expr, func_ctx)?;
self.named_expressions.insert(expr, name);
}
let func_name = &self.names[&NameKey::Function(function)];
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -693,6 +716,28 @@ impl<W: Write> Writer<W> {
}
writeln!(self.out, ");")?
}
+ Statement::Atomic {
+ pointer,
+ ref fun,
+ value,
+ result,
+ } => {
+ write!(self.out, "{}", INDENT.repeat(indent))?;
+ let res_name = format!("{}{}", back::BAKE_PREFIX, result.index());
+ self.start_named_expr(module, result, func_ctx, &res_name)?;
+ self.named_expressions.insert(result, res_name);
+
+ let fun_str = fun.to_wgsl();
+ write!(self.out, "atomic{}({}", fun_str, ATOMIC_REFERENCE)?;
+ self.write_expr(module, pointer, func_ctx)?;
+ if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun {
+ write!(self.out, ", ")?;
+ self.write_expr(module, cmp, func_ctx)?;
+ }
+ write!(self.out, ", ")?;
+ self.write_expr(module, value, func_ctx)?;
+ writeln!(self.out, ");")?
+ }
Statement::ImageStore {
image,
coordinate,
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -1123,7 +1168,22 @@ impl<W: Write> Writer<W> {
self.write_expr(module, value, func_ctx)?;
write!(self.out, ")")?;
}
- Expression::Load { pointer } => self.write_expr(module, pointer, func_ctx)?,
+ Expression::Load { pointer } => {
+ let is_atomic = match *func_ctx.info[pointer].ty.inner_with(&module.types) {
+ crate::TypeInner::Pointer { base, .. } => match module.types[base].inner {
+ crate::TypeInner::Atomic { .. } => true,
+ _ => false,
+ },
+ _ => false,
+ };
+ if is_atomic {
+ write!(self.out, "atomicLoad({}", ATOMIC_REFERENCE)?;
+ }
+ self.write_expr(module, pointer, func_ctx)?;
+ if is_atomic {
+ write!(self.out, ")")?;
+ }
+ }
Expression::LocalVariable(handle) => {
write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])?
}
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -1287,7 +1347,7 @@ impl<W: Write> Writer<W> {
write!(self.out, ")")?
}
// Nothing to do here, since call expression already cached
- Expression::Call(_) => {}
+ Expression::CallResult(_) | Expression::AtomicResult { .. } => {}
}
Ok(())
diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs
--- a/src/front/glsl/constants.rs
+++ b/src/front/glsl/constants.rs
@@ -25,6 +25,8 @@ pub enum ConstantSolvingError {
ArrayLengthDynamic,
#[error("Constants cannot call functions")]
Call,
+ #[error("Constants don't support atomic functions")]
+ Atomic,
#[error("Constants don't support relational functions")]
Relational,
#[error("Constants don't support derivative functions")]
diff --git a/src/front/glsl/constants.rs b/src/front/glsl/constants.rs
--- a/src/front/glsl/constants.rs
+++ b/src/front/glsl/constants.rs
@@ -235,7 +237,8 @@ impl<'a> ConstantSolver<'a> {
Expression::LocalVariable(_) => Err(ConstantSolvingError::LocalVariable),
Expression::Derivative { .. } => Err(ConstantSolvingError::Derivative),
Expression::Relational { .. } => Err(ConstantSolvingError::Relational),
- Expression::Call { .. } => Err(ConstantSolvingError::Call),
+ Expression::CallResult { .. } => Err(ConstantSolvingError::Call),
+ Expression::AtomicResult { .. } => Err(ConstantSolvingError::Atomic),
Expression::FunctionArgument(_) => Err(ConstantSolvingError::FunctionArg),
Expression::GlobalVariable(_) => Err(ConstantSolvingError::GlobalVariable),
Expression::ImageSample { .. }
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -1020,7 +1020,7 @@ impl Parser {
ctx.emit_flush(body);
let result = if !is_void {
- Some(ctx.add_expression(Expression::Call(function), body))
+ Some(ctx.add_expression(Expression::CallResult(function), body))
} else {
None
};
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -65,6 +65,7 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
pub(super) fn parse_function(&mut self, module: &mut crate::Module) -> Result<(), Error> {
self.lookup_expression.clear();
self.lookup_load_override.clear();
+ self.lookup_sampled_image.clear();
let result_type_id = self.next()?;
let fun_id = self.next()?;
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -391,8 +392,6 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
module.apply_common_default_interpolation();
- self.lookup_expression.clear();
- self.lookup_sampled_image.clear();
Ok(())
}
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1756,7 +1756,8 @@ impl<I: Iterator<Item = u32>> Parser<I> {
let result = if self.lookup_void_type == Some(result_type_id) {
None
} else {
- let expr_handle = expressions.append(crate::Expression::Call(function));
+ let expr_handle =
+ expressions.append(crate::Expression::CallResult(function));
self.lookup_expression.insert(
result_id,
LookupExpression {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2302,7 +2303,8 @@ impl<I: Iterator<Item = u32>> Parser<I> {
| S::Kill
| S::Barrier(_)
| S::Store { .. }
- | S::ImageStore { .. } => {}
+ | S::ImageStore { .. }
+ | S::Atomic { .. } => {}
S::Call {
function: ref mut callee,
ref arguments,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2355,7 +2357,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
fun: &mut crate::Function,
) -> Result<(), Error> {
for (_, expr) in fun.expressions.iter_mut() {
- if let crate::Expression::Call(ref mut function) = *expr {
+ if let crate::Expression::CallResult(ref mut function) = *expr {
let fun_id = self.deferred_function_calls[function.index()];
*function = *self.lookup_function.lookup(fun_id)?;
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -126,6 +126,8 @@ pub enum Error<'a> {
UnknownLocalFunction(Span),
InitializationTypeMismatch(Span, Handle<crate::Type>),
MissingType(Span),
+ InvalidAtomicPointer(Span),
+ InvalidAtomicOperandType(Span),
Other,
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -337,6 +339,16 @@ impl<'a> Error<'a> {
labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())],
notes: vec![],
},
+ Error::InvalidAtomicPointer(ref span) => ParseError {
+ message: "atomic operation is done on a pointer to a non-atomic".to_string(),
+ labels: vec![(span.clone(), "atomic pointer is invalid".into())],
+ notes: vec![],
+ },
+ Error::InvalidAtomicOperandType(ref span) => ParseError {
+ message: "atomic operand type is inconsistent with the operation".to_string(),
+ labels: vec![(span.clone(), "atomic operand type is invalid".into())],
+ notes: vec![],
+ },
Error::Other => ParseError {
message: "other error".to_string(),
labels: vec![],
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -347,7 +359,7 @@ impl<'a> Error<'a> {
}
impl crate::StorageFormat {
- pub fn to_wgsl(self) -> &'static str {
+ fn to_wgsl(self) -> &'static str {
use crate::StorageFormat as Sf;
match self {
Sf::R8Unorm => "r8unorm",
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -392,17 +404,15 @@ impl crate::TypeInner {
/// For example `vec3<f32>`.
///
/// Note: The names of a `TypeInner::Struct` is not known. Therefore this method will simply return "struct" for them.
- pub fn to_wgsl(
- &self,
- types: &Arena<crate::Type>,
- constants: &Arena<crate::Constant>,
- ) -> String {
+ fn to_wgsl(&self, types: &Arena<crate::Type>, constants: &Arena<crate::Constant>) -> String {
+ use crate::TypeInner as Ti;
+
match *self {
- crate::TypeInner::Scalar { kind, width } => kind.to_wgsl(width),
- crate::TypeInner::Vector { size, kind, width } => {
+ Ti::Scalar { kind, width } => kind.to_wgsl(width),
+ Ti::Vector { size, kind, width } => {
format!("vec{}<{}>", size as u32, kind.to_wgsl(width))
}
- crate::TypeInner::Matrix {
+ Ti::Matrix {
columns,
rows,
width,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -414,15 +424,18 @@ impl crate::TypeInner {
crate::ScalarKind::Float.to_wgsl(width),
)
}
- crate::TypeInner::Pointer { base, .. } => {
+ Ti::Atomic { kind, width } => {
+ format!("atomic<{}>", kind.to_wgsl(width))
+ }
+ Ti::Pointer { base, .. } => {
let base = &types[base];
let name = base.name.as_deref().unwrap_or("unknown");
- format!("*{}", name)
+ format!("ptr<{}>", name)
}
- crate::TypeInner::ValuePointer { kind, width, .. } => {
- format!("*{}", kind.to_wgsl(width))
+ Ti::ValuePointer { kind, width, .. } => {
+ format!("ptr<{}>", kind.to_wgsl(width))
}
- crate::TypeInner::Array { base, size, .. } => {
+ Ti::Array { base, size, .. } => {
let member_type = &types[base];
let base = member_type.name.as_deref().unwrap_or("unknown");
match size {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -433,11 +446,11 @@ impl crate::TypeInner {
crate::ArraySize::Dynamic => format!("{}[]", base),
}
}
- crate::TypeInner::Struct { .. } => {
+ Ti::Struct { .. } => {
// TODO: Actually output the struct?
"struct".to_string()
}
- crate::TypeInner::Image {
+ Ti::Image {
dim,
arrayed,
class,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -481,7 +494,7 @@ impl crate::TypeInner {
class_suffix, dim_suffix, array_suffix, type_in_brackets
)
}
- crate::TypeInner::Sampler { .. } => "sampler".to_string(),
+ Ti::Sampler { .. } => "sampler".to_string(),
}
}
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -778,6 +791,17 @@ impl<'a> ExpressionContext<'a, '_, '_> {
}
Ok(left)
}
+
+ /// Add a single expression to the expression table that is not covered by `self.emitter`.
+ ///
+ /// This is useful for `CallResult` and `AtomicResult` expressions, which should not be covered by
+ /// `Emit` statements.
+ fn interrupt_emitter(&mut self, expression: crate::Expression) -> Handle<crate::Expression> {
+ self.block.extend(self.emitter.finish(self.expressions));
+ let result = self.expressions.append(expression);
+ self.emitter.start(self.expressions);
+ result
+ }
}
enum Composition {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1059,6 +1083,31 @@ impl Parser {
})
}
+ fn parse_atomic_pointer<'a>(
+ &mut self,
+ lexer: &mut Lexer<'a>,
+ mut ctx: ExpressionContext<'a, '_, '_>,
+ ) -> Result<Handle<crate::Expression>, Error<'a>> {
+ let (pointer, pointer_span) =
+ lexer.capture_span(|lexer| self.parse_singular_expression(lexer, ctx.reborrow()))?;
+ // Check if the pointer expression is to an atomic.
+ // The IR uses regular `Expression::Load` and `Statement::Store` for atomic load/stores,
+ // and it will not catch the use of a non-atomic variable here.
+ match *ctx.resolve_type(pointer)? {
+ crate::TypeInner::Pointer { base, .. } => match ctx.types[base].inner {
+ crate::TypeInner::Atomic { .. } => Ok(pointer),
+ ref other => {
+ log::error!("Pointer type to {:?} passed to atomic op", other);
+ Err(Error::InvalidAtomicPointer(pointer_span))
+ }
+ },
+ ref other => {
+ log::error!("Type {:?} passed to atomic op", other);
+ Err(Error::InvalidAtomicPointer(pointer_span))
+ }
+ }
+ }
+
fn parse_local_function_call<'a>(
&mut self,
lexer: &mut Lexer<'a>,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1087,6 +1136,39 @@ impl Parser {
Ok(Some((fun_handle, arguments)))
}
+ fn parse_atomic_helper<'a>(
+ &mut self,
+ lexer: &mut Lexer<'a>,
+ fun: crate::AtomicFunction,
+ mut ctx: ExpressionContext<'a, '_, '_>,
+ ) -> Result<Handle<crate::Expression>, Error<'a>> {
+ lexer.open_arguments()?;
+ let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?;
+ lexer.expect(Token::Separator(','))?;
+ let ctx_span = ctx.reborrow();
+ let (value, value_span) =
+ lexer.capture_span(|lexer| self.parse_singular_expression(lexer, ctx_span))?;
+ lexer.close_arguments()?;
+
+ let expression = match *ctx.resolve_type(value)? {
+ crate::TypeInner::Scalar { kind, width } => crate::Expression::AtomicResult {
+ kind,
+ width,
+ comparison: false,
+ },
+ _ => return Err(Error::InvalidAtomicOperandType(value_span)),
+ };
+
+ let result = ctx.interrupt_emitter(expression);
+ ctx.block.push(crate::Statement::Atomic {
+ pointer,
+ fun,
+ value,
+ result,
+ });
+ Ok(result)
+ }
+
fn parse_function_call_inner<'a>(
&mut self,
lexer: &mut Lexer<'a>,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1126,27 +1208,117 @@ impl Parser {
arg1,
arg2,
}
- } else if name == "select" {
- lexer.open_arguments()?;
- let reject = self.parse_general_expression(lexer, ctx.reborrow())?;
- lexer.expect(Token::Separator(','))?;
- let accept = self.parse_general_expression(lexer, ctx.reborrow())?;
- lexer.expect(Token::Separator(','))?;
- let condition = self.parse_general_expression(lexer, ctx.reborrow())?;
- lexer.close_arguments()?;
- crate::Expression::Select {
- condition,
- accept,
- reject,
- }
- } else if name == "arrayLength" {
- lexer.open_arguments()?;
- let array = self.parse_singular_expression(lexer, ctx.reborrow())?;
- lexer.close_arguments()?;
- crate::Expression::ArrayLength(array)
} else {
- // texture sampling
match name {
+ "select" => {
+ lexer.open_arguments()?;
+ let reject = self.parse_general_expression(lexer, ctx.reborrow())?;
+ lexer.expect(Token::Separator(','))?;
+ let accept = self.parse_general_expression(lexer, ctx.reborrow())?;
+ lexer.expect(Token::Separator(','))?;
+ let condition = self.parse_general_expression(lexer, ctx.reborrow())?;
+ lexer.close_arguments()?;
+ crate::Expression::Select {
+ condition,
+ accept,
+ reject,
+ }
+ }
+ "arrayLength" => {
+ lexer.open_arguments()?;
+ let array = self.parse_singular_expression(lexer, ctx.reborrow())?;
+ lexer.close_arguments()?;
+ crate::Expression::ArrayLength(array)
+ }
+ // atomics
+ "atomicLoad" => {
+ lexer.open_arguments()?;
+ let pointer = self.parse_atomic_pointer(lexer, ctx.reborrow())?;
+ lexer.close_arguments()?;
+ crate::Expression::Load { pointer }
+ }
+ "atomicAdd" => {
+ let handle = self.parse_atomic_helper(
+ lexer,
+ crate::AtomicFunction::Add,
+ ctx.reborrow(),
+ )?;
+ return Ok(Some(handle));
+ }
+ "atomicAnd" => {
+ let handle = self.parse_atomic_helper(
+ lexer,
+ crate::AtomicFunction::And,
+ ctx.reborrow(),
+ )?;
+ return Ok(Some(handle));
+ }
+ "atomicOr" => {
+ let handle = self.parse_atomic_helper(
+ lexer,
+ crate::AtomicFunction::InclusiveOr,
+ ctx.reborrow(),
+ )?;
+ return Ok(Some(handle));
+ }
+ "atomicXor" => {
+ let handle = self.parse_atomic_helper(
+ lexer,
+ crate::AtomicFunction::ExclusiveOr,
+ ctx.reborrow(),
+ )?;
+ return Ok(Some(handle));
+ }
+ "atomicMin" => {
+ let handle =
+ self.parse_atomic_helper(lexer, crate::AtomicFunction::Min, ctx)?;
+ return Ok(Some(handle));
+ }
+ "atomicMax" => {
+ let handle =
+ self.parse_atomic_helper(lexer, crate::AtomicFunction::Max, ctx)?;
+ return Ok(Some(handle));
+ }
+ "atomicExchange" => {
+ let handle = self.parse_atomic_helper(
+ lexer,
+ crate::AtomicFunction::Exchange { compare: None },
+ ctx,
+ )?;
+ return Ok(Some(handle));
+ }
+ "atomicCompareExchangeWeak" => {
+ lexer.open_arguments()?;
+ let pointer = self.parse_singular_expression(lexer, ctx.reborrow())?;
+ lexer.expect(Token::Separator(','))?;
+ let cmp = self.parse_singular_expression(lexer, ctx.reborrow())?;
+ lexer.expect(Token::Separator(','))?;
+ let (value, value_span) = lexer.capture_span(|lexer| {
+ self.parse_singular_expression(lexer, ctx.reborrow())
+ })?;
+ lexer.close_arguments()?;
+
+ let expression = match *ctx.resolve_type(value)? {
+ crate::TypeInner::Scalar { kind, width } => {
+ crate::Expression::AtomicResult {
+ kind,
+ width,
+ comparison: true,
+ }
+ }
+ _ => return Err(Error::InvalidAtomicOperandType(value_span)),
+ };
+
+ let result = ctx.interrupt_emitter(expression);
+ ctx.block.push(crate::Statement::Atomic {
+ pointer,
+ fun: crate::AtomicFunction::Exchange { compare: Some(cmp) },
+ value,
+ result,
+ });
+ return Ok(Some(result));
+ }
+ // texture sampling
"textureSample" => {
lexer.open_arguments()?;
let (image_name, image_span) = lexer.next_ident_with_span()?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1422,16 +1594,14 @@ impl Parser {
let handle =
match self.parse_local_function_call(lexer, name, ctx.reborrow())? {
Some((function, arguments)) => {
- ctx.block.extend(ctx.emitter.finish(ctx.expressions));
- let result =
- Some(ctx.expressions.append(crate::Expression::Call(function)));
+ let result = Some(
+ ctx.interrupt_emitter(crate::Expression::CallResult(function)),
+ );
ctx.block.push(crate::Statement::Call {
function,
arguments,
result,
});
- // restart the emitter
- ctx.emitter.start(ctx.expressions);
result
}
None => None,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1632,12 +1802,7 @@ impl Parser {
let const_handle =
self.parse_const_expression_impl(token, lexer, None, ctx.types, ctx.constants)?;
// pause the emitter while generating this expression, since it's pre-emitted
- ctx.block.extend(ctx.emitter.finish(ctx.expressions));
- let expr = ctx
- .expressions
- .append(crate::Expression::Constant(const_handle));
- ctx.emitter.start(ctx.expressions);
- expr
+ ctx.interrupt_emitter(crate::Expression::Constant(const_handle))
}
(Token::Word(word), span) => {
if let Some(&expr) = ctx.lookup_ident.get(word) {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2244,6 +2409,10 @@ impl Parser {
width,
}
}
+ "atomic" => {
+ let (kind, width) = lexer.next_scalar_generic()?;
+ crate::TypeInner::Atomic { kind, width }
+ }
"ptr" => {
lexer.expect_generic_paren('<')?;
let (ident, span) = lexer.next_ident_with_span()?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2928,6 +3097,15 @@ impl Parser {
lexer.expect(Token::Paren(')'))?;
block.push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP));
}
+ "atomicStore" => {
+ lexer.open_arguments()?;
+ let mut expression_ctx = context.as_expression(block, &mut emitter);
+ let pointer = self.parse_atomic_pointer(lexer, expression_ctx.reborrow())?;
+ lexer.expect(Token::Separator(','))?;
+ let value = self.parse_general_expression(lexer, expression_ctx)?;
+ lexer.close_arguments()?;
+ block.push(crate::Statement::Store { pointer, value });
+ }
"textureStore" => {
emitter.start(context.expressions);
lexer.open_arguments()?;
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -49,7 +49,7 @@ element of an `Arena` has an index of 1, not 0.)
Naga's representation of function calls is unusual. Most languages treat
function calls as expressions, but because calls may have side effects, Naga
represents them as a kind of statement, [`Statement::Call`]. If the function
-returns a value, a call statement designates a particular [`Expression::Call`]
+returns a value, a call statement designates a particular [`Expression::CallResult`]
expression to represent its return value, for use by subsequent statements and
expressions.
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -87,7 +87,7 @@ Naga's rules for when `Expression`s are evaluated are as follows:
a pointer. Such global variables hold opaque types like shaders or
images, and cannot be assigned to.
-- A [`Call`](Expression::Call) expression that is the `result` of a
+- A [`Call`](Expression::CallResult) expression that is the `result` of a
[`Statement::Call`], representing the call's return value, is evaluated when
the `Call` statement is executed.
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -509,6 +509,8 @@ pub enum TypeInner {
rows: VectorSize,
width: Bytes,
},
+ /// Atomic scalar.
+ Atomic { kind: ScalarKind, width: Bytes },
/// Pointer to another type.
///
/// ## Pointers to non-`SIZED` types
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -735,6 +737,23 @@ pub enum BinaryOperator {
ShiftRight,
}
+/// Function on an atomic value.
+///
+/// Note: these do not include load/store, which use the existing
+/// [`Expression::Load`] and [`Statement::Store`].
+#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
+#[cfg_attr(feature = "serialize", derive(Serialize))]
+#[cfg_attr(feature = "deserialize", derive(Deserialize))]
+pub enum AtomicFunction {
+ Add,
+ And,
+ ExclusiveOr,
+ InclusiveOr,
+ Min,
+ Max,
+ Exchange { compare: Option<Handle<Expression>> },
+}
+
/// Axis on which to compute a derivative.
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1004,6 +1023,9 @@ pub enum Expression {
LocalVariable(Handle<LocalVariable>),
/// Load a value indirectly.
+ ///
+ /// For [`TypeInner::Atomic`] the result is a corresponding scalar.
+ /// For other types behind the pointer<T>, the result is T.
Load { pointer: Handle<Expression> },
/// Sample a point from a sampled or a depth image.
ImageSample {
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1138,7 +1160,13 @@ pub enum Expression {
convert: Option<Bytes>,
},
/// Result of calling another function.
- Call(Handle<Function>),
+ CallResult(Handle<Function>),
+ /// Result of an atomic operation.
+ AtomicResult {
+ kind: ScalarKind,
+ width: Bytes,
+ comparison: bool,
+ },
/// Get the length of an array.
/// The expression must resolve to a pointer to an array with a dynamic size.
///
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1257,6 +1285,10 @@ pub enum Statement {
Barrier(Barrier),
/// Stores a value at an address.
///
+ /// For [`TypeInner::Atomic`] type behind the pointer, the value
+ /// has to be a corresponding scalar.
+ /// For other types behind the pointer<T>, the value is T.
+ ///
/// This statement is a barrier for any operations on the
/// `Expression::LocalVariable` or `Expression::GlobalVariable`
/// that is the destination of an access chain, started
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1282,10 +1314,21 @@ pub enum Statement {
array_index: Option<Handle<Expression>>,
value: Handle<Expression>,
},
+ /// Atomic function.
+ Atomic {
+ /// Pointer to an atomic value.
+ pointer: Handle<Expression>,
+ /// Function to run on the atomic.
+ fun: AtomicFunction,
+ /// Value to use in the function.
+ value: Handle<Expression>,
+ /// Emitted expression as a result.
+ result: Handle<Expression>,
+ },
/// Calls a function.
///
/// If the `result` is `Some`, the corresponding expression has to be
- /// `Expression::Call`, and this statement serves as a barrier for any
+ /// `Expression::CallResult`, and this statement serves as a barrier for any
/// operations on that expression.
Call {
function: Handle<Function>,
diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs
--- a/src/proc/layouter.rs
+++ b/src/proc/layouter.rs
@@ -72,7 +72,7 @@ impl Layouter {
for (ty_handle, ty) in types.iter().skip(self.layouts.len()) {
let size = ty.inner.span(constants);
let layout = match ty.inner {
- Ti::Scalar { width, .. } => TypeLayout {
+ Ti::Scalar { width, .. } | Ti::Atomic { width, .. } => TypeLayout {
size,
alignment: Alignment::new(width as u32).unwrap(),
},
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -95,7 +95,7 @@ impl super::TypeInner {
pub fn span(&self, constants: &super::Arena<super::Constant>) -> u32 {
match *self {
- Self::Scalar { kind: _, width } => width as u32,
+ Self::Scalar { kind: _, width } | Self::Atomic { kind: _, width } => width as u32,
Self::Vector {
size,
kind: _,
diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs
--- a/src/proc/terminator.rs
+++ b/src/proc/terminator.rs
@@ -39,6 +39,7 @@ pub fn ensure_block_returns(block: &mut crate::Block) {
| Some(&mut S::Store { .. })
| Some(&mut S::ImageStore { .. })
| Some(&mut S::Call { .. })
+ | Some(&mut S::Atomic { .. })
| Some(&mut S::Barrier(_))
| None => block.push(S::Return { value: None }),
}
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -350,7 +350,13 @@ impl<'a> ResolveContext<'a> {
})
}
crate::Expression::Load { pointer } => match *past(pointer).inner_with(types) {
- Ti::Pointer { base, class: _ } => TypeResolution::Handle(base),
+ Ti::Pointer { base, class: _ } => {
+ if let Ti::Atomic { kind, width } = types[base].inner {
+ TypeResolution::Value(Ti::Scalar { kind, width })
+ } else {
+ TypeResolution::Handle(base)
+ }
+ }
Ti::ValuePointer {
size,
kind,
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -502,6 +508,21 @@ impl<'a> ResolveContext<'a> {
| crate::BinaryOperator::ShiftLeft
| crate::BinaryOperator::ShiftRight => past(left).clone(),
},
+ crate::Expression::AtomicResult {
+ kind,
+ width,
+ comparison,
+ } => {
+ if comparison {
+ TypeResolution::Value(Ti::Vector {
+ size: crate::VectorSize::Bi,
+ kind,
+ width,
+ })
+ } else {
+ TypeResolution::Value(Ti::Scalar { kind, width })
+ }
+ }
crate::Expression::Select { accept, .. } => past(accept).clone(),
crate::Expression::Derivative { axis: _, expr } => past(expr).clone(),
crate::Expression::Relational { .. } => TypeResolution::Value(Ti::Scalar {
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -660,7 +681,7 @@ impl<'a> ResolveContext<'a> {
)))
}
},
- crate::Expression::Call(function) => {
+ crate::Expression::CallResult(function) => {
let result = self.functions[function]
.result
.as_ref()
diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs
--- a/src/valid/analyzer.rs
+++ b/src/valid/analyzer.rs
@@ -567,13 +567,17 @@ impl FunctionInfo {
non_uniform_result: self.add_ref(expr),
requirements: UniformityRequirements::empty(),
},
- E::Call(function) => {
+ E::CallResult(function) => {
let info = other_functions
.get(function.index())
.ok_or(ExpressionError::CallToUndeclaredFunction(function))?;
info.uniformity.clone()
}
+ E::AtomicResult { .. } => Uniformity {
+ non_uniform_result: Some(handle),
+ requirements: UniformityRequirements::empty(),
+ },
E::ArrayLength(expr) => Uniformity {
non_uniform_result: self.add_ref_impl(expr, GlobalUse::QUERY),
requirements: UniformityRequirements::empty(),
diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs
--- a/src/valid/analyzer.rs
+++ b/src/valid/analyzer.rs
@@ -774,6 +778,19 @@ impl FunctionInfo {
//Note: the result is validated by the Validator, not here
self.process_call(info, arguments, expression_arena)?
}
+ S::Atomic {
+ pointer,
+ ref fun,
+ value,
+ result: _,
+ } => {
+ let _ = self.add_ref_impl(pointer, GlobalUse::WRITE);
+ let _ = self.add_ref(value);
+ if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun {
+ let _ = self.add_ref(cmp);
+ }
+ FunctionUniformity::new()
+ }
};
disruptor = disruptor.or(uniformity.exit_disruptor());
diff --git a/src/valid/expression.rs b/src/valid/expression.rs
--- a/src/valid/expression.rs
+++ b/src/valid/expression.rs
@@ -105,6 +105,8 @@ pub enum ExpressionError {
WrongArgumentCount(crate::MathFunction),
#[error("Argument [{1}] to {0:?} as expression {2:?} has an invalid type.")]
InvalidArgumentType(crate::MathFunction, u32, Handle<crate::Expression>),
+ #[error("Atomic result type can't be {0:?} of {1} bytes")]
+ InvalidAtomicResultType(crate::ScalarKind, crate::Bytes),
}
struct ExpressionTypeResolver<'a> {
diff --git a/src/valid/expression.rs b/src/valid/expression.rs
--- a/src/valid/expression.rs
+++ b/src/valid/expression.rs
@@ -1191,7 +1193,23 @@ impl super::Validator {
}
ShaderStages::all()
}
- E::Call(function) => other_infos[function.index()].available_stages,
+ E::CallResult(function) => other_infos[function.index()].available_stages,
+ E::AtomicResult {
+ kind,
+ width,
+ comparison: _,
+ } => {
+ let good = match kind {
+ crate::ScalarKind::Uint | crate::ScalarKind::Sint => {
+ self.check_width(kind, width)
+ }
+ _ => false,
+ };
+ if !good {
+ return Err(ExpressionError::InvalidAtomicResultType(kind, width));
+ }
+ ShaderStages::all()
+ }
E::ArrayLength(expr) => match *resolver.resolve(expr)? {
Ti::Pointer { base, .. } => {
if let Some(&Ti::Array {
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -98,6 +111,8 @@ pub enum FunctionError {
#[source]
error: CallError,
},
+ #[error("Atomic operation is invalid")]
+ InvalidAtomic(#[from] AtomicError),
#[error(
"Required uniformity of control flow for {0:?} in {1:?} is not fulfilled because of {2:?}"
)]
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -239,7 +254,8 @@ impl super::Validator {
return Err(CallError::ResultAlreadyInScope(expr));
}
match context.expressions[expr] {
- crate::Expression::Call(callee) if fun.result.is_some() && callee == function => {}
+ crate::Expression::CallResult(callee)
+ if fun.result.is_some() && callee == function => {}
_ => return Err(CallError::ExpressionMismatch(result)),
}
} else if fun.result.is_some() {
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -250,6 +266,62 @@ impl super::Validator {
Ok(callee_info.available_stages)
}
+ fn validate_atomic(
+ &mut self,
+ pointer: Handle<crate::Expression>,
+ fun: &crate::AtomicFunction,
+ value: Handle<crate::Expression>,
+ result: Handle<crate::Expression>,
+ context: &BlockContext,
+ ) -> Result<(), FunctionError> {
+ let pointer_inner = context.resolve_type(pointer, &self.valid_expression_set)?;
+ let (ptr_kind, ptr_width) = match *pointer_inner {
+ crate::TypeInner::Pointer { base, .. } => match context.types[base].inner {
+ crate::TypeInner::Atomic { kind, width } => (kind, width),
+ ref other => {
+ log::error!("Atomic pointer to type {:?}", other);
+ return Err(AtomicError::InvalidPointer(pointer).into());
+ }
+ },
+ ref other => {
+ log::error!("Atomic on type {:?}", other);
+ return Err(AtomicError::InvalidPointer(pointer).into());
+ }
+ };
+
+ let value_inner = context.resolve_type(value, &self.valid_expression_set)?;
+ match *value_inner {
+ crate::TypeInner::Scalar { width, kind } if kind == ptr_kind && width == ptr_width => {}
+ ref other => {
+ log::error!("Atomic operand type {:?}", other);
+ return Err(AtomicError::InvalidOperand(value).into());
+ }
+ }
+
+ if let crate::AtomicFunction::Exchange { compare: Some(cmp) } = *fun {
+ if context.resolve_type(cmp, &self.valid_expression_set)? != value_inner {
+ log::error!("Atomic exchange comparison has a different type from the value");
+ return Err(AtomicError::InvalidOperand(cmp).into());
+ }
+ }
+
+ if self.valid_expression_set.insert(result.index()) {
+ self.valid_expression_list.push(result);
+ } else {
+ return Err(AtomicError::ResultAlreadyInScope(result).into());
+ }
+ match context.expressions[result] {
+ //TODO: support atomic result with comparison
+ crate::Expression::AtomicResult {
+ kind,
+ width,
+ comparison: false,
+ } if kind == ptr_kind && width == ptr_width => {}
+ _ => return Err(AtomicError::ResultTypeMismatch(result).into()),
+ }
+ Ok(())
+ }
+
fn validate_block_impl(
&mut self,
statements: &[crate::Statement],
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -399,7 +471,10 @@ impl super::Validator {
_ => {}
}
let good = match *context.resolve_pointer_type(pointer)? {
- Ti::Pointer { base, class: _ } => *value_ty == context.types[base].inner,
+ Ti::Pointer { base, class: _ } => match context.types[base].inner {
+ Ti::Atomic { kind, width } => *value_ty == Ti::Scalar { kind, width },
+ ref other => value_ty == other,
+ },
Ti::ValuePointer {
size: Some(size),
kind,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -508,6 +583,14 @@ impl super::Validator {
Ok(callee_stages) => stages &= callee_stages,
Err(error) => return Err(FunctionError::InvalidCall { function, error }),
},
+ S::Atomic {
+ pointer,
+ ref fun,
+ value,
+ result,
+ } => {
+ self.validate_atomic(pointer, fun, value, result, context)?;
+ }
}
}
Ok(stages)
diff --git a/src/valid/interface.rs b/src/valid/interface.rs
--- a/src/valid/interface.rs
+++ b/src/valid/interface.rs
@@ -338,6 +338,7 @@ impl super::Validator {
}
(
TypeFlags::DATA
+ | TypeFlags::COPY
| TypeFlags::SIZED
| TypeFlags::HOST_SHARED
| TypeFlags::TOP_LEVEL,
diff --git a/src/valid/interface.rs b/src/valid/interface.rs
--- a/src/valid/interface.rs
+++ b/src/valid/interface.rs
@@ -361,7 +362,7 @@ impl super::Validator {
));
}
(
- TypeFlags::DATA | TypeFlags::HOST_SHARED | TypeFlags::SIZED,
+ TypeFlags::DATA | TypeFlags::COPY | TypeFlags::HOST_SHARED | TypeFlags::SIZED,
false,
)
}
diff --git a/src/valid/mod.rs b/src/valid/mod.rs
--- a/src/valid/mod.rs
+++ b/src/valid/mod.rs
@@ -167,6 +167,7 @@ impl crate::TypeInner {
size: crate::ArraySize::Constant(_),
..
}
+ | Self::Atomic { .. }
| Self::Pointer { .. }
| Self::ValuePointer { .. }
| Self::Struct { .. } => true,
diff --git a/src/valid/type.rs b/src/valid/type.rs
--- a/src/valid/type.rs
+++ b/src/valid/type.rs
@@ -16,7 +16,7 @@ bitflags::bitflags! {
/// This flag is required on types of local variables, function
/// arguments, array elements, and struct members.
///
- /// This includes all types except `Image`, `Sampler`, `ValuePointer`,
+ /// This includes all types except `Image`, `Sampler`,
/// and some `Pointer` types.
const DATA = 0x1;
diff --git a/src/valid/type.rs b/src/valid/type.rs
--- a/src/valid/type.rs
+++ b/src/valid/type.rs
@@ -35,20 +35,23 @@ bitflags::bitflags! {
/// [`Struct`]: crate::Type::struct
const SIZED = 0x2;
+ /// The data can be copied around.
+ const COPY = 0x4;
+
/// Can be be used for interfacing between pipeline stages.
///
/// This includes non-bool scalars and vectors, matrices, and structs
/// and arrays containing only interface types.
- const INTERFACE = 0x4;
+ const INTERFACE = 0x8;
/// Can be used for host-shareable structures.
- const HOST_SHARED = 0x8;
+ const HOST_SHARED = 0x10;
/// This is a top-level host-shareable type.
- const TOP_LEVEL = 0x10;
+ const TOP_LEVEL = 0x20;
/// This type can be passed as a function argument.
- const ARGUMENT = 0x20;
+ const ARGUMENT = 0x40;
}
}
diff --git a/src/valid/type.rs b/src/valid/type.rs
--- a/src/valid/type.rs
+++ b/src/valid/type.rs
@@ -66,20 +69,22 @@ pub enum Disalignment {
},
#[error("The struct member[{index}] is not statically sized")]
UnsizedMember { index: u32 },
+ #[error("The type is not host-shareable")]
+ NonHostShareable,
}
#[derive(Clone, Debug, thiserror::Error)]
pub enum TypeError {
#[error("The {0:?} scalar width {1} is not supported")]
InvalidWidth(crate::ScalarKind, crate::Bytes),
+ #[error("The {0:?} scalar width {1} is not supported for an atomic")]
+ InvalidAtomicWidth(crate::ScalarKind, crate::Bytes),
#[error("The base handle {0:?} can not be resolved")]
UnresolvedBase(Handle<crate::Type>),
#[error("Invalid type for pointer target {0:?}")]
InvalidPointerBase(Handle<crate::Type>),
#[error("Expected data type, found {0:?}")]
InvalidData(Handle<crate::Type>),
- #[error("Structure type {0:?} can not be a block structure")]
- InvalidBlockType(Handle<crate::Type>),
#[error("Base type {0:?} for the array is invalid")]
InvalidArrayBaseType(Handle<crate::Type>),
#[error("The constant {0:?} can not be used for an array size")]
diff --git a/src/valid/type.rs b/src/valid/type.rs
--- a/src/valid/type.rs
+++ b/src/valid/type.rs
@@ -194,6 +199,7 @@ impl super::Validator {
TypeInfo::new(
TypeFlags::DATA
| TypeFlags::SIZED
+ | TypeFlags::COPY
| TypeFlags::INTERFACE
| TypeFlags::HOST_SHARED
| TypeFlags::ARGUMENT,
diff --git a/src/valid/type.rs b/src/valid/type.rs
--- a/src/valid/type.rs
+++ b/src/valid/type.rs
@@ -208,6 +214,7 @@ impl super::Validator {
TypeInfo::new(
TypeFlags::DATA
| TypeFlags::SIZED
+ | TypeFlags::COPY
| TypeFlags::INTERFACE
| TypeFlags::HOST_SHARED
| TypeFlags::ARGUMENT,
diff --git a/src/valid/type.rs b/src/valid/type.rs
--- a/src/valid/type.rs
+++ b/src/valid/type.rs
@@ -226,24 +233,41 @@ impl super::Validator {
TypeInfo::new(
TypeFlags::DATA
| TypeFlags::SIZED
+ | TypeFlags::COPY
| TypeFlags::INTERFACE
| TypeFlags::HOST_SHARED
| TypeFlags::ARGUMENT,
count * (width as u32),
)
}
+ Ti::Atomic { kind, width } => {
+ let good = match kind {
+ crate::ScalarKind::Bool | crate::ScalarKind::Float => false,
+ crate::ScalarKind::Sint | crate::ScalarKind::Uint => width == 4,
+ };
+ if !good {
+ return Err(TypeError::InvalidAtomicWidth(kind, width));
+ }
+ TypeInfo::new(
+ TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::HOST_SHARED,
+ width as u32,
+ )
+ }
Ti::Pointer { base, class: _ } => {
if base >= handle {
return Err(TypeError::UnresolvedBase(base));
}
+ let base_info = &self.types[base.index()];
+ if !base_info.flags.contains(TypeFlags::DATA) {
+ return Err(TypeError::InvalidPointerBase(base));
+ }
// Pointers to dynamically-sized arrays are needed, to serve as
// the type of an `AccessIndex` expression referring to a
// dynamically sized array appearing as the final member of a
// top-level `Struct`. But such pointers cannot be passed to
// functions, stored in variables, etc. So, we mark them as not
// `DATA`.
- let base_info = &self.types[base.index()];
let data_flag = if base_info.flags.contains(TypeFlags::SIZED) {
TypeFlags::DATA | TypeFlags::ARGUMENT
} else if let crate::TypeInner::Struct { .. } = types[base].inner {
diff --git a/src/valid/type.rs b/src/valid/type.rs
--- a/src/valid/type.rs
+++ b/src/valid/type.rs
@@ -252,7 +276,7 @@ impl super::Validator {
TypeFlags::empty()
};
- TypeInfo::new(data_flag | TypeFlags::SIZED, 0)
+ TypeInfo::new(data_flag | TypeFlags::SIZED | TypeFlags::COPY, 0)
}
Ti::ValuePointer {
size: _,
diff --git a/src/valid/type.rs b/src/valid/type.rs
--- a/src/valid/type.rs
+++ b/src/valid/type.rs
@@ -263,7 +287,7 @@ impl super::Validator {
if !self.check_width(kind, width) {
return Err(TypeError::InvalidWidth(kind, width));
}
- TypeInfo::new(TypeFlags::SIZED, 0)
+ TypeInfo::new(TypeFlags::DATA | TypeFlags::SIZED | TypeFlags::COPY, 0)
}
Ti::Array { base, size, stride } => {
if base >= handle {
diff --git a/src/valid/type.rs b/src/valid/type.rs
--- a/src/valid/type.rs
+++ b/src/valid/type.rs
@@ -366,7 +390,7 @@ impl super::Validator {
}
};
- let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE;
+ let base_mask = TypeFlags::COPY | TypeFlags::HOST_SHARED | TypeFlags::INTERFACE;
TypeInfo {
flags: TypeFlags::DATA | (base_info.flags & base_mask) | sized_flag,
uniform_layout,
diff --git a/src/valid/type.rs b/src/valid/type.rs
--- a/src/valid/type.rs
+++ b/src/valid/type.rs
@@ -381,6 +405,7 @@ impl super::Validator {
let mut ti = TypeInfo::new(
TypeFlags::DATA
| TypeFlags::SIZED
+ | TypeFlags::COPY
| TypeFlags::HOST_SHARED
| TypeFlags::INTERFACE
| TypeFlags::ARGUMENT,
diff --git a/src/valid/type.rs b/src/valid/type.rs
--- a/src/valid/type.rs
+++ b/src/valid/type.rs
@@ -396,12 +421,17 @@ impl super::Validator {
if !base_info.flags.contains(TypeFlags::DATA) {
return Err(TypeError::InvalidData(member.ty));
}
- if top_level && !base_info.flags.contains(TypeFlags::INTERFACE) {
- return Err(TypeError::InvalidBlockType(member.ty));
- }
if base_info.flags.contains(TypeFlags::TOP_LEVEL) {
return Err(TypeError::NestedTopLevel);
}
+ if !base_info.flags.contains(TypeFlags::HOST_SHARED) {
+ if ti.uniform_layout.is_ok() {
+ ti.uniform_layout = Err((member.ty, Disalignment::NonHostShareable));
+ }
+ if ti.storage_layout.is_ok() {
+ ti.storage_layout = Err((member.ty, Disalignment::NonHostShareable));
+ }
+ }
ti.flags &= base_info.flags;
if member.offset < min_offset {
|
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -2496,8 +2598,8 @@ fn test_stack_size() {
}
let stack_size = addresses.end - addresses.start;
// check the size (in debug only)
- // last observed macOS value: 17664
- if stack_size < 14000 || stack_size > 19000 {
+ // last observed macOS value: 18304
+ if stack_size < 15000 || stack_size > 20000 {
panic!("`put_expression` stack size {} has changed!", stack_size);
}
}
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -2511,8 +2613,8 @@ fn test_stack_size() {
}
let stack_size = addresses.end - addresses.start;
// check the size (in debug only)
- // last observed macOS value: 13600
- if stack_size < 11000 || stack_size > 16000 {
+ // last observed macOS value: 17504
+ if stack_size < 14000 || stack_size > 19000 {
panic!("`put_block` stack size {} has changed!", stack_size);
}
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -537,7 +550,7 @@ mod type_inner_tests {
access: crate::StorageAccess::default(),
},
};
- assert_eq!(ptr.to_wgsl(&types, &constants), "*MyType2");
+ assert_eq!(ptr.to_wgsl(&types, &constants), "ptr<MyType2>");
let img1 = crate::TypeInner::Image {
dim: crate::ImageDimension::D2,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -34,6 +34,19 @@ pub enum CallError {
ExpressionMismatch(Option<Handle<crate::Expression>>),
}
+#[derive(Clone, Debug, thiserror::Error)]
+#[cfg_attr(test, derive(PartialEq))]
+pub enum AtomicError {
+ #[error("Pointer {0:?} to atomic is invalid.")]
+ InvalidPointer(Handle<crate::Expression>),
+ #[error("Operand {0:?} has invalid type.")]
+ InvalidOperand(Handle<crate::Expression>),
+ #[error("Result expression {0:?} has already been introduced earlier")]
+ ResultAlreadyInScope(Handle<crate::Expression>),
+ #[error("Result type for {0:?} doesn't match the statement")]
+ ResultTypeMismatch(Handle<crate::Expression>),
+}
+
#[derive(Clone, Debug, thiserror::Error)]
#[cfg_attr(test, derive(PartialEq))]
pub enum LocalVariableError {
diff --git a/tests/in/access.param.ron b/tests/in/access.param.ron
--- a/tests/in/access.param.ron
+++ b/tests/in/access.param.ron
@@ -12,6 +12,12 @@
},
sizes_buffer: Some(24),
),
+ cs: (
+ resources: {
+ (group: 0, binding: 0): (buffer: Some(0), mutable: true),
+ },
+ sizes_buffer: Some(24),
+ ),
),
inline_samplers: [],
spirv_cross_compatibility: false,
diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl
--- a/tests/in/access.wgsl
+++ b/tests/in/access.wgsl
@@ -3,6 +3,7 @@
[[block]]
struct Bar {
matrix: mat4x4<f32>;
+ atom: atomic<i32>;
arr: [[stride(8)]] array<vec2<u32>, 2>;
data: [[stride(4)]] array<i32>;
};
diff --git a/tests/in/access.wgsl b/tests/in/access.wgsl
--- a/tests/in/access.wgsl
+++ b/tests/in/access.wgsl
@@ -36,3 +37,19 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4<f32> {
return matrix * vec4<f32>(vec4<i32>(value));
}
+
+[[stage(compute), workgroup_size(1)]]
+fn atomics() {
+ var tmp: i32;
+ let value = atomicLoad(&bar.atom);
+ tmp = atomicAdd(&bar.atom, 5);
+ tmp = atomicAnd(&bar.atom, 5);
+ tmp = atomicOr(&bar.atom, 5);
+ tmp = atomicXor(&bar.atom, 5);
+ tmp = atomicMin(&bar.atom, 5);
+ tmp = atomicMax(&bar.atom, 5);
+ tmp = atomicExchange(&bar.atom, 5);
+ // https://github.com/gpuweb/gpuweb/issues/2021
+ // tmp = atomicCompareExchangeWeak(&bar.atom, 5, 5);
+ atomicStore(&bar.atom, value);
+}
diff --git /dev/null b/tests/out/glsl/access.atomics.Compute.glsl
new file mode 100644
--- /dev/null
+++ b/tests/out/glsl/access.atomics.Compute.glsl
@@ -0,0 +1,36 @@
+#version 310 es
+
+precision highp float;
+precision highp int;
+
+layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
+
+buffer Bar_block_0Cs {
+ mat4x4 matrix;
+ int atom;
+ uvec2 arr[2];
+ int data[];
+} _group_0_binding_0;
+
+
+void main() {
+ int tmp = 0;
+ int value = _group_0_binding_0.atom;
+ int _expr6 = atomicAdd(_group_0_binding_0.atom, 5);
+ tmp = _expr6;
+ int _expr9 = atomicAnd(_group_0_binding_0.atom, 5);
+ tmp = _expr9;
+ int _expr12 = atomicOr(_group_0_binding_0.atom, 5);
+ tmp = _expr12;
+ int _expr15 = atomicXor(_group_0_binding_0.atom, 5);
+ tmp = _expr15;
+ int _expr18 = atomicMin(_group_0_binding_0.atom, 5);
+ tmp = _expr18;
+ int _expr21 = atomicMax(_group_0_binding_0.atom, 5);
+ tmp = _expr21;
+ int _expr24 = atomicExchange(_group_0_binding_0.atom, 5);
+ tmp = _expr24;
+ _group_0_binding_0.atom = value;
+ return;
+}
+
diff --git a/tests/out/glsl/access.foo.Vertex.glsl b/tests/out/glsl/access.foo.Vertex.glsl
--- a/tests/out/glsl/access.foo.Vertex.glsl
+++ b/tests/out/glsl/access.foo.Vertex.glsl
@@ -5,6 +5,7 @@ precision highp int;
buffer Bar_block_0Vs {
mat4x4 matrix;
+ int atom;
uvec2 arr[2];
int data[];
} _group_0_binding_0;
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -20,10 +20,10 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position
float baz = foo1;
foo1 = 1.0;
float4x4 matrix1 = transpose(float4x4(asfloat(bar.Load4(0+0)), asfloat(bar.Load4(0+16)), asfloat(bar.Load4(0+32)), asfloat(bar.Load4(0+48))));
- uint2 arr[2] = {asuint(bar.Load2(64+0)), asuint(bar.Load2(64+8))};
+ uint2 arr[2] = {asuint(bar.Load2(72+0)), asuint(bar.Load2(72+8))};
float4 _expr13 = asfloat(bar.Load4(48+0));
float b = _expr13.x;
- int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 80) / 4) - 2u)*4+80));
+ int a = asint(bar.Load((((NagaBufferLengthRW(bar) - 88) / 4) - 2u)*4+88));
bar.Store(8+16+0, asuint(1.0));
{
float4x4 _value2 = transpose(float4x4(float4(0.0.xxxx), float4(1.0.xxxx), float4(2.0.xxxx), float4(3.0.xxxx)));
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -34,8 +34,8 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position
}
{
uint2 _value2[2] = { uint2(0u.xx), uint2(1u.xx) };
- bar.Store2(64+0, asuint(_value2[0]));
- bar.Store2(64+8, asuint(_value2[1]));
+ bar.Store2(72+0, asuint(_value2[0]));
+ bar.Store2(72+8, asuint(_value2[1]));
}
{
int _result[5]={ a, int(b), 3, 4, 5 };
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -45,3 +45,27 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position
int value = c[vertexinput_foo.vi1];
return mul(matrix1, float4(int4(value.xxxx)));
}
+
+[numthreads(1, 1, 1)]
+void atomics()
+{
+ int tmp = (int)0;
+
+ int value = asint(bar.Load(64));
+ int _e6; bar.InterlockedAdd(64, 5, _e6);
+ tmp = _e6;
+ int _e9; bar.InterlockedAnd(64, 5, _e9);
+ tmp = _e9;
+ int _e12; bar.InterlockedOr(64, 5, _e12);
+ tmp = _e12;
+ int _e15; bar.InterlockedXor(64, 5, _e15);
+ tmp = _e15;
+ int _e18; bar.InterlockedMin(64, 5, _e18);
+ tmp = _e18;
+ int _e21; bar.InterlockedMax(64, 5, _e21);
+ tmp = _e21;
+ int _e24; bar.InterlockedExchange(64, 5, _e24);
+ tmp = _e24;
+ bar.Store(64, asuint(value));
+ return;
+}
diff --git a/tests/out/hlsl/access.hlsl.config b/tests/out/hlsl/access.hlsl.config
--- a/tests/out/hlsl/access.hlsl.config
+++ b/tests/out/hlsl/access.hlsl.config
@@ -1,3 +1,3 @@
vertex=(foo:vs_5_1 )
fragment=()
-compute=()
+compute=(atomics:cs_5_1 )
diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron
--- a/tests/out/ir/collatz.ron
+++ b/tests/out/ir/collatz.ron
@@ -320,7 +320,7 @@
Load(
pointer: 8,
),
- Call(1),
+ CallResult(1),
],
named_expressions: {},
body: [
diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron
--- a/tests/out/ir/shadow.ron
+++ b/tests/out/ir/shadow.ron
@@ -1189,7 +1189,7 @@
left: 61,
right: 62,
),
- Call(1),
+ CallResult(1),
Load(
pointer: 2,
),
diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl
--- a/tests/out/msl/access.msl
+++ b/tests/out/msl/access.msl
@@ -6,16 +6,18 @@ struct _mslBufferSizes {
metal::uint size0;
};
-struct type2 {
+struct type3 {
metal::uint2 inner[2];
};
-typedef int type4[1];
+typedef int type5[1];
struct Bar {
metal::float4x4 matrix;
- type2 arr;
- type4 data;
+ metal::atomic_int atom;
+ char _pad2[4];
+ type3 arr;
+ type5 data;
};
-struct type8 {
+struct type9 {
int inner[5];
};
diff --git a/tests/out/msl/access.msl b/tests/out/msl/access.msl
--- a/tests/out/msl/access.msl
+++ b/tests/out/msl/access.msl
@@ -30,19 +32,44 @@ vertex fooOutput foo(
, constant _mslBufferSizes& _buffer_sizes [[buffer(24)]]
) {
float foo1 = 0.0;
- type8 c;
+ type9 c;
float baz = foo1;
foo1 = 1.0;
metal::float4x4 matrix = bar.matrix;
- type2 arr = bar.arr;
+ type3 arr = bar.arr;
metal::float4 _e13 = bar.matrix[3];
float b = _e13.x;
- int a = bar.data[(1 + (_buffer_sizes.size0 - 80 - 4) / 4) - 2u];
+ int a = bar.data[(1 + (_buffer_sizes.size0 - 88 - 4) / 4) - 2u];
bar.matrix[1].z = 1.0;
bar.matrix = metal::float4x4(metal::float4(0.0), metal::float4(1.0), metal::float4(2.0), metal::float4(3.0));
- for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type2 {metal::uint2(0u), metal::uint2(1u)}.inner[_i];
- for(int _i=0; _i<5; ++_i) c.inner[_i] = type8 {a, static_cast<int>(b), 3, 4, 5}.inner[_i];
+ for(int _i=0; _i<2; ++_i) bar.arr.inner[_i] = type3 {metal::uint2(0u), metal::uint2(1u)}.inner[_i];
+ for(int _i=0; _i<5; ++_i) c.inner[_i] = type9 {a, static_cast<int>(b), 3, 4, 5}.inner[_i];
c.inner[vi + 1u] = 42;
int value = c.inner[vi];
return fooOutput { matrix * static_cast<float4>(metal::int4(value)) };
}
+
+
+kernel void atomics(
+ device Bar& bar [[buffer(0)]]
+, constant _mslBufferSizes& _buffer_sizes [[buffer(24)]]
+) {
+ int tmp;
+ int value = metal::atomic_load_explicit(&bar.atom, metal::memory_order_relaxed);
+ int _e6 = metal::atomic_fetch_add_explicit(&bar.atom, 5, metal::memory_order_relaxed);
+ tmp = _e6;
+ int _e9 = metal::atomic_fetch_and_explicit(&bar.atom, 5, metal::memory_order_relaxed);
+ tmp = _e9;
+ int _e12 = metal::atomic_fetch_or_explicit(&bar.atom, 5, metal::memory_order_relaxed);
+ tmp = _e12;
+ int _e15 = metal::atomic_fetch_xor_explicit(&bar.atom, 5, metal::memory_order_relaxed);
+ tmp = _e15;
+ int _e18 = metal::atomic_fetch_min_explicit(&bar.atom, 5, metal::memory_order_relaxed);
+ tmp = _e18;
+ int _e21 = metal::atomic_fetch_max_explicit(&bar.atom, 5, metal::memory_order_relaxed);
+ tmp = _e21;
+ int _e24 = metal::atomic_exchange_explicit(&bar.atom, 5, metal::memory_order_relaxed);
+ tmp = _e24;
+ metal::atomic_store_explicit(&bar.atom, value, metal::memory_order_relaxed);
+ return;
+}
diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm
--- a/tests/out/spv/access.spvasm
+++ b/tests/out/spv/access.spvasm
@@ -1,22 +1,27 @@
; SPIR-V
; Version: 1.1
; Generator: rspirv
-; Bound: 82
+; Bound: 105
OpCapability Shader
OpExtension "SPV_KHR_storage_buffer_storage_class"
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Vertex %39 "foo" %34 %37
+OpEntryPoint GLCompute %84 "atomics"
+OpExecutionMode %84 LocalSize 1 1 1
OpSource GLSL 450
OpName %25 "Bar"
OpMemberName %25 0 "matrix"
-OpMemberName %25 1 "arr"
-OpMemberName %25 2 "data"
+OpMemberName %25 1 "atom"
+OpMemberName %25 2 "arr"
+OpMemberName %25 3 "data"
OpName %27 "bar"
OpName %29 "foo"
OpName %31 "c"
OpName %34 "vi"
OpName %39 "foo"
+OpName %82 "tmp"
+OpName %84 "atomics"
OpDecorate %23 ArrayStride 8
OpDecorate %24 ArrayStride 4
OpDecorate %25 Block
diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm
--- a/tests/out/spv/access.spvasm
+++ b/tests/out/spv/access.spvasm
@@ -24,7 +29,8 @@ OpMemberDecorate %25 0 Offset 0
OpMemberDecorate %25 0 ColMajor
OpMemberDecorate %25 0 MatrixStride 16
OpMemberDecorate %25 1 Offset 64
-OpMemberDecorate %25 2 Offset 80
+OpMemberDecorate %25 2 Offset 72
+OpMemberDecorate %25 3 Offset 88
OpDecorate %26 ArrayStride 4
OpDecorate %27 DescriptorSet 0
OpDecorate %27 Binding 0
diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm
--- a/tests/out/spv/access.spvasm
+++ b/tests/out/spv/access.spvasm
@@ -53,7 +59,7 @@ OpDecorate %37 BuiltIn Position
%22 = OpTypeVector %9 2
%23 = OpTypeArray %22 %3
%24 = OpTypeRuntimeArray %4
-%25 = OpTypeStruct %20 %23 %24
+%25 = OpTypeStruct %20 %4 %23 %24
%26 = OpTypeArray %4 %16
%28 = OpTypePointer StorageBuffer %25
%27 = OpVariable %28 StorageBuffer
diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm
--- a/tests/out/spv/access.spvasm
+++ b/tests/out/spv/access.spvasm
@@ -72,6 +78,8 @@ OpDecorate %37 BuiltIn Position
%59 = OpTypePointer StorageBuffer %6
%74 = OpTypePointer Function %4
%78 = OpTypeVector %4 4
+%86 = OpTypePointer StorageBuffer %4
+%89 = OpConstant %9 64
%39 = OpFunction %2 None %40
%33 = OpLabel
%29 = OpVariable %30 Function %5
diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm
--- a/tests/out/spv/access.spvasm
+++ b/tests/out/spv/access.spvasm
@@ -83,14 +91,14 @@ OpBranch %41
OpStore %29 %7
%44 = OpAccessChain %43 %27 %14
%45 = OpLoad %20 %44
-%47 = OpAccessChain %46 %27 %15
+%47 = OpAccessChain %46 %27 %10
%48 = OpLoad %23 %47
%50 = OpAccessChain %49 %27 %14 %8
%51 = OpLoad %21 %50
%52 = OpCompositeExtract %6 %51 0
-%54 = OpArrayLength %9 %27 2
+%54 = OpArrayLength %9 %27 3
%55 = OpISub %9 %54 %10
-%57 = OpAccessChain %56 %27 %10 %55
+%57 = OpAccessChain %56 %27 %8 %55
%58 = OpLoad %4 %57
%60 = OpAccessChain %59 %27 %14 %15 %10
OpStore %60 %7
diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm
--- a/tests/out/spv/access.spvasm
+++ b/tests/out/spv/access.spvasm
@@ -104,7 +112,7 @@ OpStore %66 %65
%67 = OpCompositeConstruct %22 %14 %14
%68 = OpCompositeConstruct %22 %15 %15
%69 = OpCompositeConstruct %23 %67 %68
-%70 = OpAccessChain %46 %27 %15
+%70 = OpAccessChain %46 %27 %10
OpStore %70 %69
%71 = OpConvertFToS %4 %52
%72 = OpCompositeConstruct %26 %58 %71 %17 %18 %16
diff --git a/tests/out/spv/access.spvasm b/tests/out/spv/access.spvasm
--- a/tests/out/spv/access.spvasm
+++ b/tests/out/spv/access.spvasm
@@ -119,4 +127,36 @@ OpStore %75 %19
%81 = OpMatrixTimesVector %21 %45 %80
OpStore %37 %81
OpReturn
+OpFunctionEnd
+%84 = OpFunction %2 None %40
+%83 = OpLabel
+%82 = OpVariable %74 Function
+OpBranch %85
+%85 = OpLabel
+%87 = OpAccessChain %86 %27 %15
+%88 = OpAtomicLoad %4 %87 %11 %89
+%91 = OpAccessChain %86 %27 %15
+%90 = OpAtomicIAdd %4 %91 %11 %89 %16
+OpStore %82 %90
+%93 = OpAccessChain %86 %27 %15
+%92 = OpAtomicAnd %4 %93 %11 %89 %16
+OpStore %82 %92
+%95 = OpAccessChain %86 %27 %15
+%94 = OpAtomicOr %4 %95 %11 %89 %16
+OpStore %82 %94
+%97 = OpAccessChain %86 %27 %15
+%96 = OpAtomicXor %4 %97 %11 %89 %16
+OpStore %82 %96
+%99 = OpAccessChain %86 %27 %15
+%98 = OpAtomicSMin %4 %99 %11 %89 %16
+OpStore %82 %98
+%101 = OpAccessChain %86 %27 %15
+%100 = OpAtomicSMax %4 %101 %11 %89 %16
+OpStore %82 %100
+%103 = OpAccessChain %86 %27 %15
+%102 = OpAtomicExchange %4 %103 %11 %89 %16
+OpStore %82 %102
+%104 = OpAccessChain %86 %27 %15
+OpAtomicStore %104 %11 %89 %88
+OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl
--- a/tests/out/wgsl/access.wgsl
+++ b/tests/out/wgsl/access.wgsl
@@ -1,6 +1,7 @@
[[block]]
struct Bar {
matrix: mat4x4<f32>;
+ atom: atomic<i32>;
arr: [[stride(8)]] array<vec2<u32>,2>;
data: [[stride(4)]] array<i32>;
};
diff --git a/tests/out/wgsl/access.wgsl b/tests/out/wgsl/access.wgsl
--- a/tests/out/wgsl/access.wgsl
+++ b/tests/out/wgsl/access.wgsl
@@ -28,3 +29,26 @@ fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4<f32> {
let value: i32 = c[vi];
return (matrix * vec4<f32>(vec4<i32>(value)));
}
+
+[[stage(compute), workgroup_size(1, 1, 1)]]
+fn atomics() {
+ var tmp: i32;
+
+ let value: i32 = atomicLoad(&bar.atom);
+ let _e6: i32 = atomicAdd(&bar.atom, 5);
+ tmp = _e6;
+ let _e9: i32 = atomicAnd(&bar.atom, 5);
+ tmp = _e9;
+ let _e12: i32 = atomicOr(&bar.atom, 5);
+ tmp = _e12;
+ let _e15: i32 = atomicXor(&bar.atom, 5);
+ tmp = _e15;
+ let _e18: i32 = atomicMin(&bar.atom, 5);
+ tmp = _e18;
+ let _e21: i32 = atomicMax(&bar.atom, 5);
+ tmp = _e21;
+ let _e24: i32 = atomicExchange(&bar.atom, 5);
+ tmp = _e24;
+ atomicStore(&bar.atom, value);
+ return;
+}
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -619,14 +619,6 @@ fn invalid_structs() {
})
}
- check_validation_error! {
- "[[block]] struct Bad { data: ptr<storage, f32>; };":
- Err(naga::valid::ValidationError::Type {
- error: naga::valid::TypeError::InvalidBlockType(_),
- ..
- })
- }
-
check_validation_error! {
"struct Bad { data: array<f32>; other: f32; };":
Err(naga::valid::ValidationError::Type {
|
Atomic operations
See https://github.com/gpuweb/gpuweb/pull/1448
|
There is quite a few choices here on how to approach this.
First, for the type system:
1. `TypeInner::Scalar { kind, width, atomic: bool }` - becomes very annoying since in 99% of cases `atomic==false`
2. `TypeInner::Atomic { kind, width }` - less annoying
In both cases the `Typifier` needs a hack: `Expression::Load` needs to check now if, say, the pointer is pointing to a regular scalar or an atomic, and resolve accordingly.
The awkward part here is that atomics can't really be copied or passed by value, unlike pretty much all the other types. So there is another way to approach this - by avoiding the type system modification. Instead, `struct StructMember` can have `atomic: bool` field on it, and same goes for `TypeInner::Pointer`.
|
2021-06-01T14:08:39Z
|
0.5
|
2021-08-11T01:48:05Z
|
c39810233274b0973fe0fcbfedb3ced8c9f685b6
|
[
"back::msl::writer::test_stack_size",
"front::wgsl::type_inner_tests::to_wgsl",
"convert_wgsl"
] |
[
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::layout::test_logical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"front::spv::test::parse",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::vector_indexing",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::tests::parse_expressions",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::control_flow",
"front::glsl::parser_tests::function_overloading",
"proc::test_matrix_size",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_store",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_switch",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::declarations",
"front::glsl::parser_tests::functions",
"convert_spv_pointer_access",
"convert_spv_shadow",
"convert_spv_quad_vert",
"convert_glsl_folder",
"function_without_identifier",
"bad_texture_sample_type",
"inconsistent_binding",
"invalid_integer",
"bad_for_initializer",
"invalid_float",
"bad_type_cast",
"invalid_scalar_width",
"invalid_texture_sample_type",
"invalid_functions",
"local_var_type_mismatch",
"local_var_missing_type",
"let_type_mismatch",
"invalid_structs",
"invalid_arrays",
"bad_texture",
"invalid_local_vars",
"unknown_attribute",
"struct_member_zero_size",
"unknown_conservative_depth",
"unknown_built_in",
"struct_member_zero_align",
"invalid_access",
"unknown_access",
"unknown_shader_stage",
"unknown_storage_class",
"unknown_storage_format",
"unknown_scalar_type",
"unknown_type",
"unknown_ident",
"missing_bindings",
"unknown_local_function",
"negative_index",
"zero_array_stride",
"unknown_identifier",
"valid_access",
"src/front/glsl/mod.rs - front::glsl::Options (line 37)",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 26)",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 17)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 135)"
] |
[] |
[] |
gfx-rs/naga
| 898
|
gfx-rs__naga-898
|
[
"887"
] |
99fbb34bd6b07ca0a0cc2cf01c151d8264789965
|
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -25,7 +25,7 @@ pub struct FunctionSignature {
#[derive(Debug, Clone)]
pub struct FunctionDeclaration {
- pub parameters: Vec<ParameterQualifier>,
+ pub qualifiers: Vec<ParameterQualifier>,
pub handle: Handle<Function>,
/// Wheter this function was already defined or is just a prototype
pub defined: bool,
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -203,12 +203,15 @@ impl<'function> Context<'function> {
for &(ref name, lookup) in program.global_variables.iter() {
this.emit_flush(body);
- let expr = match lookup {
- GlobalLookup::Variable(v) => Expression::GlobalVariable(v),
+ let (expr, load) = match lookup {
+ GlobalLookup::Variable(v) => (
+ Expression::GlobalVariable(v),
+ program.module.global_variables[v].class != StorageClass::Handle,
+ ),
GlobalLookup::BlockSelect(handle, index) => {
let base = this.expressions.append(Expression::GlobalVariable(handle));
- Expression::AccessIndex { base, index }
+ (Expression::AccessIndex { base, index }, true)
}
};
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -217,7 +220,11 @@ impl<'function> Context<'function> {
let var = VariableReference {
expr,
- load: Some(this.add_expression(Expression::Load { pointer: expr }, body)),
+ load: if load {
+ Some(this.add_expression(Expression::Load { pointer: expr }, body))
+ } else {
+ None
+ },
// TODO: respect constant qualifier
mutable: true,
};
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -288,22 +295,37 @@ impl<'function> Context<'function> {
/// Add function argument to current scope
pub fn add_function_arg(
&mut self,
+ program: &mut Program,
+ sig: &mut FunctionSignature,
body: &mut Block,
name: Option<String>,
ty: Handle<Type>,
- parameter: ParameterQualifier,
+ qualifier: ParameterQualifier,
) {
let index = self.arguments.len();
- self.arguments.push(FunctionArgument {
+ let mut arg = FunctionArgument {
name: name.clone(),
ty,
binding: None,
- });
+ };
+ sig.parameters.push(ty);
+
+ if qualifier.is_lhs() {
+ arg.ty = program.module.types.fetch_or_append(Type {
+ name: None,
+ inner: TypeInner::Pointer {
+ base: arg.ty,
+ class: StorageClass::Function,
+ },
+ })
+ }
+
+ self.arguments.push(arg);
if let Some(name) = name {
let expr = self.add_expression(Expression::FunctionArgument(index as u32), body);
- let mutable = parameter != ParameterQualifier::Const;
- let load = if parameter.is_lhs() {
+ let mutable = qualifier != ParameterQualifier::Const;
+ let load = if qualifier.is_lhs() {
Some(self.add_expression(Expression::Load { pointer: expr }, body))
} else {
None
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -1,8 +1,8 @@
use crate::{
proc::ensure_block_returns, Arena, BinaryOperator, Binding, Block, BuiltIn, EntryPoint,
Expression, Function, FunctionArgument, FunctionResult, Handle, MathFunction,
- RelationalFunction, SampleLevel, ScalarKind, ShaderStage, Statement, StorageClass,
- StructMember, Type, TypeInner,
+ RelationalFunction, SampleLevel, ShaderStage, Statement, StructMember, SwizzleComponent, Type,
+ TypeInner,
};
use super::{ast::*, error::ErrorKind, SourceMetadata};
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -37,8 +37,7 @@ impl Program<'_> {
},
body,
),
- TypeInner::Scalar { kind, width }
- | TypeInner::Vector { kind, width, .. } => ctx.add_expression(
+ TypeInner::Scalar { kind, width } => ctx.add_expression(
Expression::As {
kind,
expr: args[0].0,
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -46,24 +45,80 @@ impl Program<'_> {
},
body,
),
- TypeInner::Matrix {
- columns,
- rows,
- width,
- } => {
- let value = ctx.add_expression(
- Expression::As {
- kind: ScalarKind::Float,
- expr: args[0].0,
- convert: Some(width),
+ TypeInner::Vector { size, kind, width } => {
+ let expr = ctx.add_expression(
+ Expression::Swizzle {
+ size,
+ vector: args[0].0,
+ pattern: [
+ SwizzleComponent::X,
+ SwizzleComponent::Y,
+ SwizzleComponent::Z,
+ SwizzleComponent::W,
+ ],
},
body,
);
- let column = if is_vec {
- value
- } else {
- ctx.add_expression(Expression::Splat { size: rows, value }, body)
+ ctx.add_expression(
+ Expression::As {
+ kind,
+ expr,
+ convert: Some(width),
+ },
+ body,
+ )
+ }
+ TypeInner::Matrix { columns, rows, .. } => {
+ // TODO: casts
+ // `Expression::As` doesn't support matrix width
+ // casts so we need to do some extra work for casts
+
+ let column = match *self.resolve_type(ctx, args[0].0, args[0].1)? {
+ TypeInner::Scalar { .. } => ctx.add_expression(
+ Expression::Splat {
+ size: rows,
+ value: args[0].0,
+ },
+ body,
+ ),
+ TypeInner::Matrix { .. } => {
+ let mut components = Vec::new();
+
+ for n in 0..columns as u32 {
+ let vector = ctx.add_expression(
+ Expression::AccessIndex {
+ base: args[0].0,
+ index: n,
+ },
+ body,
+ );
+
+ let c = ctx.add_expression(
+ Expression::Swizzle {
+ size: rows,
+ vector,
+ pattern: [
+ SwizzleComponent::X,
+ SwizzleComponent::Y,
+ SwizzleComponent::Z,
+ SwizzleComponent::W,
+ ],
+ },
+ body,
+ );
+
+ components.push(c)
+ }
+
+ let h = ctx.add_expression(
+ Expression::Compose { ty, components },
+ body,
+ );
+
+ return Ok(Some(h));
+ }
+ _ => args[0].0,
};
let columns =
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -125,6 +180,14 @@ impl Program<'_> {
if args.len() != 3 {
return Err(ErrorKind::wrong_function_args(name, 3, args.len(), meta));
}
+ let exact = ctx.add_expression(
+ Expression::As {
+ kind: crate::ScalarKind::Float,
+ expr: args[2].0,
+ convert: Some(4),
+ },
+ body,
+ );
if let Some(sampler) = ctx.samplers.get(&args[0].0).copied() {
Ok(Some(ctx.add_expression(
Expression::ImageSample {
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -133,7 +196,7 @@ impl Program<'_> {
coordinate: args[1].0,
array_index: None, //TODO
offset: None, //TODO
- level: SampleLevel::Exact(args[2].0),
+ level: SampleLevel::Exact(exact),
depth_ref: None,
},
body,
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -274,7 +337,7 @@ impl Program<'_> {
.clone();
let mut arguments = Vec::with_capacity(raw_args.len());
- for (qualifier, expr) in fun.parameters.iter().zip(raw_args.iter()) {
+ for (qualifier, expr) in fun.qualifiers.iter().zip(raw_args.iter()) {
let handle = ctx.lower_expect(self, *expr, qualifier.is_lhs(), body)?.0;
arguments.push(handle)
}
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -327,37 +390,17 @@ impl Program<'_> {
pub fn add_function(
&mut self,
mut function: Function,
- parameters: Vec<ParameterQualifier>,
+ sig: FunctionSignature,
+ qualifiers: Vec<ParameterQualifier>,
meta: SourceMetadata,
) -> Result<(), ErrorKind> {
ensure_block_returns(&mut function.body);
- let name = function
- .name
- .clone()
- .ok_or_else(|| ErrorKind::SemanticError(meta, "Unnamed function".into()))?;
- let stage = self.entry_points.get(&name);
+ let stage = self.entry_points.get(&sig.name);
if let Some(&stage) = stage {
let handle = self.module.functions.append(function);
- self.entries.push((name, stage, handle));
+ self.entries.push((sig.name, stage, handle));
} else {
- let sig = FunctionSignature {
- name,
- parameters: function.arguments.iter().map(|p| p.ty).collect(),
- };
-
- for (arg, qualifier) in function.arguments.iter_mut().zip(parameters.iter()) {
- if qualifier.is_lhs() {
- arg.ty = self.module.types.fetch_or_append(Type {
- name: None,
- inner: TypeInner::Pointer {
- base: arg.ty,
- class: StorageClass::Function,
- },
- })
- }
- }
-
let void = function.result.is_none();
if let Some(decl) = self.lookup_function.get_mut(&sig) {
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -375,7 +418,7 @@ impl Program<'_> {
self.lookup_function.insert(
sig,
FunctionDeclaration {
- parameters,
+ qualifiers,
handle,
defined: true,
void,
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -389,43 +432,33 @@ impl Program<'_> {
pub fn add_prototype(
&mut self,
- mut function: Function,
- parameters: Vec<ParameterQualifier>,
+ function: Function,
+ sig: FunctionSignature,
+ qualifiers: Vec<ParameterQualifier>,
meta: SourceMetadata,
) -> Result<(), ErrorKind> {
- let name = function
- .name
- .clone()
- .ok_or_else(|| ErrorKind::SemanticError(meta, "Unnamed function".into()))?;
- let sig = FunctionSignature {
- name,
- parameters: function.arguments.iter().map(|p| p.ty).collect(),
- };
let void = function.result.is_none();
- for (arg, qualifier) in function.arguments.iter_mut().zip(parameters.iter()) {
- if qualifier.is_lhs() {
- arg.ty = self.module.types.fetch_or_append(Type {
- name: None,
- inner: TypeInner::Pointer {
- base: arg.ty,
- class: StorageClass::Function,
- },
- })
- }
- }
-
let handle = self.module.functions.append(function);
- self.lookup_function.insert(
- sig,
- FunctionDeclaration {
- parameters,
- handle,
- defined: false,
- void,
- },
- );
+ if self
+ .lookup_function
+ .insert(
+ sig,
+ FunctionDeclaration {
+ qualifiers,
+ handle,
+ defined: false,
+ void,
+ },
+ )
+ .is_some()
+ {
+ return Err(ErrorKind::SemanticError(
+ meta,
+ "Prototype already defined".into(),
+ ));
+ }
Ok(())
}
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -439,6 +472,7 @@ impl Program<'_> {
for (binding, input, handle) in self.entry_args.iter().cloned() {
match binding {
Binding::Location { .. } if !input => continue,
+ Binding::BuiltIn(builtin) if !should_read(builtin, stage) => continue,
_ => {}
}
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -495,7 +529,7 @@ impl Program<'_> {
let ty = self.module.types.append(Type {
name: None,
inner: TypeInner::Struct {
- top_level: true,
+ top_level: false,
members,
span,
},
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -524,6 +558,32 @@ impl Program<'_> {
}
}
+// FIXME: Both of the functions below should be removed they are a temporary solution
+//
+// The fix should analyze the entry point and children function calls
+// (recursively) and store something like `GlobalUse` and then later only read
+// or store the globals that need to be read or written in that stage
+
+fn should_read(built_in: BuiltIn, stage: ShaderStage) -> bool {
+ match (built_in, stage) {
+ (BuiltIn::Position, ShaderStage::Fragment)
+ | (BuiltIn::BaseInstance, ShaderStage::Vertex)
+ | (BuiltIn::BaseVertex, ShaderStage::Vertex)
+ | (BuiltIn::ClipDistance, ShaderStage::Fragment)
+ | (BuiltIn::InstanceIndex, ShaderStage::Vertex)
+ | (BuiltIn::VertexIndex, ShaderStage::Vertex)
+ | (BuiltIn::FrontFacing, ShaderStage::Fragment)
+ | (BuiltIn::SampleIndex, ShaderStage::Fragment)
+ | (BuiltIn::SampleMask, ShaderStage::Fragment)
+ | (BuiltIn::GlobalInvocationId, ShaderStage::Compute)
+ | (BuiltIn::LocalInvocationId, ShaderStage::Compute)
+ | (BuiltIn::LocalInvocationIndex, ShaderStage::Compute)
+ | (BuiltIn::WorkGroupId, ShaderStage::Compute)
+ | (BuiltIn::WorkGroupSize, ShaderStage::Compute) => true,
+ _ => false,
+ }
+}
+
fn should_write(built_in: BuiltIn, stage: ShaderStage) -> bool {
match (built_in, stage) {
(BuiltIn::Position, ShaderStage::Vertex)
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -1,7 +1,7 @@
use super::{
ast::{
- Context, FunctionCall, FunctionCallKind, GlobalLookup, HirExpr, HirExprKind,
- ParameterQualifier, Profile, StorageQualifier, StructLayout, TypeQualifier,
+ Context, FunctionCall, FunctionCallKind, FunctionSignature, GlobalLookup, HirExpr,
+ HirExprKind, ParameterQualifier, Profile, StorageQualifier, StructLayout, TypeQualifier,
},
error::ErrorKind,
lex::Lexer,
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -567,6 +567,10 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
let mut arguments = Vec::new();
let mut parameters = Vec::new();
let mut body = Block::new();
+ let mut sig = FunctionSignature {
+ name: name.clone(),
+ parameters: Vec::new(),
+ };
let mut context = Context::new(
self.program,
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -576,7 +580,12 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
&mut arguments,
);
- self.parse_function_args(&mut context, &mut body, &mut parameters)?;
+ self.parse_function_args(
+ &mut context,
+ &mut body,
+ &mut parameters,
+ &mut sig,
+ )?;
let end_meta = self.expect(TokenValue::RightParen)?.meta;
meta = meta.union(&end_meta);
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -592,6 +601,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
arguments,
..Default::default()
},
+ sig,
parameters,
meta,
)?;
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -615,6 +625,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
arguments,
body,
},
+ sig,
parameters,
meta,
)?;
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -775,8 +786,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
binding,
ty,
init: None,
- // TODO
- storage_access: StorageAccess::all(),
+ storage_access: StorageAccess::empty(),
});
if let Some(k) = name {
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -1546,6 +1556,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
context: &mut Context,
body: &mut Block,
parameters: &mut Vec<ParameterQualifier>,
+ sig: &mut FunctionSignature,
) -> Result<()> {
loop {
if self.peek_type_name() || self.peek_parameter_qualifier() {
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -1556,7 +1567,7 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
match self.expect_peek()?.value {
TokenValue::Comma => {
self.bump()?;
- context.add_function_arg(body, None, ty, qualifier);
+ context.add_function_arg(&mut self.program, sig, body, None, ty, qualifier);
continue;
}
TokenValue::Identifier(_) => {
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -1565,7 +1576,14 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
let size = self.parse_array_specifier()?;
let ty = self.maybe_array(ty, size);
- context.add_function_arg(body, Some(name), ty, qualifier);
+ context.add_function_arg(
+ &mut self.program,
+ sig,
+ body,
+ Some(name),
+ ty,
+ qualifier,
+ );
if self.bump_if(TokenValue::Comma).is_some() {
continue;
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -1,6 +1,7 @@
use crate::{
- Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, LocalVariable,
- ScalarKind, StorageAccess, StorageClass, Type, TypeInner, VectorSize,
+ Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle, ImageClass,
+ Interpolation, LocalVariable, ScalarKind, StorageAccess, StorageClass, Type, TypeInner,
+ VectorSize,
};
use super::ast::*;
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -41,7 +42,7 @@ impl Program<'_> {
binding: None,
ty,
init: None,
- storage_access: StorageAccess::all(),
+ storage_access: StorageAccess::empty(),
});
self.entry_args
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -297,6 +298,13 @@ impl Program<'_> {
if let Some(location) = location {
let input = StorageQualifier::Input == storage;
+ let interpolation = self.module.types[ty].inner.scalar_kind().map(|kind| {
+ if let ScalarKind::Float = kind {
+ Interpolation::Perspective
+ } else {
+ Interpolation::Flat
+ }
+ });
let handle = self.module.global_variables.append(GlobalVariable {
name: Some(name.clone()),
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -304,7 +312,7 @@ impl Program<'_> {
binding: None,
ty,
init,
- storage_access: StorageAccess::all(),
+ storage_access: StorageAccess::empty(),
});
self.entry_args.push((
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -331,9 +339,25 @@ impl Program<'_> {
return Ok(ctx.add_expression(Expression::Constant(handle), body));
}
- let class = match storage {
- StorageQualifier::StorageClass(class) => class,
- _ => StorageClass::Private,
+ let (class, storage_access) = match self.module.types[ty].inner {
+ TypeInner::Image { class, .. } => (
+ StorageClass::Handle,
+ if let ImageClass::Storage(_) = class {
+ // TODO: Add support for qualifiers such as readonly,
+ // writeonly and readwrite
+ StorageAccess::all()
+ } else {
+ StorageAccess::empty()
+ },
+ ),
+ TypeInner::Sampler { .. } => (StorageClass::Handle, StorageAccess::empty()),
+ _ => (
+ match storage {
+ StorageQualifier::StorageClass(class) => class,
+ _ => StorageClass::Private,
+ },
+ StorageAccess::empty(),
+ ),
};
let handle = self.module.global_variables.append(GlobalVariable {
diff --git a/src/front/glsl/variables.rs b/src/front/glsl/variables.rs
--- a/src/front/glsl/variables.rs
+++ b/src/front/glsl/variables.rs
@@ -342,8 +366,7 @@ impl Program<'_> {
binding,
ty,
init,
- // TODO
- storage_access: StorageAccess::all(),
+ storage_access,
});
self.global_variables
|
diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs
--- a/src/front/glsl/parser_tests.rs
+++ b/src/front/glsl/parser_tests.rs
@@ -369,6 +369,22 @@ fn functions() {
&entry_points,
)
.unwrap();
+
+ parse_program(
+ r#"
+ # version 450
+ void fun(vec2 in_parameter, out float out_parameter) {
+ ivec2 _ = ivec2(in_parameter);
+ }
+
+ void main() {
+ float a;
+ fun(vec2(1.0), a);
+ }
+ "#,
+ &entry_points,
+ )
+ .unwrap();
}
#[test]
|
[glsl-in] Builtin global have empty storage access
```glsl
#version 450
void main() {
gl_Position = vec4(1.0, 1.0, 1,0, 1.0);
}
```
```bash
Global variable [1] 'gl_Position' is invalid:
Storage access LOAD | STORE exceeds the allowed (empty)
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', bin/naga.rs:286:70
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
|
2021-05-23T03:41:52Z
|
0.4
|
2021-07-05T11:13:04Z
|
575304a50c102f2e2a3a622b4be567c0ccf6e6c0
|
[
"front::glsl::parser_tests::functions"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::spv::test::parse",
"front::glsl::parser_tests::constants",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::lexer::test_tokens",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::version",
"back::msl::writer::test_stack_size",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::textures",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_texture_load",
"convert_glsl_quad",
"convert_spv_quad_vert",
"convert_spv_shadow",
"convert_wgsl",
"function_without_identifier",
"invalid_float",
"invalid_scalar_width",
"invalid_integer",
"unknown_identifier",
"invalid_structs",
"invalid_arrays",
"missing_bindings"
] |
[] |
[] |
|
gfx-rs/naga
| 863
|
gfx-rs__naga-863
|
[
"862"
] |
057d03ad86f18e3bb3866b20901d8d4e892dd3d6
|
diff --git a/src/front/spv/flow.rs b/src/front/spv/flow.rs
--- a/src/front/spv/flow.rs
+++ b/src/front/spv/flow.rs
@@ -797,12 +797,13 @@ impl FlowGraph {
Terminator::Branch { target_id } => {
let target_index = self.block_to_node[&target_id];
- let edge = self.flow[self.flow.find_edge(node_index, target_index).unwrap()];
+ let edge =
+ self.flow[self.flow.find_edge(node_index, target_index).unwrap()];
if edge == ControlFlowEdgeType::LoopBreak {
result.push(crate::Statement::Break);
}
- },
+ }
_ => return Err(Error::InvalidTerminator),
};
Ok(result)
diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs
--- a/src/front/wgsl/conv.rs
+++ b/src/front/wgsl/conv.rs
@@ -118,7 +118,7 @@ pub fn map_derivative_axis(word: &str) -> Option<crate::DerivativeAxis> {
match word {
"dpdx" => Some(crate::DerivativeAxis::X),
"dpdy" => Some(crate::DerivativeAxis::Y),
- "dwidth" => Some(crate::DerivativeAxis::Width),
+ "fwidth" => Some(crate::DerivativeAxis::Width),
_ => None,
}
}
|
diff --git /dev/null b/tests/in/standard.param.ron
new file mode 100644
--- /dev/null
+++ b/tests/in/standard.param.ron
@@ -0,0 +1,5 @@
+(
+ spv_version: (1, 0),
+ spv_capabilities: [ Shader ],
+ spv_adjust_coordinate_space: false,
+)
diff --git /dev/null b/tests/in/standard.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/in/standard.wgsl
@@ -0,0 +1,9 @@
+// Standard functions.
+
+[[stage(fragment)]]
+fn derivatives([[builtin(position)]] foo: vec4<f32>) -> [[location(0)]] vec4<f32> {
+ let x = dpdx(foo);
+ let y = dpdy(foo);
+ let z = fwidth(foo);
+ return (x + y) * z;
+}
diff --git /dev/null b/tests/out/standard.Fragment.glsl
new file mode 100644
--- /dev/null
+++ b/tests/out/standard.Fragment.glsl
@@ -0,0 +1,15 @@
+#version 310 es
+
+precision highp float;
+
+layout(location = 0) out vec4 _fs2p_location0;
+
+void main() {
+ vec4 foo = gl_FragCoord;
+ vec4 _expr1 = dFdx(foo);
+ vec4 _expr2 = dFdy(foo);
+ vec4 _expr3 = fwidth(foo);
+ _fs2p_location0 = ((_expr1 + _expr2) * _expr3);
+ return;
+}
+
diff --git /dev/null b/tests/out/standard.msl
new file mode 100644
--- /dev/null
+++ b/tests/out/standard.msl
@@ -0,0 +1,17 @@
+#include <metal_stdlib>
+#include <simd/simd.h>
+
+
+struct derivativesInput {
+};
+struct derivativesOutput {
+ metal::float4 member [[color(0)]];
+};
+fragment derivativesOutput derivatives(
+ metal::float4 foo [[position]]
+) {
+ metal::float4 _e1 = metal::dfdx(foo);
+ metal::float4 _e2 = metal::dfdy(foo);
+ metal::float4 _e3 = metal::fwidth(foo);
+ return derivativesOutput { (_e1 + _e2) * _e3 };
+}
diff --git /dev/null b/tests/out/standard.spvasm
new file mode 100644
--- /dev/null
+++ b/tests/out/standard.spvasm
@@ -0,0 +1,32 @@
+; SPIR-V
+; Version: 1.0
+; Generator: rspirv
+; Bound: 19
+OpCapability Shader
+%1 = OpExtInstImport "GLSL.std.450"
+OpMemoryModel Logical GLSL450
+OpEntryPoint Fragment %11 "derivatives" %6 %9
+OpExecutionMode %11 OriginUpperLeft
+OpDecorate %6 BuiltIn FragCoord
+OpDecorate %9 Location 0
+%2 = OpTypeVoid
+%4 = OpTypeFloat 32
+%3 = OpTypeVector %4 4
+%7 = OpTypePointer Input %3
+%6 = OpVariable %7 Input
+%10 = OpTypePointer Output %3
+%9 = OpVariable %10 Output
+%12 = OpTypeFunction %2
+%11 = OpFunction %2 None %12
+%5 = OpLabel
+%8 = OpLoad %3 %6
+OpBranch %13
+%13 = OpLabel
+%14 = OpDPdx %3 %8
+%15 = OpDPdy %3 %8
+%16 = OpFwidth %3 %8
+%17 = OpFAdd %3 %14 %15
+%18 = OpFMul %3 %17 %16
+OpStore %9 %18
+OpReturn
+OpFunctionEnd
\ No newline at end of file
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -266,6 +266,7 @@ fn convert_wgsl() {
"control-flow",
Targets::SPIRV | Targets::METAL | Targets::GLSL,
),
+ ("standard", Targets::SPIRV | Targets::METAL | Targets::GLSL),
];
for &(name, targets) in inputs.iter() {
|
Error: unknown type: `fwidth`
I have started to translate my glsl shaders into wgsl but ran into an issue on this line:
`let derivative = fwitdth(coords);` which gave me the error that's the title of this issue. [According to the wgsl spec](https://gpuweb.github.io/gpuweb/wgsl/#derivative-builtin-functions) `fwidth` should be defined in the same way as it is in glsl so I'm not sure if this just hasn't been implemented yet? Anyways it was easy to workaround by simply use this instead :
`let derivative = abs(dpdx(coord)) + abs(dpdy(coord));`
But I expected it to be possible to use `fwidth` based on the specification.
|
2021-05-14T21:45:57Z
|
0.4
|
2021-05-14T14:19:44Z
|
575304a50c102f2e2a3a622b4be567c0ccf6e6c0
|
[
"convert_wgsl"
] |
[
"arena::tests::append_non_unique",
"back::msl::test_error_size",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_physical_layout_in_words",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::lex::tests::lex_tokens",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::spv::test::parse",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_pointers",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_if",
"back::msl::writer::test_stack_size",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::constants",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_statement",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_switch",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::control_flow",
"convert_glsl_quad",
"convert_spv_quad_vert",
"convert_spv_shadow",
"function_without_identifier",
"invalid_integer",
"invalid_float",
"invalid_scalar_width",
"invalid_structs",
"invalid_arrays"
] |
[] |
[] |
|
gfx-rs/naga
| 2,510
|
gfx-rs__naga-2510
|
[
"2412",
"2234"
] |
3bcb114adbf144544cb46497b000adf3e7e71181
|
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1129,7 +1129,8 @@ impl<'a, W: Write> Writer<'a, W> {
let ty_name = &self.names[&NameKey::Type(global.ty)];
let block_name = format!(
"{}_block_{}{:?}",
- ty_name,
+ // avoid double underscores as they are reserved in GLSL
+ ty_name.trim_end_matches('_'),
self.block_id.generate(),
self.entry_point.stage,
);
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -36,6 +36,7 @@ impl Namer {
/// - Drop leading digits.
/// - Retain only alphanumeric and `_` characters.
/// - Avoid prefixes in [`Namer::reserved_prefixes`].
+ /// - Replace consecutive `_` characters with a single `_` character.
///
/// The return value is a valid identifier prefix in all of Naga's output languages,
/// and it never ends with a `SEPARATOR` character.
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -46,6 +47,7 @@ impl Namer {
.trim_end_matches(SEPARATOR);
let base = if !string.is_empty()
+ && !string.contains("__")
&& string
.chars()
.all(|c: char| c.is_ascii_alphanumeric() || c == '_')
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -55,7 +57,13 @@ impl Namer {
let mut filtered = string
.chars()
.filter(|&c| c.is_ascii_alphanumeric() || c == '_')
- .collect::<String>();
+ .fold(String::new(), |mut s, c| {
+ if s.ends_with('_') && c == '_' {
+ return s;
+ }
+ s.push(c);
+ s
+ });
let stripped_len = filtered.trim_end_matches(SEPARATOR).len();
filtered.truncate(stripped_len);
if filtered.is_empty() {
|
diff --git a/src/proc/namer.rs b/src/proc/namer.rs
--- a/src/proc/namer.rs
+++ b/src/proc/namer.rs
@@ -268,4 +276,6 @@ fn test() {
assert_eq!(namer.call("x"), "x");
assert_eq!(namer.call("x"), "x_1");
assert_eq!(namer.call("x1"), "x1_");
+ assert_eq!(namer.call("__x"), "_x");
+ assert_eq!(namer.call("1___x"), "_x_1");
}
diff --git a/tests/out/glsl/math-functions.main.Fragment.glsl b/tests/out/glsl/math-functions.main.Fragment.glsl
--- a/tests/out/glsl/math-functions.main.Fragment.glsl
+++ b/tests/out/glsl/math-functions.main.Fragment.glsl
@@ -3,55 +3,55 @@
precision highp float;
precision highp int;
-struct __modf_result_f32_ {
+struct _modf_result_f32_ {
float fract_;
float whole;
};
-struct __modf_result_vec2_f32_ {
+struct _modf_result_vec2_f32_ {
vec2 fract_;
vec2 whole;
};
-struct __modf_result_vec4_f32_ {
+struct _modf_result_vec4_f32_ {
vec4 fract_;
vec4 whole;
};
-struct __frexp_result_f32_ {
+struct _frexp_result_f32_ {
float fract_;
int exp_;
};
-struct __frexp_result_vec4_f32_ {
+struct _frexp_result_vec4_f32_ {
vec4 fract_;
ivec4 exp_;
};
-__modf_result_f32_ naga_modf(float arg) {
+_modf_result_f32_ naga_modf(float arg) {
float other;
float fract = modf(arg, other);
- return __modf_result_f32_(fract, other);
+ return _modf_result_f32_(fract, other);
}
-__modf_result_vec2_f32_ naga_modf(vec2 arg) {
+_modf_result_vec2_f32_ naga_modf(vec2 arg) {
vec2 other;
vec2 fract = modf(arg, other);
- return __modf_result_vec2_f32_(fract, other);
+ return _modf_result_vec2_f32_(fract, other);
}
-__modf_result_vec4_f32_ naga_modf(vec4 arg) {
+_modf_result_vec4_f32_ naga_modf(vec4 arg) {
vec4 other;
vec4 fract = modf(arg, other);
- return __modf_result_vec4_f32_(fract, other);
+ return _modf_result_vec4_f32_(fract, other);
}
-__frexp_result_f32_ naga_frexp(float arg) {
+_frexp_result_f32_ naga_frexp(float arg) {
int other;
float fract = frexp(arg, other);
- return __frexp_result_f32_(fract, other);
+ return _frexp_result_f32_(fract, other);
}
-__frexp_result_vec4_f32_ naga_frexp(vec4 arg) {
+_frexp_result_vec4_f32_ naga_frexp(vec4 arg) {
ivec4 other;
vec4 fract = frexp(arg, other);
- return __frexp_result_vec4_f32_(fract, other);
+ return _frexp_result_vec4_f32_(fract, other);
}
void main() {
diff --git a/tests/out/glsl/math-functions.main.Fragment.glsl b/tests/out/glsl/math-functions.main.Fragment.glsl
--- a/tests/out/glsl/math-functions.main.Fragment.glsl
+++ b/tests/out/glsl/math-functions.main.Fragment.glsl
@@ -90,13 +90,13 @@ void main() {
uvec2 clz_d = uvec2(ivec2(31) - findMSB(uvec2(1u)));
float lde_a = ldexp(1.0, 2);
vec2 lde_b = ldexp(vec2(1.0, 2.0), ivec2(3, 4));
- __modf_result_f32_ modf_a = naga_modf(1.5);
+ _modf_result_f32_ modf_a = naga_modf(1.5);
float modf_b = naga_modf(1.5).fract_;
float modf_c = naga_modf(1.5).whole;
- __modf_result_vec2_f32_ modf_d = naga_modf(vec2(1.5, 1.5));
+ _modf_result_vec2_f32_ modf_d = naga_modf(vec2(1.5, 1.5));
float modf_e = naga_modf(vec4(1.5, 1.5, 1.5, 1.5)).whole.x;
float modf_f = naga_modf(vec2(1.5, 1.5)).fract_.y;
- __frexp_result_f32_ frexp_a = naga_frexp(1.5);
+ _frexp_result_f32_ frexp_a = naga_frexp(1.5);
float frexp_b = naga_frexp(1.5).fract_;
int frexp_c = naga_frexp(1.5).exp_;
int frexp_d = naga_frexp(vec4(1.5, 1.5, 1.5, 1.5)).exp_.x;
diff --git a/tests/out/glsl/padding.vertex.Vertex.glsl b/tests/out/glsl/padding.vertex.Vertex.glsl
--- a/tests/out/glsl/padding.vertex.Vertex.glsl
+++ b/tests/out/glsl/padding.vertex.Vertex.glsl
@@ -20,9 +20,9 @@ struct Test3_ {
};
uniform Test_block_0Vertex { Test _group_0_binding_0_vs; };
-uniform Test2__block_1Vertex { Test2_ _group_0_binding_1_vs; };
+uniform Test2_block_1Vertex { Test2_ _group_0_binding_1_vs; };
-uniform Test3__block_2Vertex { Test3_ _group_0_binding_2_vs; };
+uniform Test3_block_2Vertex { Test3_ _group_0_binding_2_vs; };
void main() {
diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl
--- a/tests/out/hlsl/math-functions.hlsl
+++ b/tests/out/hlsl/math-functions.hlsl
@@ -1,63 +1,63 @@
-struct __modf_result_f32_ {
+struct _modf_result_f32_ {
float fract;
float whole;
};
-struct __modf_result_vec2_f32_ {
+struct _modf_result_vec2_f32_ {
float2 fract;
float2 whole;
};
-struct __modf_result_vec4_f32_ {
+struct _modf_result_vec4_f32_ {
float4 fract;
float4 whole;
};
-struct __frexp_result_f32_ {
+struct _frexp_result_f32_ {
float fract;
int exp_;
};
-struct __frexp_result_vec4_f32_ {
+struct _frexp_result_vec4_f32_ {
float4 fract;
int4 exp_;
};
-__modf_result_f32_ naga_modf(float arg) {
+_modf_result_f32_ naga_modf(float arg) {
float other;
- __modf_result_f32_ result;
+ _modf_result_f32_ result;
result.fract = modf(arg, other);
result.whole = other;
return result;
}
-__modf_result_vec2_f32_ naga_modf(float2 arg) {
+_modf_result_vec2_f32_ naga_modf(float2 arg) {
float2 other;
- __modf_result_vec2_f32_ result;
+ _modf_result_vec2_f32_ result;
result.fract = modf(arg, other);
result.whole = other;
return result;
}
-__modf_result_vec4_f32_ naga_modf(float4 arg) {
+_modf_result_vec4_f32_ naga_modf(float4 arg) {
float4 other;
- __modf_result_vec4_f32_ result;
+ _modf_result_vec4_f32_ result;
result.fract = modf(arg, other);
result.whole = other;
return result;
}
-__frexp_result_f32_ naga_frexp(float arg) {
+_frexp_result_f32_ naga_frexp(float arg) {
float other;
- __frexp_result_f32_ result;
+ _frexp_result_f32_ result;
result.fract = sign(arg) * frexp(arg, other);
result.exp_ = other;
return result;
}
-__frexp_result_vec4_f32_ naga_frexp(float4 arg) {
+_frexp_result_vec4_f32_ naga_frexp(float4 arg) {
float4 other;
- __frexp_result_vec4_f32_ result;
+ _frexp_result_vec4_f32_ result;
result.fract = sign(arg) * frexp(arg, other);
result.exp_ = other;
return result;
diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl
--- a/tests/out/hlsl/math-functions.hlsl
+++ b/tests/out/hlsl/math-functions.hlsl
@@ -100,13 +100,13 @@ void main()
uint2 clz_d = ((31u).xx - firstbithigh((1u).xx));
float lde_a = ldexp(1.0, 2);
float2 lde_b = ldexp(float2(1.0, 2.0), int2(3, 4));
- __modf_result_f32_ modf_a = naga_modf(1.5);
+ _modf_result_f32_ modf_a = naga_modf(1.5);
float modf_b = naga_modf(1.5).fract;
float modf_c = naga_modf(1.5).whole;
- __modf_result_vec2_f32_ modf_d = naga_modf(float2(1.5, 1.5));
+ _modf_result_vec2_f32_ modf_d = naga_modf(float2(1.5, 1.5));
float modf_e = naga_modf(float4(1.5, 1.5, 1.5, 1.5)).whole.x;
float modf_f = naga_modf(float2(1.5, 1.5)).fract.y;
- __frexp_result_f32_ frexp_a = naga_frexp(1.5);
+ _frexp_result_f32_ frexp_a = naga_frexp(1.5);
float frexp_b = naga_frexp(1.5).fract;
int frexp_c = naga_frexp(1.5).exp_;
int frexp_d = naga_frexp(float4(1.5, 1.5, 1.5, 1.5)).exp_.x;
diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl
--- a/tests/out/msl/math-functions.msl
+++ b/tests/out/msl/math-functions.msl
@@ -4,55 +4,55 @@
using metal::uint;
-struct __modf_result_f32_ {
+struct _modf_result_f32_ {
float fract;
float whole;
};
-struct __modf_result_vec2_f32_ {
+struct _modf_result_vec2_f32_ {
metal::float2 fract;
metal::float2 whole;
};
-struct __modf_result_vec4_f32_ {
+struct _modf_result_vec4_f32_ {
metal::float4 fract;
metal::float4 whole;
};
-struct __frexp_result_f32_ {
+struct _frexp_result_f32_ {
float fract;
int exp;
};
-struct __frexp_result_vec4_f32_ {
+struct _frexp_result_vec4_f32_ {
metal::float4 fract;
metal::int4 exp;
};
-__modf_result_f32_ naga_modf(float arg) {
+_modf_result_f32_ naga_modf(float arg) {
float other;
float fract = metal::modf(arg, other);
- return __modf_result_f32_{ fract, other };
+ return _modf_result_f32_{ fract, other };
}
-__modf_result_vec2_f32_ naga_modf(metal::float2 arg) {
+_modf_result_vec2_f32_ naga_modf(metal::float2 arg) {
metal::float2 other;
metal::float2 fract = metal::modf(arg, other);
- return __modf_result_vec2_f32_{ fract, other };
+ return _modf_result_vec2_f32_{ fract, other };
}
-__modf_result_vec4_f32_ naga_modf(metal::float4 arg) {
+_modf_result_vec4_f32_ naga_modf(metal::float4 arg) {
metal::float4 other;
metal::float4 fract = metal::modf(arg, other);
- return __modf_result_vec4_f32_{ fract, other };
+ return _modf_result_vec4_f32_{ fract, other };
}
-__frexp_result_f32_ naga_frexp(float arg) {
+_frexp_result_f32_ naga_frexp(float arg) {
int other;
float fract = metal::frexp(arg, other);
- return __frexp_result_f32_{ fract, other };
+ return _frexp_result_f32_{ fract, other };
}
-__frexp_result_vec4_f32_ naga_frexp(metal::float4 arg) {
+_frexp_result_vec4_f32_ naga_frexp(metal::float4 arg) {
int4 other;
metal::float4 fract = metal::frexp(arg, other);
- return __frexp_result_vec4_f32_{ fract, other };
+ return _frexp_result_vec4_f32_{ fract, other };
}
fragment void main_(
diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl
--- a/tests/out/msl/math-functions.msl
+++ b/tests/out/msl/math-functions.msl
@@ -95,13 +95,13 @@ fragment void main_(
metal::uint2 clz_d = metal::clz(metal::uint2(1u));
float lde_a = metal::ldexp(1.0, 2);
metal::float2 lde_b = metal::ldexp(metal::float2(1.0, 2.0), metal::int2(3, 4));
- __modf_result_f32_ modf_a = naga_modf(1.5);
+ _modf_result_f32_ modf_a = naga_modf(1.5);
float modf_b = naga_modf(1.5).fract;
float modf_c = naga_modf(1.5).whole;
- __modf_result_vec2_f32_ modf_d = naga_modf(metal::float2(1.5, 1.5));
+ _modf_result_vec2_f32_ modf_d = naga_modf(metal::float2(1.5, 1.5));
float modf_e = naga_modf(metal::float4(1.5, 1.5, 1.5, 1.5)).whole.x;
float modf_f = naga_modf(metal::float2(1.5, 1.5)).fract.y;
- __frexp_result_f32_ frexp_a = naga_frexp(1.5);
+ _frexp_result_f32_ frexp_a = naga_frexp(1.5);
float frexp_b = naga_frexp(1.5).fract;
int frexp_c = naga_frexp(1.5).exp;
int frexp_d = naga_frexp(metal::float4(1.5, 1.5, 1.5, 1.5)).exp.x;
|
[glsl-out] Rename identifiers containing two consecutive underscores since they are reserved
> In addition, all identifiers containing two consecutive underscores (__) are reserved for use by underlying software layers. Defining such a name in a shader does not itself result in an error, but may result in unintended behaviors that stem from having multiple definitions of the same name.
_from https://registry.khronos.org/OpenGL/specs/gl/GLSLangSpec.4.60.html#keywords_
with naga-10, from glsl to glsl target, compile error: names containing consecutive underscores are reserved
with naga-10, compile glsl code to glsl target, when type name is ends with number, occus compile error
## compile error with glsl source code in vertex shader
``` txt
Error: 0:38: 'M01__block_1Vetrtex' : identifiers containing two consecutive underscores (__) are reserved as possible future keywords
Error: 0:40: 'M02__block_2Vetrtex' : identifiers containing two consecutive underscores (__) are reserved as possible future keywords
```
## source code
``` glsl
#version 450
precision highp float;
layout(location=0) in vec2 position;
layout(set=0,binding=0) uniform M01 {
mat4 project;
mat4 view;
};
layout(set=2,binding=0) uniform M02 {
mat4 world;
};
void main() {
gl_Position = project * view * world * vec4(position.x, position.y, 1.0, 1.0);
}
```
## specs of gles 3.0
By convention, all macro names containing two consecutive underscores ( __ ) are reserved for use by underlying software layers. Defining such a name in a shader does not itself result in an error, but may result in unintended behaviors that stem from having multiple definitions of the same name
|
## first underscore
when type name is ends with number, it put the underscore

## last underscore in code:
in naga\src\back\glsl\mod.rs, write_interface_block function, as follow:

|
2023-09-26T17:57:14Z
|
0.13
|
2023-09-26T14:46:03Z
|
a17a93ef8f6a06ed8dfc3145276663786828df03
|
[
"proc::namer::test"
] |
[
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::nan_handling",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::spv::test::parse",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::parse::lexer::test_tokens",
"front::wgsl::parse::lexer::test_numbers",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_alias",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::declarations",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_parentheses_switch",
"front::wgsl::tests::parse_parentheses_if",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_repeated_attributes",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_missing_workgroup_size",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::binary_expression_mixed_scalar_and_vector_operands",
"front::wgsl::tests::parse_struct",
"front::wgsl::parse::lexer::test_variable_decl",
"front::wgsl::tests::parse_switch_default_in_case",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_load_store_expecting_four_args",
"proc::test_matrix_size",
"span::span_location",
"valid::handles::constant_deps",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_types",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"convert_wgsl",
"cube_array",
"sampler1d",
"storage1d",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"assign_to_expr",
"bad_for_initializer",
"bad_texture_sample_type",
"bad_type_cast",
"binary_statement",
"binding_array_private",
"binding_array_non_struct",
"bad_texture",
"binding_array_local",
"break_if_bad_condition",
"assign_to_let",
"function_param_redefinition_as_local",
"inconsistent_binding",
"discard_in_wrong_stage",
"function_without_identifier",
"function_param_redefinition_as_param",
"cyclic_function",
"dead_code",
"constructor_parameter_type_mismatch",
"function_returns_void",
"invalid_float",
"local_var_missing_type",
"invalid_integer",
"invalid_access",
"invalid_arrays",
"let_type_mismatch",
"invalid_texture_sample_type",
"misplaced_break_if",
"matrix_with_bad_type",
"invalid_structs",
"invalid_functions",
"negative_index",
"missing_default_case",
"invalid_runtime_sized_arrays",
"recursive_function",
"reserved_identifier_prefix",
"module_scope_identifier_redefinition",
"pointer_type_equivalence",
"invalid_local_vars",
"missing_bindings2",
"host_shareable_types",
"struct_member_size_too_low",
"struct_member_non_po2_align",
"missing_bindings",
"postfix_pointers",
"type_not_inferrable",
"swizzle_assignment",
"struct_member_align_too_low",
"unknown_attribute",
"unknown_access",
"unknown_built_in",
"select",
"unknown_conservative_depth",
"unknown_ident",
"unknown_scalar_type",
"switch_signed_unsigned_mismatch",
"type_not_constructible",
"io_shareable_types",
"unexpected_constructor_parameters",
"unknown_storage_class",
"unknown_local_function",
"unknown_storage_format",
"unknown_type",
"unknown_identifier",
"reserved_keyword",
"var_type_mismatch",
"valid_access",
"wrong_access_mode",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 717)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 738)",
"src/front/mod.rs - front::SymbolTable (line 201)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/glsl/mod.rs - front::glsl::Frontend (line 142)"
] |
[] |
[] |
gfx-rs/naga
| 2,454
|
gfx-rs__naga-2454
|
[
"1161",
"1441"
] |
f49314dbbdfb3beb8c91c4e48402ca7a0591edeb
|
diff --git a/src/back/glsl/keywords.rs b/src/back/glsl/keywords.rs
--- a/src/back/glsl/keywords.rs
+++ b/src/back/glsl/keywords.rs
@@ -477,4 +477,7 @@ pub const RESERVED_KEYWORDS: &[&str] = &[
// entry point name (should not be shadowed)
//
"main",
+ // Naga utilities:
+ super::MODF_FUNCTION,
+ super::FREXP_FUNCTION,
];
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -72,6 +72,9 @@ pub const SUPPORTED_ES_VERSIONS: &[u16] = &[300, 310, 320];
/// of detail for bounds checking in `ImageLoad`
const CLAMPED_LOD_SUFFIX: &str = "_clamped_lod";
+pub(crate) const MODF_FUNCTION: &str = "naga_modf";
+pub(crate) const FREXP_FUNCTION: &str = "naga_frexp";
+
/// Mapping between resources and bindings.
pub type BindingMap = std::collections::BTreeMap<crate::ResourceBinding, u8>;
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -631,6 +634,53 @@ impl<'a, W: Write> Writer<'a, W> {
}
}
+ // Write functions to create special types.
+ for (type_key, struct_ty) in self.module.special_types.predeclared_types.iter() {
+ match type_key {
+ &crate::PredeclaredType::ModfResult { size, width }
+ | &crate::PredeclaredType::FrexpResult { size, width } => {
+ let arg_type_name_owner;
+ let arg_type_name = if let Some(size) = size {
+ arg_type_name_owner =
+ format!("{}vec{}", if width == 8 { "d" } else { "" }, size as u8);
+ &arg_type_name_owner
+ } else if width == 8 {
+ "double"
+ } else {
+ "float"
+ };
+
+ let other_type_name_owner;
+ let (defined_func_name, called_func_name, other_type_name) =
+ if matches!(type_key, &crate::PredeclaredType::ModfResult { .. }) {
+ (MODF_FUNCTION, "modf", arg_type_name)
+ } else {
+ let other_type_name = if let Some(size) = size {
+ other_type_name_owner = format!("ivec{}", size as u8);
+ &other_type_name_owner
+ } else {
+ "int"
+ };
+ (FREXP_FUNCTION, "frexp", other_type_name)
+ };
+
+ let struct_name = &self.names[&NameKey::Type(*struct_ty)];
+
+ writeln!(self.out)?;
+ writeln!(
+ self.out,
+ "{} {defined_func_name}({arg_type_name} arg) {{
+ {other_type_name} other;
+ {arg_type_name} fract = {called_func_name}(arg, other);
+ return {}(fract, other);
+}}",
+ struct_name, struct_name
+ )?;
+ }
+ &crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {}
+ }
+ }
+
// Write all named constants
let mut constants = self
.module
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -2997,8 +3047,8 @@ impl<'a, W: Write> Writer<'a, W> {
Mf::Round => "roundEven",
Mf::Fract => "fract",
Mf::Trunc => "trunc",
- Mf::Modf => "modf",
- Mf::Frexp => "frexp",
+ Mf::Modf => MODF_FUNCTION,
+ Mf::Frexp => FREXP_FUNCTION,
Mf::Ldexp => "ldexp",
// exponent
Mf::Exp => "exp",
diff --git a/src/back/hlsl/help.rs b/src/back/hlsl/help.rs
--- a/src/back/hlsl/help.rs
+++ b/src/back/hlsl/help.rs
@@ -781,6 +781,59 @@ impl<'a, W: Write> super::Writer<'a, W> {
Ok(())
}
+ /// Write functions to create special types.
+ pub(super) fn write_special_functions(&mut self, module: &crate::Module) -> BackendResult {
+ for (type_key, struct_ty) in module.special_types.predeclared_types.iter() {
+ match type_key {
+ &crate::PredeclaredType::ModfResult { size, width }
+ | &crate::PredeclaredType::FrexpResult { size, width } => {
+ let arg_type_name_owner;
+ let arg_type_name = if let Some(size) = size {
+ arg_type_name_owner = format!(
+ "{}{}",
+ if width == 8 { "double" } else { "float" },
+ size as u8
+ );
+ &arg_type_name_owner
+ } else if width == 8 {
+ "double"
+ } else {
+ "float"
+ };
+
+ let (defined_func_name, called_func_name, second_field_name, sign_multiplier) =
+ if matches!(type_key, &crate::PredeclaredType::ModfResult { .. }) {
+ (super::writer::MODF_FUNCTION, "modf", "whole", "")
+ } else {
+ (
+ super::writer::FREXP_FUNCTION,
+ "frexp",
+ "exp_",
+ "sign(arg) * ",
+ )
+ };
+
+ let struct_name = &self.names[&NameKey::Type(*struct_ty)];
+
+ writeln!(
+ self.out,
+ "{struct_name} {defined_func_name}({arg_type_name} arg) {{
+ {arg_type_name} other;
+ {struct_name} result;
+ result.fract = {sign_multiplier}{called_func_name}(arg, other);
+ result.{second_field_name} = other;
+ return result;
+}}"
+ )?;
+ writeln!(self.out)?;
+ }
+ &crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {}
+ }
+ }
+
+ Ok(())
+ }
+
/// Helper function that writes compose wrapped functions
pub(super) fn write_wrapped_compose_functions(
&mut self,
diff --git a/src/back/hlsl/keywords.rs b/src/back/hlsl/keywords.rs
--- a/src/back/hlsl/keywords.rs
+++ b/src/back/hlsl/keywords.rs
@@ -814,6 +814,9 @@ pub const RESERVED: &[&str] = &[
"TextureBuffer",
"ConstantBuffer",
"RayQuery",
+ // Naga utilities
+ super::writer::MODF_FUNCTION,
+ super::writer::FREXP_FUNCTION,
];
// DXC scalar types, from https://github.com/microsoft/DirectXShaderCompiler/blob/18c9e114f9c314f93e68fbc72ce207d4ed2e65ae/tools/clang/lib/AST/ASTContextHLSL.cpp#L48-L254
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -17,6 +17,9 @@ const SPECIAL_BASE_VERTEX: &str = "base_vertex";
const SPECIAL_BASE_INSTANCE: &str = "base_instance";
const SPECIAL_OTHER: &str = "other";
+pub(crate) const MODF_FUNCTION: &str = "naga_modf";
+pub(crate) const FREXP_FUNCTION: &str = "naga_frexp";
+
struct EpStructMember {
name: String,
ty: Handle<crate::Type>,
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -244,6 +247,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
}
}
+ self.write_special_functions(module)?;
+
self.write_wrapped_compose_functions(module, &module.const_expressions)?;
// Write all named constants
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -2675,8 +2680,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
Mf::Round => Function::Regular("round"),
Mf::Fract => Function::Regular("frac"),
Mf::Trunc => Function::Regular("trunc"),
- Mf::Modf => Function::Regular("modf"),
- Mf::Frexp => Function::Regular("frexp"),
+ Mf::Modf => Function::Regular(MODF_FUNCTION),
+ Mf::Frexp => Function::Regular(FREXP_FUNCTION),
Mf::Ldexp => Function::Regular("ldexp"),
// exponent
Mf::Exp => Function::Regular("exp"),
diff --git a/src/back/msl/keywords.rs b/src/back/msl/keywords.rs
--- a/src/back/msl/keywords.rs
+++ b/src/back/msl/keywords.rs
@@ -214,4 +214,6 @@ pub const RESERVED: &[&str] = &[
// Naga utilities
"DefaultConstructible",
"clamped_lod_e",
+ super::writer::FREXP_FUNCTION,
+ super::writer::MODF_FUNCTION,
];
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -32,6 +32,9 @@ const RAY_QUERY_FIELD_INTERSECTION: &str = "intersection";
const RAY_QUERY_FIELD_READY: &str = "ready";
const RAY_QUERY_FUN_MAP_INTERSECTION: &str = "_map_intersection_type";
+pub(crate) const MODF_FUNCTION: &str = "naga_modf";
+pub(crate) const FREXP_FUNCTION: &str = "naga_frexp";
+
/// Write the Metal name for a Naga numeric type: scalar, vector, or matrix.
///
/// The `sizes` slice determines whether this function writes a
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -1678,8 +1681,8 @@ impl<W: Write> Writer<W> {
Mf::Round => "rint",
Mf::Fract => "fract",
Mf::Trunc => "trunc",
- Mf::Modf => "modf",
- Mf::Frexp => "frexp",
+ Mf::Modf => MODF_FUNCTION,
+ Mf::Frexp => FREXP_FUNCTION,
Mf::Ldexp => "ldexp",
// exponent
Mf::Exp => "exp",
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -1813,6 +1816,9 @@ impl<W: Write> Writer<W> {
write!(self.out, "((")?;
self.put_expression(arg, context, false)?;
write!(self.out, ") * 57.295779513082322865)")?;
+ } else if fun == Mf::Modf || fun == Mf::Frexp {
+ write!(self.out, "{fun_name}")?;
+ self.put_call_parameters(iter::once(arg), context)?;
} else {
write!(self.out, "{NAMESPACE}::{fun_name}")?;
self.put_call_parameters(
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -3236,6 +3242,57 @@ impl<W: Write> Writer<W> {
}
}
}
+
+ // Write functions to create special types.
+ for (type_key, struct_ty) in module.special_types.predeclared_types.iter() {
+ match type_key {
+ &crate::PredeclaredType::ModfResult { size, width }
+ | &crate::PredeclaredType::FrexpResult { size, width } => {
+ let arg_type_name_owner;
+ let arg_type_name = if let Some(size) = size {
+ arg_type_name_owner = format!(
+ "{NAMESPACE}::{}{}",
+ if width == 8 { "double" } else { "float" },
+ size as u8
+ );
+ &arg_type_name_owner
+ } else if width == 8 {
+ "double"
+ } else {
+ "float"
+ };
+
+ let other_type_name_owner;
+ let (defined_func_name, called_func_name, other_type_name) =
+ if matches!(type_key, &crate::PredeclaredType::ModfResult { .. }) {
+ (MODF_FUNCTION, "modf", arg_type_name)
+ } else {
+ let other_type_name = if let Some(size) = size {
+ other_type_name_owner = format!("int{}", size as u8);
+ &other_type_name_owner
+ } else {
+ "int"
+ };
+ (FREXP_FUNCTION, "frexp", other_type_name)
+ };
+
+ let struct_name = &self.names[&NameKey::Type(*struct_ty)];
+
+ writeln!(self.out)?;
+ writeln!(
+ self.out,
+ "{} {defined_func_name}({arg_type_name} arg) {{
+ {other_type_name} other;
+ {arg_type_name} fract = {NAMESPACE}::{called_func_name}(arg, other);
+ return {}{{ fract, other }};
+}}",
+ struct_name, struct_name
+ )?;
+ }
+ &crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {}
+ }
+ }
+
Ok(())
}
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -787,8 +787,8 @@ impl<'w> BlockContext<'w> {
Mf::Floor => MathOp::Ext(spirv::GLOp::Floor),
Mf::Fract => MathOp::Ext(spirv::GLOp::Fract),
Mf::Trunc => MathOp::Ext(spirv::GLOp::Trunc),
- Mf::Modf => MathOp::Ext(spirv::GLOp::Modf),
- Mf::Frexp => MathOp::Ext(spirv::GLOp::Frexp),
+ Mf::Modf => MathOp::Ext(spirv::GLOp::ModfStruct),
+ Mf::Frexp => MathOp::Ext(spirv::GLOp::FrexpStruct),
Mf::Ldexp => MathOp::Ext(spirv::GLOp::Ldexp),
// geometry
Mf::Dot => match *self.fun_info[arg].ty.inner_with(&self.ir_module.types) {
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -97,6 +97,14 @@ impl<W: Write> Writer<W> {
self.ep_results.clear();
}
+ fn is_builtin_wgsl_struct(&self, module: &Module, handle: Handle<crate::Type>) -> bool {
+ module
+ .special_types
+ .predeclared_types
+ .values()
+ .any(|t| *t == handle)
+ }
+
pub fn write(&mut self, module: &Module, info: &valid::ModuleInfo) -> BackendResult {
self.reset(module);
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -109,13 +117,13 @@ impl<W: Write> Writer<W> {
// Write all structs
for (handle, ty) in module.types.iter() {
- if let TypeInner::Struct {
- ref members,
- span: _,
- } = ty.inner
- {
- self.write_struct(module, handle, members)?;
- writeln!(self.out)?;
+ if let TypeInner::Struct { ref members, .. } = ty.inner {
+ {
+ if !self.is_builtin_wgsl_struct(module, handle) {
+ self.write_struct(module, handle, members)?;
+ writeln!(self.out)?;
+ }
+ }
}
}
diff --git a/src/front/type_gen.rs b/src/front/type_gen.rs
--- a/src/front/type_gen.rs
+++ b/src/front/type_gen.rs
@@ -5,55 +5,6 @@ Type generators.
use crate::{arena::Handle, span::Span};
impl crate::Module {
- pub fn generate_atomic_compare_exchange_result(
- &mut self,
- kind: crate::ScalarKind,
- width: crate::Bytes,
- ) -> Handle<crate::Type> {
- let bool_ty = self.types.insert(
- crate::Type {
- name: None,
- inner: crate::TypeInner::Scalar {
- kind: crate::ScalarKind::Bool,
- width: crate::BOOL_WIDTH,
- },
- },
- Span::UNDEFINED,
- );
- let scalar_ty = self.types.insert(
- crate::Type {
- name: None,
- inner: crate::TypeInner::Scalar { kind, width },
- },
- Span::UNDEFINED,
- );
-
- self.types.insert(
- crate::Type {
- name: Some(format!(
- "__atomic_compare_exchange_result<{kind:?},{width}>"
- )),
- inner: crate::TypeInner::Struct {
- members: vec![
- crate::StructMember {
- name: Some("old_value".to_string()),
- ty: scalar_ty,
- binding: None,
- offset: 0,
- },
- crate::StructMember {
- name: Some("exchanged".to_string()),
- ty: bool_ty,
- binding: None,
- offset: 4,
- },
- ],
- span: 8,
- },
- },
- Span::UNDEFINED,
- )
- }
/// Populate this module's [`SpecialTypes::ray_desc`] type.
///
/// [`SpecialTypes::ray_desc`] is the type of the [`descriptor`] operand of
diff --git a/src/front/type_gen.rs b/src/front/type_gen.rs
--- a/src/front/type_gen.rs
+++ b/src/front/type_gen.rs
@@ -311,4 +262,203 @@ impl crate::Module {
self.special_types.ray_intersection = Some(handle);
handle
}
+
+ /// Populate this module's [`SpecialTypes::predeclared_types`] type and return the handle.
+ ///
+ /// [`SpecialTypes::predeclared_types`]: crate::SpecialTypes::predeclared_types
+ pub fn generate_predeclared_type(
+ &mut self,
+ special_type: crate::PredeclaredType,
+ ) -> Handle<crate::Type> {
+ use std::fmt::Write;
+
+ if let Some(value) = self.special_types.predeclared_types.get(&special_type) {
+ return *value;
+ }
+
+ let ty = match special_type {
+ crate::PredeclaredType::AtomicCompareExchangeWeakResult { kind, width } => {
+ let bool_ty = self.types.insert(
+ crate::Type {
+ name: None,
+ inner: crate::TypeInner::Scalar {
+ kind: crate::ScalarKind::Bool,
+ width: crate::BOOL_WIDTH,
+ },
+ },
+ Span::UNDEFINED,
+ );
+ let scalar_ty = self.types.insert(
+ crate::Type {
+ name: None,
+ inner: crate::TypeInner::Scalar { kind, width },
+ },
+ Span::UNDEFINED,
+ );
+
+ crate::Type {
+ name: Some(format!(
+ "__atomic_compare_exchange_result<{kind:?},{width}>"
+ )),
+ inner: crate::TypeInner::Struct {
+ members: vec![
+ crate::StructMember {
+ name: Some("old_value".to_string()),
+ ty: scalar_ty,
+ binding: None,
+ offset: 0,
+ },
+ crate::StructMember {
+ name: Some("exchanged".to_string()),
+ ty: bool_ty,
+ binding: None,
+ offset: 4,
+ },
+ ],
+ span: 8,
+ },
+ }
+ }
+ crate::PredeclaredType::ModfResult { size, width } => {
+ let float_ty = self.types.insert(
+ crate::Type {
+ name: None,
+ inner: crate::TypeInner::Scalar {
+ kind: crate::ScalarKind::Float,
+ width,
+ },
+ },
+ Span::UNDEFINED,
+ );
+
+ let (member_ty, second_offset) = if let Some(size) = size {
+ let vec_ty = self.types.insert(
+ crate::Type {
+ name: None,
+ inner: crate::TypeInner::Vector {
+ size,
+ kind: crate::ScalarKind::Float,
+ width,
+ },
+ },
+ Span::UNDEFINED,
+ );
+ (vec_ty, size as u32 * width as u32)
+ } else {
+ (float_ty, width as u32)
+ };
+
+ let mut type_name = "__modf_result_".to_string();
+ if let Some(size) = size {
+ let _ = write!(type_name, "vec{}_", size as u8);
+ }
+ let _ = write!(type_name, "f{}", width * 8);
+
+ crate::Type {
+ name: Some(type_name),
+ inner: crate::TypeInner::Struct {
+ members: vec![
+ crate::StructMember {
+ name: Some("fract".to_string()),
+ ty: member_ty,
+ binding: None,
+ offset: 0,
+ },
+ crate::StructMember {
+ name: Some("whole".to_string()),
+ ty: member_ty,
+ binding: None,
+ offset: second_offset,
+ },
+ ],
+ span: second_offset * 2,
+ },
+ }
+ }
+ crate::PredeclaredType::FrexpResult { size, width } => {
+ let float_ty = self.types.insert(
+ crate::Type {
+ name: None,
+ inner: crate::TypeInner::Scalar {
+ kind: crate::ScalarKind::Float,
+ width,
+ },
+ },
+ Span::UNDEFINED,
+ );
+
+ let int_ty = self.types.insert(
+ crate::Type {
+ name: None,
+ inner: crate::TypeInner::Scalar {
+ kind: crate::ScalarKind::Sint,
+ width,
+ },
+ },
+ Span::UNDEFINED,
+ );
+
+ let (fract_member_ty, exp_member_ty, second_offset) = if let Some(size) = size {
+ let vec_float_ty = self.types.insert(
+ crate::Type {
+ name: None,
+ inner: crate::TypeInner::Vector {
+ size,
+ kind: crate::ScalarKind::Float,
+ width,
+ },
+ },
+ Span::UNDEFINED,
+ );
+ let vec_int_ty = self.types.insert(
+ crate::Type {
+ name: None,
+ inner: crate::TypeInner::Vector {
+ size,
+ kind: crate::ScalarKind::Sint,
+ width,
+ },
+ },
+ Span::UNDEFINED,
+ );
+ (vec_float_ty, vec_int_ty, size as u32 * width as u32)
+ } else {
+ (float_ty, int_ty, width as u32)
+ };
+
+ let mut type_name = "__frexp_result_".to_string();
+ if let Some(size) = size {
+ let _ = write!(type_name, "vec{}_", size as u8);
+ }
+ let _ = write!(type_name, "f{}", width * 8);
+
+ crate::Type {
+ name: Some(type_name),
+ inner: crate::TypeInner::Struct {
+ members: vec![
+ crate::StructMember {
+ name: Some("fract".to_string()),
+ ty: fract_member_ty,
+ binding: None,
+ offset: 0,
+ },
+ crate::StructMember {
+ name: Some("exp".to_string()),
+ ty: exp_member_ty,
+ binding: None,
+ offset: second_offset,
+ },
+ ],
+ span: second_offset * 2,
+ },
+ }
+ }
+ };
+
+ let handle = self.types.insert(ty, Span::UNDEFINED);
+ self.special_types
+ .predeclared_types
+ .insert(special_type, handle);
+ handle
+ }
}
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -1745,6 +1745,25 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
args.finish()?;
+ if fun == crate::MathFunction::Modf || fun == crate::MathFunction::Frexp {
+ ctx.grow_types(arg)?;
+ if let Some((size, width)) = match *ctx.resolved_inner(arg) {
+ crate::TypeInner::Scalar { width, .. } => Some((None, width)),
+ crate::TypeInner::Vector { size, width, .. } => {
+ Some((Some(size), width))
+ }
+ _ => None,
+ } {
+ ctx.module.generate_predeclared_type(
+ if fun == crate::MathFunction::Modf {
+ crate::PredeclaredType::ModfResult { size, width }
+ } else {
+ crate::PredeclaredType::FrexpResult { size, width }
+ },
+ );
+ }
+ }
+
crate::Expression::Math {
fun,
arg,
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -1880,10 +1899,12 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
let expression = match *ctx.resolved_inner(value) {
crate::TypeInner::Scalar { kind, width } => {
crate::Expression::AtomicResult {
- //TODO: cache this to avoid generating duplicate types
- ty: ctx
- .module
- .generate_atomic_compare_exchange_result(kind, width),
+ ty: ctx.module.generate_predeclared_type(
+ crate::PredeclaredType::AtomicCompareExchangeWeakResult {
+ kind,
+ width,
+ },
+ ),
comparison: true,
}
}
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1945,6 +1945,31 @@ pub struct EntryPoint {
pub function: Function,
}
+/// Return types predeclared for the frexp, modf, and atomicCompareExchangeWeak built-in functions.
+///
+/// These cannot be spelled in WGSL source.
+///
+/// Stored in [`SpecialTypes::predeclared_types`] and created by [`Module::generate_predeclared_type`].
+#[derive(Debug, PartialEq, Eq, Hash)]
+#[cfg_attr(feature = "clone", derive(Clone))]
+#[cfg_attr(feature = "serialize", derive(Serialize))]
+#[cfg_attr(feature = "deserialize", derive(Deserialize))]
+#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
+pub enum PredeclaredType {
+ AtomicCompareExchangeWeakResult {
+ kind: ScalarKind,
+ width: Bytes,
+ },
+ ModfResult {
+ size: Option<VectorSize>,
+ width: Bytes,
+ },
+ FrexpResult {
+ size: Option<VectorSize>,
+ width: Bytes,
+ },
+}
+
/// Set of special types that can be optionally generated by the frontends.
#[derive(Debug, Default)]
#[cfg_attr(feature = "clone", derive(Clone))]
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1963,6 +1988,12 @@ pub struct SpecialTypes {
/// Call [`Module::generate_ray_intersection_type`] to populate
/// this if needed and return the handle.
pub ray_intersection: Option<Handle<Type>>,
+
+ /// Types for predeclared wgsl types instantiated on demand.
+ ///
+ /// Call [`Module::generate_predeclared_type`] to populate this if
+ /// needed and return the handle.
+ pub predeclared_types: indexmap::IndexMap<PredeclaredType, Handle<Type>>,
}
/// Shader module.
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -375,8 +375,8 @@ impl super::MathFunction {
Self::Round => 1,
Self::Fract => 1,
Self::Trunc => 1,
- Self::Modf => 2,
- Self::Frexp => 2,
+ Self::Modf => 1,
+ Self::Frexp => 1,
Self::Ldexp => 2,
// exponent
Self::Exp => 1,
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -706,8 +706,6 @@ impl<'a> ResolveContext<'a> {
Mf::Round |
Mf::Fract |
Mf::Trunc |
- Mf::Modf |
- Mf::Frexp |
Mf::Ldexp |
// exponent
Mf::Exp |
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -715,6 +713,31 @@ impl<'a> ResolveContext<'a> {
Mf::Log |
Mf::Log2 |
Mf::Pow => res_arg.clone(),
+ Mf::Modf | Mf::Frexp => {
+ let (size, width) = match res_arg.inner_with(types) {
+ &Ti::Scalar {
+ kind: crate::ScalarKind::Float,
+ width,
+ } => (None, width),
+ &Ti::Vector {
+ kind: crate::ScalarKind::Float,
+ size,
+ width,
+ } => (Some(size), width),
+ ref other =>
+ return Err(ResolveError::IncompatibleOperands(format!("{fun:?}({other:?}, _)")))
+ };
+ let result = self
+ .special_types
+ .predeclared_types
+ .get(&if fun == Mf::Modf {
+ crate::PredeclaredType::ModfResult { size, width }
+ } else {
+ crate::PredeclaredType::FrexpResult { size, width }
+ })
+ .ok_or(ResolveError::MissingSpecialType)?;
+ TypeResolution::Handle(*result)
+ },
// geometry
Mf::Dot => match *res_arg.inner_with(types) {
Ti::Vector {
diff --git a/src/valid/expression.rs b/src/valid/expression.rs
--- a/src/valid/expression.rs
+++ b/src/valid/expression.rs
@@ -1015,38 +1015,20 @@ impl super::Validator {
}
}
Mf::Modf | Mf::Frexp => {
- let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) {
- (Some(ty1), None, None) => ty1,
- _ => return Err(ExpressionError::WrongArgumentCount(fun)),
- };
- let (size0, width0) = match *arg_ty {
+ if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() {
+ return Err(ExpressionError::WrongArgumentCount(fun));
+ }
+ if !matches!(
+ *arg_ty,
Ti::Scalar {
kind: Sk::Float,
- width,
- } => (None, width),
- Ti::Vector {
- kind: Sk::Float,
- size,
- width,
- } => (Some(size), width),
- _ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
- };
- let good = match *arg1_ty {
- Ti::Pointer { base, space: _ } => module.types[base].inner == *arg_ty,
- Ti::ValuePointer {
- size,
+ ..
+ } | Ti::Vector {
kind: Sk::Float,
- width,
- space: _,
- } => size == size0 && width == width0,
- _ => false,
- };
- if !good {
- return Err(ExpressionError::InvalidArgumentType(
- fun,
- 1,
- arg1.unwrap(),
- ));
+ ..
+ },
+ ) {
+ return Err(ExpressionError::InvalidArgumentType(fun, 1, arg));
}
}
Mf::Ldexp => {
|
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -456,10 +456,11 @@ fn binary_expression_mixed_scalar_and_vector_operands() {
#[test]
fn parse_pointers() {
parse_str(
- "fn foo() {
+ "fn foo(a: ptr<private, f32>) -> f32 { return *a; }
+ fn bar() {
var x: f32 = 1.0;
let px = &x;
- let py = frexp(0.5, px);
+ let py = foo(px);
}",
)
.unwrap();
diff --git a/tests/in/math-functions.wgsl b/tests/in/math-functions.wgsl
--- a/tests/in/math-functions.wgsl
+++ b/tests/in/math-functions.wgsl
@@ -31,4 +31,14 @@ fn main() {
let clz_d = countLeadingZeros(vec2(1u));
let lde_a = ldexp(1.0, 2);
let lde_b = ldexp(vec2(1.0, 2.0), vec2(3, 4));
+ let modf_a = modf(1.5);
+ let modf_b = modf(1.5).fract;
+ let modf_c = modf(1.5).whole;
+ let modf_d = modf(vec2(1.5, 1.5));
+ let modf_e = modf(vec4(1.5, 1.5, 1.5, 1.5)).whole.x;
+ let modf_f: f32 = modf(vec2(1.5, 1.5)).fract.y;
+ let frexp_a = frexp(1.5);
+ let frexp_b = frexp(1.5).fract;
+ let frexp_c: i32 = frexp(1.5).exp;
+ let frexp_d: i32 = frexp(vec4(1.5, 1.5, 1.5, 1.5)).exp.x;
}
diff --git a/tests/out/glsl/math-functions.main.Fragment.glsl b/tests/out/glsl/math-functions.main.Fragment.glsl
--- a/tests/out/glsl/math-functions.main.Fragment.glsl
+++ b/tests/out/glsl/math-functions.main.Fragment.glsl
@@ -3,6 +3,56 @@
precision highp float;
precision highp int;
+struct __modf_result_f32_ {
+ float fract_;
+ float whole;
+};
+struct __modf_result_vec2_f32_ {
+ vec2 fract_;
+ vec2 whole;
+};
+struct __modf_result_vec4_f32_ {
+ vec4 fract_;
+ vec4 whole;
+};
+struct __frexp_result_f32_ {
+ float fract_;
+ int exp_;
+};
+struct __frexp_result_vec4_f32_ {
+ vec4 fract_;
+ ivec4 exp_;
+};
+
+__modf_result_f32_ naga_modf(float arg) {
+ float other;
+ float fract = modf(arg, other);
+ return __modf_result_f32_(fract, other);
+}
+
+__modf_result_vec2_f32_ naga_modf(vec2 arg) {
+ vec2 other;
+ vec2 fract = modf(arg, other);
+ return __modf_result_vec2_f32_(fract, other);
+}
+
+__modf_result_vec4_f32_ naga_modf(vec4 arg) {
+ vec4 other;
+ vec4 fract = modf(arg, other);
+ return __modf_result_vec4_f32_(fract, other);
+}
+
+__frexp_result_f32_ naga_frexp(float arg) {
+ int other;
+ float fract = frexp(arg, other);
+ return __frexp_result_f32_(fract, other);
+}
+
+__frexp_result_vec4_f32_ naga_frexp(vec4 arg) {
+ ivec4 other;
+ vec4 fract = frexp(arg, other);
+ return __frexp_result_vec4_f32_(fract, other);
+}
void main() {
vec4 v = vec4(0.0);
diff --git a/tests/out/glsl/math-functions.main.Fragment.glsl b/tests/out/glsl/math-functions.main.Fragment.glsl
--- a/tests/out/glsl/math-functions.main.Fragment.glsl
+++ b/tests/out/glsl/math-functions.main.Fragment.glsl
@@ -36,5 +86,15 @@ void main() {
uvec2 clz_d = uvec2(ivec2(31) - findMSB(uvec2(1u)));
float lde_a = ldexp(1.0, 2);
vec2 lde_b = ldexp(vec2(1.0, 2.0), ivec2(3, 4));
+ __modf_result_f32_ modf_a = naga_modf(1.5);
+ float modf_b = naga_modf(1.5).fract_;
+ float modf_c = naga_modf(1.5).whole;
+ __modf_result_vec2_f32_ modf_d = naga_modf(vec2(1.5, 1.5));
+ float modf_e = naga_modf(vec4(1.5, 1.5, 1.5, 1.5)).whole.x;
+ float modf_f = naga_modf(vec2(1.5, 1.5)).fract_.y;
+ __frexp_result_f32_ frexp_a = naga_frexp(1.5);
+ float frexp_b = naga_frexp(1.5).fract_;
+ int frexp_c = naga_frexp(1.5).exp_;
+ int frexp_d = naga_frexp(vec4(1.5, 1.5, 1.5, 1.5)).exp_.x;
}
diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl
--- a/tests/out/hlsl/math-functions.hlsl
+++ b/tests/out/hlsl/math-functions.hlsl
@@ -1,3 +1,68 @@
+struct __modf_result_f32_ {
+ float fract;
+ float whole;
+};
+
+struct __modf_result_vec2_f32_ {
+ float2 fract;
+ float2 whole;
+};
+
+struct __modf_result_vec4_f32_ {
+ float4 fract;
+ float4 whole;
+};
+
+struct __frexp_result_f32_ {
+ float fract;
+ int exp_;
+};
+
+struct __frexp_result_vec4_f32_ {
+ float4 fract;
+ int4 exp_;
+};
+
+__modf_result_f32_ naga_modf(float arg) {
+ float other;
+ __modf_result_f32_ result;
+ result.fract = modf(arg, other);
+ result.whole = other;
+ return result;
+}
+
+__modf_result_vec2_f32_ naga_modf(float2 arg) {
+ float2 other;
+ __modf_result_vec2_f32_ result;
+ result.fract = modf(arg, other);
+ result.whole = other;
+ return result;
+}
+
+__modf_result_vec4_f32_ naga_modf(float4 arg) {
+ float4 other;
+ __modf_result_vec4_f32_ result;
+ result.fract = modf(arg, other);
+ result.whole = other;
+ return result;
+}
+
+__frexp_result_f32_ naga_frexp(float arg) {
+ float other;
+ __frexp_result_f32_ result;
+ result.fract = sign(arg) * frexp(arg, other);
+ result.exp_ = other;
+ return result;
+}
+
+__frexp_result_vec4_f32_ naga_frexp(float4 arg) {
+ float4 other;
+ __frexp_result_vec4_f32_ result;
+ result.fract = sign(arg) * frexp(arg, other);
+ result.exp_ = other;
+ return result;
+}
+
void main()
{
float4 v = (0.0).xxxx;
diff --git a/tests/out/hlsl/math-functions.hlsl b/tests/out/hlsl/math-functions.hlsl
--- a/tests/out/hlsl/math-functions.hlsl
+++ b/tests/out/hlsl/math-functions.hlsl
@@ -31,4 +96,14 @@ void main()
uint2 clz_d = ((31u).xx - firstbithigh((1u).xx));
float lde_a = ldexp(1.0, 2);
float2 lde_b = ldexp(float2(1.0, 2.0), int2(3, 4));
+ __modf_result_f32_ modf_a = naga_modf(1.5);
+ float modf_b = naga_modf(1.5).fract;
+ float modf_c = naga_modf(1.5).whole;
+ __modf_result_vec2_f32_ modf_d = naga_modf(float2(1.5, 1.5));
+ float modf_e = naga_modf(float4(1.5, 1.5, 1.5, 1.5)).whole.x;
+ float modf_f = naga_modf(float2(1.5, 1.5)).fract.y;
+ __frexp_result_f32_ frexp_a = naga_frexp(1.5);
+ float frexp_b = naga_frexp(1.5).fract;
+ int frexp_c = naga_frexp(1.5).exp_;
+ int frexp_d = naga_frexp(float4(1.5, 1.5, 1.5, 1.5)).exp_.x;
}
diff --git a/tests/out/ir/access.ron b/tests/out/ir/access.ron
--- a/tests/out/ir/access.ron
+++ b/tests/out/ir/access.ron
@@ -334,6 +334,7 @@
special_types: (
ray_desc: None,
ray_intersection: None,
+ predeclared_types: {},
),
constants: [],
global_variables: [
diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron
--- a/tests/out/ir/collatz.ron
+++ b/tests/out/ir/collatz.ron
@@ -41,6 +41,7 @@
special_types: (
ray_desc: None,
ray_intersection: None,
+ predeclared_types: {},
),
constants: [],
global_variables: [
diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron
--- a/tests/out/ir/shadow.ron
+++ b/tests/out/ir/shadow.ron
@@ -266,6 +266,7 @@
special_types: (
ray_desc: None,
ray_intersection: None,
+ predeclared_types: {},
),
constants: [
(
diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl
--- a/tests/out/msl/math-functions.msl
+++ b/tests/out/msl/math-functions.msl
@@ -4,6 +4,56 @@
using metal::uint;
+struct __modf_result_f32_ {
+ float fract;
+ float whole;
+};
+struct __modf_result_vec2_f32_ {
+ metal::float2 fract;
+ metal::float2 whole;
+};
+struct __modf_result_vec4_f32_ {
+ metal::float4 fract;
+ metal::float4 whole;
+};
+struct __frexp_result_f32_ {
+ float fract;
+ int exp;
+};
+struct __frexp_result_vec4_f32_ {
+ metal::float4 fract;
+ metal::int4 exp;
+};
+
+__modf_result_f32_ naga_modf(float arg) {
+ float other;
+ float fract = metal::modf(arg, other);
+ return __modf_result_f32_{ fract, other };
+}
+
+__modf_result_vec2_f32_ naga_modf(metal::float2 arg) {
+ metal::float2 other;
+ metal::float2 fract = metal::modf(arg, other);
+ return __modf_result_vec2_f32_{ fract, other };
+}
+
+__modf_result_vec4_f32_ naga_modf(metal::float4 arg) {
+ metal::float4 other;
+ metal::float4 fract = metal::modf(arg, other);
+ return __modf_result_vec4_f32_{ fract, other };
+}
+
+__frexp_result_f32_ naga_frexp(float arg) {
+ int other;
+ float fract = metal::frexp(arg, other);
+ return __frexp_result_f32_{ fract, other };
+}
+
+__frexp_result_vec4_f32_ naga_frexp(metal::float4 arg) {
+ int4 other;
+ metal::float4 fract = metal::frexp(arg, other);
+ return __frexp_result_vec4_f32_{ fract, other };
+}
fragment void main_(
) {
diff --git a/tests/out/msl/math-functions.msl b/tests/out/msl/math-functions.msl
--- a/tests/out/msl/math-functions.msl
+++ b/tests/out/msl/math-functions.msl
@@ -40,4 +90,14 @@ fragment void main_(
metal::uint2 clz_d = metal::clz(metal::uint2(1u));
float lde_a = metal::ldexp(1.0, 2);
metal::float2 lde_b = metal::ldexp(metal::float2(1.0, 2.0), metal::int2(3, 4));
+ __modf_result_f32_ modf_a = naga_modf(1.5);
+ float modf_b = naga_modf(1.5).fract;
+ float modf_c = naga_modf(1.5).whole;
+ __modf_result_vec2_f32_ modf_d = naga_modf(metal::float2(1.5, 1.5));
+ float modf_e = naga_modf(metal::float4(1.5, 1.5, 1.5, 1.5)).whole.x;
+ float modf_f = naga_modf(metal::float2(1.5, 1.5)).fract.y;
+ __frexp_result_f32_ frexp_a = naga_frexp(1.5);
+ float frexp_b = naga_frexp(1.5).fract;
+ int frexp_c = naga_frexp(1.5).exp;
+ int frexp_d = naga_frexp(metal::float4(1.5, 1.5, 1.5, 1.5)).exp.x;
}
diff --git a/tests/out/spv/math-functions.spvasm b/tests/out/spv/math-functions.spvasm
--- a/tests/out/spv/math-functions.spvasm
+++ b/tests/out/spv/math-functions.spvasm
@@ -1,106 +1,147 @@
; SPIR-V
; Version: 1.1
; Generator: rspirv
-; Bound: 96
+; Bound: 127
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
-OpEntryPoint Fragment %9 "main"
-OpExecutionMode %9 OriginUpperLeft
+OpEntryPoint Fragment %15 "main"
+OpExecutionMode %15 OriginUpperLeft
+OpMemberDecorate %8 0 Offset 0
+OpMemberDecorate %8 1 Offset 4
+OpMemberDecorate %9 0 Offset 0
+OpMemberDecorate %9 1 Offset 8
+OpMemberDecorate %10 0 Offset 0
+OpMemberDecorate %10 1 Offset 16
+OpMemberDecorate %11 0 Offset 0
+OpMemberDecorate %11 1 Offset 4
+OpMemberDecorate %13 0 Offset 0
+OpMemberDecorate %13 1 Offset 16
%2 = OpTypeVoid
%4 = OpTypeFloat 32
%3 = OpTypeVector %4 4
%6 = OpTypeInt 32 1
%5 = OpTypeVector %6 2
%7 = OpTypeVector %4 2
-%10 = OpTypeFunction %2
-%11 = OpConstant %4 1.0
-%12 = OpConstant %4 0.0
-%13 = OpConstantNull %5
-%14 = OpTypeInt 32 0
-%15 = OpConstant %14 0
-%16 = OpConstant %6 -1
-%17 = OpConstant %14 1
-%18 = OpConstant %6 0
-%19 = OpConstant %14 4294967295
-%20 = OpConstant %6 1
-%21 = OpConstant %6 2
-%22 = OpConstant %4 2.0
-%23 = OpConstant %6 3
-%24 = OpConstant %6 4
-%32 = OpConstantComposite %3 %12 %12 %12 %12
-%33 = OpConstantComposite %3 %11 %11 %11 %11
-%36 = OpConstantNull %6
-%49 = OpTypeVector %14 2
-%59 = OpConstant %14 32
-%69 = OpConstantComposite %49 %59 %59
-%81 = OpConstant %6 31
-%87 = OpConstantComposite %5 %81 %81
-%9 = OpFunction %2 None %10
-%8 = OpLabel
-OpBranch %25
-%25 = OpLabel
-%26 = OpCompositeConstruct %3 %12 %12 %12 %12
-%27 = OpExtInst %4 %1 Degrees %11
-%28 = OpExtInst %4 %1 Radians %11
-%29 = OpExtInst %3 %1 Degrees %26
-%30 = OpExtInst %3 %1 Radians %26
-%31 = OpExtInst %3 %1 FClamp %26 %32 %33
-%34 = OpExtInst %3 %1 Refract %26 %26 %11
-%37 = OpCompositeExtract %6 %13 0
-%38 = OpCompositeExtract %6 %13 0
-%39 = OpIMul %6 %37 %38
-%40 = OpIAdd %6 %36 %39
-%41 = OpCompositeExtract %6 %13 1
-%42 = OpCompositeExtract %6 %13 1
-%43 = OpIMul %6 %41 %42
-%35 = OpIAdd %6 %40 %43
-%44 = OpCopyObject %14 %15
-%45 = OpExtInst %14 %1 FindUMsb %44
-%46 = OpExtInst %6 %1 FindSMsb %16
-%47 = OpCompositeConstruct %5 %16 %16
-%48 = OpExtInst %5 %1 FindSMsb %47
-%50 = OpCompositeConstruct %49 %17 %17
-%51 = OpExtInst %49 %1 FindUMsb %50
-%52 = OpExtInst %6 %1 FindILsb %16
-%53 = OpExtInst %14 %1 FindILsb %17
-%54 = OpCompositeConstruct %5 %16 %16
-%55 = OpExtInst %5 %1 FindILsb %54
-%56 = OpCompositeConstruct %49 %17 %17
-%57 = OpExtInst %49 %1 FindILsb %56
-%60 = OpExtInst %14 %1 FindILsb %15
-%58 = OpExtInst %14 %1 UMin %59 %60
-%62 = OpExtInst %6 %1 FindILsb %18
-%61 = OpExtInst %6 %1 UMin %59 %62
-%64 = OpExtInst %14 %1 FindILsb %19
-%63 = OpExtInst %14 %1 UMin %59 %64
-%66 = OpExtInst %6 %1 FindILsb %16
-%65 = OpExtInst %6 %1 UMin %59 %66
-%67 = OpCompositeConstruct %49 %15 %15
-%70 = OpExtInst %49 %1 FindILsb %67
-%68 = OpExtInst %49 %1 UMin %69 %70
-%71 = OpCompositeConstruct %5 %18 %18
-%73 = OpExtInst %5 %1 FindILsb %71
-%72 = OpExtInst %5 %1 UMin %69 %73
-%74 = OpCompositeConstruct %49 %17 %17
-%76 = OpExtInst %49 %1 FindILsb %74
-%75 = OpExtInst %49 %1 UMin %69 %76
-%77 = OpCompositeConstruct %5 %20 %20
-%79 = OpExtInst %5 %1 FindILsb %77
-%78 = OpExtInst %5 %1 UMin %69 %79
-%82 = OpExtInst %6 %1 FindUMsb %16
-%80 = OpISub %6 %81 %82
-%84 = OpExtInst %6 %1 FindUMsb %17
-%83 = OpISub %14 %81 %84
-%85 = OpCompositeConstruct %5 %16 %16
-%88 = OpExtInst %5 %1 FindUMsb %85
-%86 = OpISub %5 %87 %88
-%89 = OpCompositeConstruct %49 %17 %17
-%91 = OpExtInst %5 %1 FindUMsb %89
-%90 = OpISub %49 %87 %91
-%92 = OpExtInst %4 %1 Ldexp %11 %21
-%93 = OpCompositeConstruct %7 %11 %22
-%94 = OpCompositeConstruct %5 %23 %24
-%95 = OpExtInst %7 %1 Ldexp %93 %94
+%8 = OpTypeStruct %4 %4
+%9 = OpTypeStruct %7 %7
+%10 = OpTypeStruct %3 %3
+%11 = OpTypeStruct %4 %6
+%12 = OpTypeVector %6 4
+%13 = OpTypeStruct %3 %12
+%16 = OpTypeFunction %2
+%17 = OpConstant %4 1.0
+%18 = OpConstant %4 0.0
+%19 = OpConstantNull %5
+%20 = OpTypeInt 32 0
+%21 = OpConstant %20 0
+%22 = OpConstant %6 -1
+%23 = OpConstant %20 1
+%24 = OpConstant %6 0
+%25 = OpConstant %20 4294967295
+%26 = OpConstant %6 1
+%27 = OpConstant %6 2
+%28 = OpConstant %4 2.0
+%29 = OpConstant %6 3
+%30 = OpConstant %6 4
+%31 = OpConstant %4 1.5
+%39 = OpConstantComposite %3 %18 %18 %18 %18
+%40 = OpConstantComposite %3 %17 %17 %17 %17
+%43 = OpConstantNull %6
+%56 = OpTypeVector %20 2
+%66 = OpConstant %20 32
+%76 = OpConstantComposite %56 %66 %66
+%88 = OpConstant %6 31
+%94 = OpConstantComposite %5 %88 %88
+%15 = OpFunction %2 None %16
+%14 = OpLabel
+OpBranch %32
+%32 = OpLabel
+%33 = OpCompositeConstruct %3 %18 %18 %18 %18
+%34 = OpExtInst %4 %1 Degrees %17
+%35 = OpExtInst %4 %1 Radians %17
+%36 = OpExtInst %3 %1 Degrees %33
+%37 = OpExtInst %3 %1 Radians %33
+%38 = OpExtInst %3 %1 FClamp %33 %39 %40
+%41 = OpExtInst %3 %1 Refract %33 %33 %17
+%44 = OpCompositeExtract %6 %19 0
+%45 = OpCompositeExtract %6 %19 0
+%46 = OpIMul %6 %44 %45
+%47 = OpIAdd %6 %43 %46
+%48 = OpCompositeExtract %6 %19 1
+%49 = OpCompositeExtract %6 %19 1
+%50 = OpIMul %6 %48 %49
+%42 = OpIAdd %6 %47 %50
+%51 = OpCopyObject %20 %21
+%52 = OpExtInst %20 %1 FindUMsb %51
+%53 = OpExtInst %6 %1 FindSMsb %22
+%54 = OpCompositeConstruct %5 %22 %22
+%55 = OpExtInst %5 %1 FindSMsb %54
+%57 = OpCompositeConstruct %56 %23 %23
+%58 = OpExtInst %56 %1 FindUMsb %57
+%59 = OpExtInst %6 %1 FindILsb %22
+%60 = OpExtInst %20 %1 FindILsb %23
+%61 = OpCompositeConstruct %5 %22 %22
+%62 = OpExtInst %5 %1 FindILsb %61
+%63 = OpCompositeConstruct %56 %23 %23
+%64 = OpExtInst %56 %1 FindILsb %63
+%67 = OpExtInst %20 %1 FindILsb %21
+%65 = OpExtInst %20 %1 UMin %66 %67
+%69 = OpExtInst %6 %1 FindILsb %24
+%68 = OpExtInst %6 %1 UMin %66 %69
+%71 = OpExtInst %20 %1 FindILsb %25
+%70 = OpExtInst %20 %1 UMin %66 %71
+%73 = OpExtInst %6 %1 FindILsb %22
+%72 = OpExtInst %6 %1 UMin %66 %73
+%74 = OpCompositeConstruct %56 %21 %21
+%77 = OpExtInst %56 %1 FindILsb %74
+%75 = OpExtInst %56 %1 UMin %76 %77
+%78 = OpCompositeConstruct %5 %24 %24
+%80 = OpExtInst %5 %1 FindILsb %78
+%79 = OpExtInst %5 %1 UMin %76 %80
+%81 = OpCompositeConstruct %56 %23 %23
+%83 = OpExtInst %56 %1 FindILsb %81
+%82 = OpExtInst %56 %1 UMin %76 %83
+%84 = OpCompositeConstruct %5 %26 %26
+%86 = OpExtInst %5 %1 FindILsb %84
+%85 = OpExtInst %5 %1 UMin %76 %86
+%89 = OpExtInst %6 %1 FindUMsb %22
+%87 = OpISub %6 %88 %89
+%91 = OpExtInst %6 %1 FindUMsb %23
+%90 = OpISub %20 %88 %91
+%92 = OpCompositeConstruct %5 %22 %22
+%95 = OpExtInst %5 %1 FindUMsb %92
+%93 = OpISub %5 %94 %95
+%96 = OpCompositeConstruct %56 %23 %23
+%98 = OpExtInst %5 %1 FindUMsb %96
+%97 = OpISub %56 %94 %98
+%99 = OpExtInst %4 %1 Ldexp %17 %27
+%100 = OpCompositeConstruct %7 %17 %28
+%101 = OpCompositeConstruct %5 %29 %30
+%102 = OpExtInst %7 %1 Ldexp %100 %101
+%103 = OpExtInst %8 %1 ModfStruct %31
+%104 = OpExtInst %8 %1 ModfStruct %31
+%105 = OpCompositeExtract %4 %104 0
+%106 = OpExtInst %8 %1 ModfStruct %31
+%107 = OpCompositeExtract %4 %106 1
+%108 = OpCompositeConstruct %7 %31 %31
+%109 = OpExtInst %9 %1 ModfStruct %108
+%110 = OpCompositeConstruct %3 %31 %31 %31 %31
+%111 = OpExtInst %10 %1 ModfStruct %110
+%112 = OpCompositeExtract %3 %111 1
+%113 = OpCompositeExtract %4 %112 0
+%114 = OpCompositeConstruct %7 %31 %31
+%115 = OpExtInst %9 %1 ModfStruct %114
+%116 = OpCompositeExtract %7 %115 0
+%117 = OpCompositeExtract %4 %116 1
+%118 = OpExtInst %11 %1 FrexpStruct %31
+%119 = OpExtInst %11 %1 FrexpStruct %31
+%120 = OpCompositeExtract %4 %119 0
+%121 = OpExtInst %11 %1 FrexpStruct %31
+%122 = OpCompositeExtract %6 %121 1
+%123 = OpCompositeConstruct %3 %31 %31 %31 %31
+%124 = OpExtInst %13 %1 FrexpStruct %123
+%125 = OpCompositeExtract %12 %124 1
+%126 = OpCompositeExtract %6 %125 0
OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/wgsl/atomicCompareExchange.wgsl b/tests/out/wgsl/atomicCompareExchange.wgsl
--- a/tests/out/wgsl/atomicCompareExchange.wgsl
+++ b/tests/out/wgsl/atomicCompareExchange.wgsl
@@ -1,13 +1,3 @@
-struct gen___atomic_compare_exchange_resultSint4_ {
- old_value: i32,
- exchanged: bool,
-}
-
-struct gen___atomic_compare_exchange_resultUint4_ {
- old_value: u32,
- exchanged: bool,
-}
-
const SIZE: u32 = 128u;
@group(0) @binding(0)
diff --git a/tests/out/wgsl/math-functions.wgsl b/tests/out/wgsl/math-functions.wgsl
--- a/tests/out/wgsl/math-functions.wgsl
+++ b/tests/out/wgsl/math-functions.wgsl
@@ -30,4 +30,14 @@ fn main() {
let clz_d = countLeadingZeros(vec2<u32>(1u));
let lde_a = ldexp(1.0, 2);
let lde_b = ldexp(vec2<f32>(1.0, 2.0), vec2<i32>(3, 4));
+ let modf_a = modf(1.5);
+ let modf_b = modf(1.5).fract;
+ let modf_c = modf(1.5).whole;
+ let modf_d = modf(vec2<f32>(1.5, 1.5));
+ let modf_e = modf(vec4<f32>(1.5, 1.5, 1.5, 1.5)).whole.x;
+ let modf_f = modf(vec2<f32>(1.5, 1.5)).fract.y;
+ let frexp_a = frexp(1.5);
+ let frexp_b = frexp(1.5).fract;
+ let frexp_c = frexp(1.5).exp;
+ let frexp_d = frexp(vec4<f32>(1.5, 1.5, 1.5, 1.5)).exp.x;
}
|
Change frexp and modf to work with structures
See https://github.com/gpuweb/gpuweb/pull/1973
I think this change needs to be done at IR level.
Change frexp and modf to return structures
Closes #1161
TODO:
- [x] IR
- [x] validation
- [x] typifier
- [ ] frontends (except WGSL)
- [ ] backends (except WGSL)
|
Similar work needs to be done for atomic compare+exchange - https://github.com/gpuweb/gpuweb/pull/2113
I think all of this should wait for #1419 first.
This isn't urgent for the release.
Currently bumping up against this when targeting WebGPU, as wgpu's water example uses modf.
This should be simpler now that #2256 is in, which contains infra to create IR structure types.
This branch has conflicts that must be resolved
|
2023-08-24T00:48:00Z
|
0.13
|
2023-09-03T21:16:06Z
|
a17a93ef8f6a06ed8dfc3145276663786828df03
|
[
"convert_wgsl"
] |
[
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::access",
"back::msl::test_error_size",
"front::glsl::constants::tests::cast",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::nan_handling",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::spv::test::parse",
"front::wgsl::parse::lexer::test_numbers",
"front::wgsl::parse::lexer::test_tokens",
"front::wgsl::parse::lexer::test_variable_decl",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_alias",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_missing_workgroup_size",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_parentheses_if",
"front::glsl::parser_tests::declarations",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_parentheses_switch",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_repeated_attributes",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_switch_default_in_case",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::namer::test",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_texture_query",
"span::span_location",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_standard_fun",
"valid::handles::constant_deps",
"front::wgsl::tests::parse_type_inference",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_types",
"proc::test_matrix_size",
"front::wgsl::tests::parse_texture_load_store_expecting_four_args",
"front::wgsl::tests::binary_expression_mixed_scalar_and_vector_operands",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"convert_glsl_variations_check",
"convert_glsl_folder",
"convert_spv_all",
"sampler1d",
"storage1d",
"cube_array",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"assign_to_expr",
"bad_for_initializer",
"binary_statement",
"bad_texture_sample_type",
"bad_type_cast",
"binding_array_local",
"binding_array_private",
"binding_array_non_struct",
"bad_texture",
"break_if_bad_condition",
"cyclic_function",
"function_param_redefinition_as_local",
"function_param_redefinition_as_param",
"assign_to_let",
"function_without_identifier",
"function_returns_void",
"constructor_parameter_type_mismatch",
"discard_in_wrong_stage",
"inconsistent_binding",
"invalid_integer",
"host_shareable_types",
"invalid_texture_sample_type",
"invalid_float",
"dead_code",
"invalid_arrays",
"invalid_local_vars",
"invalid_access",
"invalid_structs",
"misplaced_break_if",
"local_var_missing_type",
"invalid_functions",
"let_type_mismatch",
"invalid_runtime_sized_arrays",
"matrix_with_bad_type",
"missing_default_case",
"reserved_identifier_prefix",
"negative_index",
"missing_bindings2",
"recursive_function",
"struct_member_align_too_low",
"pointer_type_equivalence",
"module_scope_identifier_redefinition",
"struct_member_size_too_low",
"missing_bindings",
"type_not_inferrable",
"reserved_keyword",
"unknown_attribute",
"unknown_access",
"unexpected_constructor_parameters",
"switch_signed_unsigned_mismatch",
"postfix_pointers",
"select",
"unknown_conservative_depth",
"struct_member_non_po2_align",
"swizzle_assignment",
"unknown_built_in",
"type_not_constructible",
"unknown_storage_class",
"unknown_identifier",
"io_shareable_types",
"unknown_type",
"unknown_local_function",
"unknown_scalar_type",
"unknown_ident",
"var_type_mismatch",
"unknown_storage_format",
"valid_access",
"wrong_access_mode",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 717)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 738)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/mod.rs - front::SymbolTable (line 201)",
"src/front/glsl/mod.rs - front::glsl::Frontend (line 142)"
] |
[] |
[] |
gfx-rs/naga
| 2,440
|
gfx-rs__naga-2440
|
[
"2439"
] |
7a19f3af909202c7eafd36633b5584bfbb353ecb
|
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -504,13 +504,25 @@ impl<'source, 'temp, 'out> ExpressionContext<'source, 'temp, 'out> {
}
/// Insert splats, if needed by the non-'*' operations.
+ ///
+ /// See the "Binary arithmetic expressions with mixed scalar and vector operands"
+ /// table in the WebGPU Shading Language specification for relevant operators.
+ ///
+ /// Multiply is not handled here as backends are expected to handle vec*scalar
+ /// operations, so inserting splats into the IR increases size needlessly.
fn binary_op_splat(
&mut self,
op: crate::BinaryOperator,
left: &mut Handle<crate::Expression>,
right: &mut Handle<crate::Expression>,
) -> Result<(), Error<'source>> {
- if op != crate::BinaryOperator::Multiply {
+ if matches!(
+ op,
+ crate::BinaryOperator::Add
+ | crate::BinaryOperator::Subtract
+ | crate::BinaryOperator::Divide
+ | crate::BinaryOperator::Modulo
+ ) {
self.grow_types(*left)?.grow_types(*right)?;
let left_size = match *self.resolved_inner(*left) {
|
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -387,6 +387,54 @@ fn parse_expressions() {
}").unwrap();
}
+#[test]
+fn binary_expression_mixed_scalar_and_vector_operands() {
+ for (operand, expect_splat) in [
+ ('<', false),
+ ('>', false),
+ ('&', false),
+ ('|', false),
+ ('+', true),
+ ('-', true),
+ ('*', false),
+ ('/', true),
+ ('%', true),
+ ] {
+ let module = parse_str(&format!(
+ "
+ const some_vec = vec3<f32>(1.0, 1.0, 1.0);
+ @fragment
+ fn main() -> @location(0) vec4<f32> {{
+ if (all(1.0 {operand} some_vec)) {{
+ return vec4(0.0);
+ }}
+ return vec4(1.0);
+ }}
+ "
+ ))
+ .unwrap();
+
+ let expressions = &&module.entry_points[0].function.expressions;
+
+ let found_expressions = expressions
+ .iter()
+ .filter(|&(_, e)| {
+ if let crate::Expression::Binary { left, .. } = *e {
+ matches!(
+ (expect_splat, &expressions[left]),
+ (false, &crate::Expression::Literal(crate::Literal::F32(..)))
+ | (true, &crate::Expression::Splat { .. })
+ )
+ } else {
+ false
+ }
+ })
+ .count();
+
+ assert_eq!(found_expressions, 1);
+ }
+}
+
#[test]
fn parse_pointers() {
parse_str(
|
[wgsl-in] Comparing scalar with vector type incorrectly passes validation
Spec says both sides of the comparision need to have the same type.
https://www.w3.org/TR/WGSL/#comparison-expr
The following snippet should therefore not pass validation.
```
const some_vec = vec3<f32>(1.0, 1.0, 1.0);
@fragment
fn main() -> @location(0) vec4<f32> {
if (all(1.0 < some_vec)) {
return vec4(0.0);
}
return vec4(1.0);
}
```
Note that Chrome will already correctly reject this, whereas Naga doesn't
|
2023-08-16T18:09:02Z
|
0.13
|
2023-08-18T13:08:28Z
|
a17a93ef8f6a06ed8dfc3145276663786828df03
|
[
"front::wgsl::tests::binary_expression_mixed_scalar_and_vector_operands"
] |
[
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"back::msl::test_error_size",
"arena::tests::fetch_or_append_unique",
"back::spv::layout::test_logical_layout_in_words",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::nan_handling",
"front::glsl::constants::tests::unary_op",
"back::msl::writer::test_stack_size",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"front::wgsl::parse::lexer::test_numbers",
"front::spv::test::parse",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::parse::lexer::test_variable_decl",
"front::glsl::parser_tests::control_flow",
"front::wgsl::parse::lexer::test_tokens",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_alias",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::functions",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_parentheses_switch",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_repeated_attributes",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_switch_default_in_case",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_type_cast",
"proc::namer::test",
"proc::test_matrix_size",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_type_inference",
"proc::typifier::test_error_size",
"span::span_location",
"valid::handles::constant_deps",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_texture_load",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_load_store_expecting_four_args",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"convert_wgsl",
"cube_array",
"sampler1d",
"geometry",
"storage1d",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"bad_for_initializer",
"assign_to_expr",
"bad_texture_sample_type",
"binary_statement",
"binding_array_non_struct",
"binding_array_local",
"bad_type_cast",
"binding_array_private",
"bad_texture",
"break_if_bad_condition",
"function_param_redefinition_as_local",
"function_without_identifier",
"function_param_redefinition_as_param",
"cyclic_function",
"inconsistent_binding",
"assign_to_let",
"dead_code",
"discard_in_wrong_stage",
"function_returns_void",
"constructor_parameter_type_mismatch",
"invalid_float",
"invalid_integer",
"invalid_texture_sample_type",
"invalid_local_vars",
"local_var_missing_type",
"invalid_arrays",
"invalid_access",
"let_type_mismatch",
"invalid_runtime_sized_arrays",
"misplaced_break_if",
"invalid_structs",
"matrix_with_bad_type",
"missing_default_case",
"reserved_identifier_prefix",
"missing_bindings2",
"recursive_function",
"negative_index",
"invalid_functions",
"pointer_type_equivalence",
"struct_member_align_too_low",
"struct_member_size_too_low",
"missing_bindings",
"host_shareable_types",
"switch_signed_unsigned_mismatch",
"postfix_pointers",
"struct_member_non_po2_align",
"swizzle_assignment",
"type_not_constructible",
"unknown_attribute",
"unexpected_constructor_parameters",
"type_not_inferrable",
"reserved_keyword",
"unknown_ident",
"unknown_access",
"unknown_identifier",
"unknown_local_function",
"select",
"unknown_storage_class",
"unknown_type",
"unknown_built_in",
"module_scope_identifier_redefinition",
"var_type_mismatch",
"unknown_conservative_depth",
"unknown_scalar_type",
"valid_access",
"wrong_access_mode",
"io_shareable_types",
"unknown_storage_format",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 717)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 738)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/mod.rs - front::SymbolTable (line 201)",
"src/front/glsl/mod.rs - front::glsl::Frontend (line 142)"
] |
[] |
[] |
|
gfx-rs/naga
| 2,353
|
gfx-rs__naga-2353
|
[
"1929"
] |
273ff5d829f8207d8d93b70e32e2889362246d33
|
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -121,13 +121,40 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
self.need_bake_expressions.insert(fun_handle);
}
- if let Expression::Math { fun, arg, .. } = *expr {
+ if let Expression::Math {
+ fun,
+ arg,
+ arg1,
+ arg2,
+ arg3,
+ } = *expr
+ {
match fun {
crate::MathFunction::Asinh
| crate::MathFunction::Acosh
| crate::MathFunction::Atanh
- | crate::MathFunction::Unpack2x16float => {
+ | crate::MathFunction::Unpack2x16float
+ | crate::MathFunction::Unpack2x16snorm
+ | crate::MathFunction::Unpack2x16unorm
+ | crate::MathFunction::Unpack4x8snorm
+ | crate::MathFunction::Unpack4x8unorm
+ | crate::MathFunction::Pack2x16float
+ | crate::MathFunction::Pack2x16snorm
+ | crate::MathFunction::Pack2x16unorm
+ | crate::MathFunction::Pack4x8snorm
+ | crate::MathFunction::Pack4x8unorm => {
+ self.need_bake_expressions.insert(arg);
+ }
+ crate::MathFunction::ExtractBits => {
+ self.need_bake_expressions.insert(arg);
+ self.need_bake_expressions.insert(arg1.unwrap());
+ self.need_bake_expressions.insert(arg2.unwrap());
+ }
+ crate::MathFunction::InsertBits => {
self.need_bake_expressions.insert(arg);
+ self.need_bake_expressions.insert(arg1.unwrap());
+ self.need_bake_expressions.insert(arg2.unwrap());
+ self.need_bake_expressions.insert(arg3.unwrap());
}
crate::MathFunction::CountLeadingZeros => {
let inner = info[fun_handle].ty.inner_with(&module.types);
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -2590,7 +2617,18 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
enum Function {
Asincosh { is_sin: bool },
Atanh,
+ ExtractBits,
+ InsertBits,
+ Pack2x16float,
+ Pack2x16snorm,
+ Pack2x16unorm,
+ Pack4x8snorm,
+ Pack4x8unorm,
Unpack2x16float,
+ Unpack2x16snorm,
+ Unpack2x16unorm,
+ Unpack4x8snorm,
+ Unpack4x8unorm,
Regular(&'static str),
MissingIntOverload(&'static str),
MissingIntReturnType(&'static str),
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -2664,7 +2702,20 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
Mf::ReverseBits => Function::MissingIntOverload("reversebits"),
Mf::FindLsb => Function::MissingIntReturnType("firstbitlow"),
Mf::FindMsb => Function::MissingIntReturnType("firstbithigh"),
+ Mf::ExtractBits => Function::ExtractBits,
+ Mf::InsertBits => Function::InsertBits,
+ // Data Packing
+ Mf::Pack2x16float => Function::Pack2x16float,
+ Mf::Pack2x16snorm => Function::Pack2x16snorm,
+ Mf::Pack2x16unorm => Function::Pack2x16unorm,
+ Mf::Pack4x8snorm => Function::Pack4x8snorm,
+ Mf::Pack4x8unorm => Function::Pack4x8unorm,
+ // Data Unpacking
Mf::Unpack2x16float => Function::Unpack2x16float,
+ Mf::Unpack2x16snorm => Function::Unpack2x16snorm,
+ Mf::Unpack2x16unorm => Function::Unpack2x16unorm,
+ Mf::Unpack4x8snorm => Function::Unpack4x8snorm,
+ Mf::Unpack4x8unorm => Function::Unpack4x8unorm,
_ => return Err(Error::Unimplemented(format!("write_expr_math {fun:?}"))),
};
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -2688,6 +2739,140 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
self.write_expr(module, arg, func_ctx)?;
write!(self.out, "))")?;
}
+ Function::ExtractBits => {
+ // e: T,
+ // offset: u32,
+ // count: u32
+ // T is u32 or i32 or vecN<u32> or vecN<i32>
+ if let (Some(offset), Some(count)) = (arg1, arg2) {
+ let scalar_width: u8 = 32;
+ // Works for signed and unsigned
+ // (count == 0 ? 0 : (e << (32 - count - offset)) >> (32 - count))
+ write!(self.out, "(")?;
+ self.write_expr(module, count, func_ctx)?;
+ write!(self.out, " == 0 ? 0 : (")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " << ({scalar_width} - ")?;
+ self.write_expr(module, count, func_ctx)?;
+ write!(self.out, " - ")?;
+ self.write_expr(module, offset, func_ctx)?;
+ write!(self.out, ")) >> ({scalar_width} - ")?;
+ self.write_expr(module, count, func_ctx)?;
+ write!(self.out, "))")?;
+ }
+ }
+ Function::InsertBits => {
+ // e: T,
+ // newbits: T,
+ // offset: u32,
+ // count: u32
+ // returns T
+ // T is i32, u32, vecN<i32>, or vecN<u32>
+ if let (Some(newbits), Some(offset), Some(count)) = (arg1, arg2, arg3) {
+ let scalar_width: u8 = 32;
+ let scalar_max: u32 = 0xFFFFFFFF;
+ // mask = ((0xFFFFFFFFu >> (32 - count)) << offset)
+ // (count == 0 ? e : ((e & ~mask) | ((newbits << offset) & mask)))
+ write!(self.out, "(")?;
+ self.write_expr(module, count, func_ctx)?;
+ write!(self.out, " == 0 ? ")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " : ")?;
+ write!(self.out, "(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " & ~")?;
+ // mask
+ write!(self.out, "(({scalar_max}u >> ({scalar_width}u - ")?;
+ self.write_expr(module, count, func_ctx)?;
+ write!(self.out, ")) << ")?;
+ self.write_expr(module, offset, func_ctx)?;
+ write!(self.out, ")")?;
+ // end mask
+ write!(self.out, ") | ((")?;
+ self.write_expr(module, newbits, func_ctx)?;
+ write!(self.out, " << ")?;
+ self.write_expr(module, offset, func_ctx)?;
+ write!(self.out, ") & ")?;
+ // // mask
+ write!(self.out, "(({scalar_max}u >> ({scalar_width}u - ")?;
+ self.write_expr(module, count, func_ctx)?;
+ write!(self.out, ")) << ")?;
+ self.write_expr(module, offset, func_ctx)?;
+ write!(self.out, ")")?;
+ // // end mask
+ write!(self.out, "))")?;
+ }
+ }
+ Function::Pack2x16float => {
+ write!(self.out, "(f32tof16(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, "[0]) | f32tof16(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, "[1]) << 16)")?;
+ }
+ Function::Pack2x16snorm => {
+ let scale = 32767;
+
+ write!(self.out, "uint((int(round(clamp(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(
+ self.out,
+ "[0], -1.0, 1.0) * {scale}.0)) & 0xFFFF) | ((int(round(clamp("
+ )?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, "[1], -1.0, 1.0) * {scale}.0)) & 0xFFFF) << 16))",)?;
+ }
+ Function::Pack2x16unorm => {
+ let scale = 65535;
+
+ write!(self.out, "(uint(round(clamp(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, "[0], 0.0, 1.0) * {scale}.0)) | uint(round(clamp(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, "[1], 0.0, 1.0) * {scale}.0)) << 16)")?;
+ }
+ Function::Pack4x8snorm => {
+ let scale = 127;
+
+ write!(self.out, "uint((int(round(clamp(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(
+ self.out,
+ "[0], -1.0, 1.0) * {scale}.0)) & 0xFF) | ((int(round(clamp("
+ )?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(
+ self.out,
+ "[1], -1.0, 1.0) * {scale}.0)) & 0xFF) << 8) | ((int(round(clamp("
+ )?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(
+ self.out,
+ "[2], -1.0, 1.0) * {scale}.0)) & 0xFF) << 16) | ((int(round(clamp("
+ )?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, "[3], -1.0, 1.0) * {scale}.0)) & 0xFF) << 24))",)?;
+ }
+ Function::Pack4x8unorm => {
+ let scale = 255;
+
+ write!(self.out, "(uint(round(clamp(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, "[0], 0.0, 1.0) * {scale}.0)) | uint(round(clamp(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(
+ self.out,
+ "[1], 0.0, 1.0) * {scale}.0)) << 8 | uint(round(clamp("
+ )?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(
+ self.out,
+ "[2], 0.0, 1.0) * {scale}.0)) << 16 | uint(round(clamp("
+ )?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, "[3], 0.0, 1.0) * {scale}.0)) << 24)")?;
+ }
+
Function::Unpack2x16float => {
write!(self.out, "float2(f16tof32(")?;
self.write_expr(module, arg, func_ctx)?;
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -2695,6 +2880,50 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
self.write_expr(module, arg, func_ctx)?;
write!(self.out, ") >> 16))")?;
}
+ Function::Unpack2x16snorm => {
+ let scale = 32767;
+
+ write!(self.out, "(float2(int2(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " << 16, ")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, ") >> 16) / {scale}.0)")?;
+ }
+ Function::Unpack2x16unorm => {
+ let scale = 65535;
+
+ write!(self.out, "(float2(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " & 0xFFFF, ")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " >> 16) / {scale}.0)")?;
+ }
+ Function::Unpack4x8snorm => {
+ let scale = 127;
+
+ write!(self.out, "(float4(int4(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " << 24, ")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " << 16, ")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " << 8, ")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, ") >> 24) / {scale}.0)")?;
+ }
+ Function::Unpack4x8unorm => {
+ let scale = 255;
+
+ write!(self.out, "(float4(")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " & 0xFF, ")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " >> 8 & 0xFF, ")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " >> 16 & 0xFF, ")?;
+ self.write_expr(module, arg, func_ctx)?;
+ write!(self.out, " >> 24) / {scale}.0)")?;
+ }
Function::Regular(fun_name) => {
write!(self.out, "{fun_name}(")?;
self.write_expr(module, arg, func_ctx)?;
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -190,6 +190,17 @@ impl super::TypeInner {
}
}
+ pub const fn scalar_width(&self) -> Option<u8> {
+ // Multiply by 8 to get the bit width
+ match *self {
+ super::TypeInner::Scalar { width, .. } | super::TypeInner::Vector { width, .. } => {
+ Some(width * 8)
+ }
+ super::TypeInner::Matrix { width, .. } => Some(width * 8),
+ _ => None,
+ }
+ }
+
pub const fn pointer_space(&self) -> Option<crate::AddressSpace> {
match *self {
Self::Pointer { space, .. } => Some(space),
|
diff --git /dev/null b/tests/out/hlsl/bits.hlsl
new file mode 100644
--- /dev/null
+++ b/tests/out/hlsl/bits.hlsl
@@ -0,0 +1,131 @@
+
+[numthreads(1, 1, 1)]
+void main()
+{
+ int i = (int)0;
+ int2 i2_ = (int2)0;
+ int3 i3_ = (int3)0;
+ int4 i4_ = (int4)0;
+ uint u = (uint)0;
+ uint2 u2_ = (uint2)0;
+ uint3 u3_ = (uint3)0;
+ uint4 u4_ = (uint4)0;
+ float2 f2_ = (float2)0;
+ float4 f4_ = (float4)0;
+
+ i = 0;
+ i2_ = (0).xx;
+ i3_ = (0).xxx;
+ i4_ = (0).xxxx;
+ u = 0u;
+ u2_ = (0u).xx;
+ u3_ = (0u).xxx;
+ u4_ = (0u).xxxx;
+ f2_ = (0.0).xx;
+ f4_ = (0.0).xxxx;
+ float4 _expr28 = f4_;
+ u = uint((int(round(clamp(_expr28[0], -1.0, 1.0) * 127.0)) & 0xFF) | ((int(round(clamp(_expr28[1], -1.0, 1.0) * 127.0)) & 0xFF) << 8) | ((int(round(clamp(_expr28[2], -1.0, 1.0) * 127.0)) & 0xFF) << 16) | ((int(round(clamp(_expr28[3], -1.0, 1.0) * 127.0)) & 0xFF) << 24));
+ float4 _expr30 = f4_;
+ u = (uint(round(clamp(_expr30[0], 0.0, 1.0) * 255.0)) | uint(round(clamp(_expr30[1], 0.0, 1.0) * 255.0)) << 8 | uint(round(clamp(_expr30[2], 0.0, 1.0) * 255.0)) << 16 | uint(round(clamp(_expr30[3], 0.0, 1.0) * 255.0)) << 24);
+ float2 _expr32 = f2_;
+ u = uint((int(round(clamp(_expr32[0], -1.0, 1.0) * 32767.0)) & 0xFFFF) | ((int(round(clamp(_expr32[1], -1.0, 1.0) * 32767.0)) & 0xFFFF) << 16));
+ float2 _expr34 = f2_;
+ u = (uint(round(clamp(_expr34[0], 0.0, 1.0) * 65535.0)) | uint(round(clamp(_expr34[1], 0.0, 1.0) * 65535.0)) << 16);
+ float2 _expr36 = f2_;
+ u = (f32tof16(_expr36[0]) | f32tof16(_expr36[1]) << 16);
+ uint _expr38 = u;
+ f4_ = (float4(int4(_expr38 << 24, _expr38 << 16, _expr38 << 8, _expr38) >> 24) / 127.0);
+ uint _expr40 = u;
+ f4_ = (float4(_expr40 & 0xFF, _expr40 >> 8 & 0xFF, _expr40 >> 16 & 0xFF, _expr40 >> 24) / 255.0);
+ uint _expr42 = u;
+ f2_ = (float2(int2(_expr42 << 16, _expr42) >> 16) / 32767.0);
+ uint _expr44 = u;
+ f2_ = (float2(_expr44 & 0xFFFF, _expr44 >> 16) / 65535.0);
+ uint _expr46 = u;
+ f2_ = float2(f16tof32(_expr46), f16tof32((_expr46) >> 16));
+ int _expr48 = i;
+ int _expr49 = i;
+ i = (10u == 0 ? _expr48 : (_expr48 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr49 << 5u) & ((4294967295u >> (32u - 10u)) << 5u)));
+ int2 _expr53 = i2_;
+ int2 _expr54 = i2_;
+ i2_ = (10u == 0 ? _expr53 : (_expr53 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr54 << 5u) & ((4294967295u >> (32u - 10u)) << 5u)));
+ int3 _expr58 = i3_;
+ int3 _expr59 = i3_;
+ i3_ = (10u == 0 ? _expr58 : (_expr58 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr59 << 5u) & ((4294967295u >> (32u - 10u)) << 5u)));
+ int4 _expr63 = i4_;
+ int4 _expr64 = i4_;
+ i4_ = (10u == 0 ? _expr63 : (_expr63 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr64 << 5u) & ((4294967295u >> (32u - 10u)) << 5u)));
+ uint _expr68 = u;
+ uint _expr69 = u;
+ u = (10u == 0 ? _expr68 : (_expr68 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr69 << 5u) & ((4294967295u >> (32u - 10u)) << 5u)));
+ uint2 _expr73 = u2_;
+ uint2 _expr74 = u2_;
+ u2_ = (10u == 0 ? _expr73 : (_expr73 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr74 << 5u) & ((4294967295u >> (32u - 10u)) << 5u)));
+ uint3 _expr78 = u3_;
+ uint3 _expr79 = u3_;
+ u3_ = (10u == 0 ? _expr78 : (_expr78 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr79 << 5u) & ((4294967295u >> (32u - 10u)) << 5u)));
+ uint4 _expr83 = u4_;
+ uint4 _expr84 = u4_;
+ u4_ = (10u == 0 ? _expr83 : (_expr83 & ~((4294967295u >> (32u - 10u)) << 5u)) | ((_expr84 << 5u) & ((4294967295u >> (32u - 10u)) << 5u)));
+ int _expr88 = i;
+ i = (10u == 0 ? 0 : (_expr88 << (32 - 10u - 5u)) >> (32 - 10u));
+ int2 _expr92 = i2_;
+ i2_ = (10u == 0 ? 0 : (_expr92 << (32 - 10u - 5u)) >> (32 - 10u));
+ int3 _expr96 = i3_;
+ i3_ = (10u == 0 ? 0 : (_expr96 << (32 - 10u - 5u)) >> (32 - 10u));
+ int4 _expr100 = i4_;
+ i4_ = (10u == 0 ? 0 : (_expr100 << (32 - 10u - 5u)) >> (32 - 10u));
+ uint _expr104 = u;
+ u = (10u == 0 ? 0 : (_expr104 << (32 - 10u - 5u)) >> (32 - 10u));
+ uint2 _expr108 = u2_;
+ u2_ = (10u == 0 ? 0 : (_expr108 << (32 - 10u - 5u)) >> (32 - 10u));
+ uint3 _expr112 = u3_;
+ u3_ = (10u == 0 ? 0 : (_expr112 << (32 - 10u - 5u)) >> (32 - 10u));
+ uint4 _expr116 = u4_;
+ u4_ = (10u == 0 ? 0 : (_expr116 << (32 - 10u - 5u)) >> (32 - 10u));
+ int _expr120 = i;
+ i = asint(firstbitlow(_expr120));
+ uint2 _expr122 = u2_;
+ u2_ = firstbitlow(_expr122);
+ int3 _expr124 = i3_;
+ i3_ = asint(firstbithigh(_expr124));
+ uint3 _expr126 = u3_;
+ u3_ = firstbithigh(_expr126);
+ int _expr128 = i;
+ i = asint(firstbithigh(_expr128));
+ uint _expr130 = u;
+ u = firstbithigh(_expr130);
+ int _expr132 = i;
+ i = asint(countbits(asuint(_expr132)));
+ int2 _expr134 = i2_;
+ i2_ = asint(countbits(asuint(_expr134)));
+ int3 _expr136 = i3_;
+ i3_ = asint(countbits(asuint(_expr136)));
+ int4 _expr138 = i4_;
+ i4_ = asint(countbits(asuint(_expr138)));
+ uint _expr140 = u;
+ u = countbits(_expr140);
+ uint2 _expr142 = u2_;
+ u2_ = countbits(_expr142);
+ uint3 _expr144 = u3_;
+ u3_ = countbits(_expr144);
+ uint4 _expr146 = u4_;
+ u4_ = countbits(_expr146);
+ int _expr148 = i;
+ i = asint(reversebits(asuint(_expr148)));
+ int2 _expr150 = i2_;
+ i2_ = asint(reversebits(asuint(_expr150)));
+ int3 _expr152 = i3_;
+ i3_ = asint(reversebits(asuint(_expr152)));
+ int4 _expr154 = i4_;
+ i4_ = asint(reversebits(asuint(_expr154)));
+ uint _expr156 = u;
+ u = reversebits(_expr156);
+ uint2 _expr158 = u2_;
+ u2_ = reversebits(_expr158);
+ uint3 _expr160 = u3_;
+ u3_ = reversebits(_expr160);
+ uint4 _expr162 = u4_;
+ u4_ = reversebits(_expr162);
+ return;
+}
diff --git /dev/null b/tests/out/hlsl/bits.hlsl.config
new file mode 100644
--- /dev/null
+++ b/tests/out/hlsl/bits.hlsl.config
@@ -0,0 +1,3 @@
+vertex=()
+fragment=()
+compute=(main:cs_5_1 )
diff --git /dev/null b/tests/out/hlsl/bits.ron
new file mode 100644
--- /dev/null
+++ b/tests/out/hlsl/bits.ron
@@ -0,0 +1,12 @@
+(
+ vertex:[
+ ],
+ fragment:[
+ ],
+ compute:[
+ (
+ entry_point:"main",
+ target_profile:"cs_5_1",
+ ),
+ ],
+)
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -420,7 +420,7 @@ fn convert_wgsl() {
),
(
"bits",
- Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::WGSL,
+ Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL,
),
(
"bitcast",
|
Missing extractBits and insertBits implementations for HLSL
Seems they were implemented for other backends in #1449 but not for HLSL.
|
I think all the other functions from that PR are missing too:
- pack4x8snorm
- pack4x8unorm
- pack2x16snorm
- pack2x16unorm
- pack2x16float
- unpack4x8snorm
- unpack4x8unorm
- unpack2x16snorm
- unpack2x16unorm
- unpack2x16float
|
2023-05-25T12:07:20Z
|
0.12
|
2023-06-23T13:52:23Z
|
04ef22f6dc8d9c4b958dc6575bbb3be9d7719ee0
|
[
"convert_wgsl"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::layout::test_logical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::nan_handling",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::swizzles",
"front::spv::test::parse",
"front::wgsl::parse::lexer::test_tokens",
"front::wgsl::parse::lexer::test_variable_decl",
"front::wgsl::parse::lexer::test_numbers",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_alias",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::tests::parse_parentheses_switch",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_postfix",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_switch_default_in_case",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"front::wgsl::tests::parse_struct_instantiation",
"proc::namer::test",
"proc::test_matrix_size",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_switch",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_texture_store",
"span::span_location",
"front::wgsl::tests::parse_type_inference",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_load",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"geometry",
"cube_array",
"sampler1d",
"storage1d",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"bad_for_initializer",
"assign_to_expr",
"bad_texture_sample_type",
"binding_array_non_struct",
"binary_statement",
"binding_array_private",
"binding_array_local",
"bad_type_cast",
"bad_texture",
"function_without_identifier",
"break_if_bad_condition",
"cyclic_function",
"function_param_redefinition_as_local",
"function_param_redefinition_as_param",
"constructor_parameter_type_mismatch",
"inconsistent_binding",
"assign_to_let",
"discard_in_wrong_stage",
"function_returns_void",
"dead_code",
"invalid_integer",
"invalid_texture_sample_type",
"invalid_local_vars",
"invalid_arrays",
"invalid_functions",
"invalid_access",
"local_var_missing_type",
"invalid_float",
"invalid_structs",
"invalid_runtime_sized_arrays",
"matrix_with_bad_type",
"misplaced_break_if",
"missing_default_case",
"let_type_mismatch",
"reserved_identifier_prefix",
"host_shareable_types",
"negative_index",
"missing_bindings2",
"recursive_function",
"pointer_type_equivalence",
"struct_member_align_too_low",
"type_not_constructible",
"struct_member_non_po2_align",
"missing_bindings",
"struct_member_size_too_low",
"module_scope_identifier_redefinition",
"postfix_pointers",
"switch_signed_unsigned_mismatch",
"swizzle_assignment",
"reserved_keyword",
"unknown_access",
"unknown_attribute",
"unknown_conservative_depth",
"unknown_built_in",
"unknown_scalar_type",
"unknown_ident",
"unknown_storage_class",
"unknown_storage_format",
"type_not_inferrable",
"unknown_local_function",
"unexpected_constructor_parameters",
"unknown_type",
"unknown_identifier",
"select",
"var_type_mismatch",
"wrong_access_mode",
"valid_access",
"io_shareable_types",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 673)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 694)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/mod.rs - front::SymbolTable (line 211)",
"src/front/glsl/mod.rs - front::glsl::Frontend (line 142)"
] |
[] |
[] |
gfx-rs/naga
| 2,342
|
gfx-rs__naga-2342
|
[
"2312"
] |
423a069dcddc790fdf27d8c389fa4487f07fcc0a
|
diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs
--- a/src/front/wgsl/parse/mod.rs
+++ b/src/front/wgsl/parse/mod.rs
@@ -84,6 +84,18 @@ impl<'a> ExpressionContext<'a, '_, '_> {
}
Ok(accumulator)
}
+
+ fn declare_local(&mut self, name: ast::Ident<'a>) -> Result<Handle<ast::Local>, Error<'a>> {
+ let handle = self.locals.append(ast::Local, name.span);
+ if let Some(old) = self.local_table.add(name.name, handle) {
+ Err(Error::Redefinition {
+ previous: self.locals.get_span(old),
+ current: name.span,
+ })
+ } else {
+ Ok(handle)
+ }
+ }
}
/// Which grammar rule we are in the midst of parsing.
diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs
--- a/src/front/wgsl/parse/mod.rs
+++ b/src/front/wgsl/parse/mod.rs
@@ -1612,14 +1624,7 @@ impl Parser {
let expr_id = self.general_expression(lexer, ctx.reborrow())?;
lexer.expect(Token::Separator(';'))?;
- let handle = ctx.locals.append(ast::Local, name.span);
- if let Some(old) = ctx.local_table.add(name.name, handle) {
- return Err(Error::Redefinition {
- previous: ctx.locals.get_span(old),
- current: name.span,
- });
- }
-
+ let handle = ctx.declare_local(name)?;
ast::StatementKind::LocalDecl(ast::LocalDecl::Let(ast::Let {
name,
ty: given_ty,
diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs
--- a/src/front/wgsl/parse/mod.rs
+++ b/src/front/wgsl/parse/mod.rs
@@ -1647,14 +1652,7 @@ impl Parser {
lexer.expect(Token::Separator(';'))?;
- let handle = ctx.locals.append(ast::Local, name.span);
- if let Some(old) = ctx.local_table.add(name.name, handle) {
- return Err(Error::Redefinition {
- previous: ctx.locals.get_span(old),
- current: name.span,
- });
- }
-
+ let handle = ctx.declare_local(name)?;
ast::StatementKind::LocalDecl(ast::LocalDecl::Var(ast::LocalVariable {
name,
ty,
diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs
--- a/src/front/wgsl/parse/mod.rs
+++ b/src/front/wgsl/parse/mod.rs
@@ -2013,15 +2011,15 @@ impl Parser {
ctx.local_table.push_scope();
lexer.expect(Token::Paren('{'))?;
- let mut statements = ast::Block::default();
+ let mut block = ast::Block::default();
while !lexer.skip(Token::Paren('}')) {
- self.statement(lexer, ctx.reborrow(), &mut statements)?;
+ self.statement(lexer, ctx.reborrow(), &mut block)?;
}
ctx.local_table.pop_scope();
let span = self.pop_rule_span(lexer);
- Ok((statements, span))
+ Ok((block, span))
}
fn varying_binding<'a>(
diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs
--- a/src/front/wgsl/parse/mod.rs
+++ b/src/front/wgsl/parse/mod.rs
@@ -2060,6 +2058,9 @@ impl Parser {
unresolved: dependencies,
};
+ // start a scope that contains arguments as well as the function body
+ ctx.local_table.push_scope();
+
// read parameter list
let mut arguments = Vec::new();
lexer.expect(Token::Paren('('))?;
diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs
--- a/src/front/wgsl/parse/mod.rs
+++ b/src/front/wgsl/parse/mod.rs
@@ -2078,8 +2079,7 @@ impl Parser {
lexer.expect(Token::Separator(':'))?;
let param_type = self.type_decl(lexer, ctx.reborrow())?;
- let handle = ctx.locals.append(ast::Local, param_name.span);
- ctx.local_table.add(param_name.name, handle);
+ let handle = ctx.declare_local(param_name)?;
arguments.push(ast::FunctionArgument {
name: param_name,
ty: param_type,
diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs
--- a/src/front/wgsl/parse/mod.rs
+++ b/src/front/wgsl/parse/mod.rs
@@ -2097,8 +2097,14 @@ impl Parser {
None
};
- // read body
- let body = self.block(lexer, ctx)?.0;
+ // do not use `self.block` here, since we must not push a new scope
+ lexer.expect(Token::Paren('{'))?;
+ let mut body = ast::Block::default();
+ while !lexer.skip(Token::Paren('}')) {
+ self.statement(lexer, ctx.reborrow(), &mut body)?;
+ }
+
+ ctx.local_table.pop_scope();
let fun = ast::Function {
entry_point: None,
|
diff --git a/tests/in/lexical-scopes.wgsl b/tests/in/lexical-scopes.wgsl
--- a/tests/in/lexical-scopes.wgsl
+++ b/tests/in/lexical-scopes.wgsl
@@ -1,45 +1,41 @@
fn blockLexicalScope(a: bool) {
- let a = 1.0;
{
let a = 2;
{
- let a = true;
+ let a = 2.0;
}
- let test = a == 3;
+ let test: i32 = a;
}
- let test = a == 2.0;
+ let test: bool = a;
}
fn ifLexicalScope(a: bool) {
- let a = 1.0;
- if (a == 1.0) {
- let a = true;
+ if (a) {
+ let a = 2.0;
}
- let test = a == 2.0;
+ let test: bool = a;
}
fn loopLexicalScope(a: bool) {
- let a = 1.0;
loop {
- let a = true;
+ let a = 2.0;
}
- let test = a == 2.0;
+ let test: bool = a;
}
fn forLexicalScope(a: f32) {
- let a = false;
for (var a = 0; a < 1; a++) {
- let a = 3.0;
+ let a = true;
}
- let test = a == true;
+ let test: f32 = a;
}
fn whileLexicalScope(a: i32) {
while (a > 2) {
let a = false;
}
- let test = a == 1;
+ let test: i32 = a;
}
fn switchLexicalScope(a: i32) {
diff --git a/tests/out/wgsl/lexical-scopes.wgsl b/tests/out/wgsl/lexical-scopes.wgsl
--- a/tests/out/wgsl/lexical-scopes.wgsl
+++ b/tests/out/wgsl/lexical-scopes.wgsl
@@ -1,22 +1,23 @@
fn blockLexicalScope(a: bool) {
{
{
+ return;
}
- let test = (2 == 3);
}
- let test_1 = (1.0 == 2.0);
}
fn ifLexicalScope(a_1: bool) {
- if (1.0 == 1.0) {
+ if a_1 {
+ return;
+ } else {
+ return;
}
- let test_2 = (1.0 == 2.0);
}
fn loopLexicalScope(a_2: bool) {
loop {
}
- let test_3 = (1.0 == 2.0);
+ return;
}
fn forLexicalScope(a_3: f32) {
diff --git a/tests/out/wgsl/lexical-scopes.wgsl b/tests/out/wgsl/lexical-scopes.wgsl
--- a/tests/out/wgsl/lexical-scopes.wgsl
+++ b/tests/out/wgsl/lexical-scopes.wgsl
@@ -24,19 +25,19 @@ fn forLexicalScope(a_3: f32) {
a_4 = 0;
loop {
- let _e4 = a_4;
- if (_e4 < 1) {
+ let _e3 = a_4;
+ if (_e3 < 1) {
} else {
break;
}
{
}
continuing {
- let _e8 = a_4;
- a_4 = (_e8 + 1);
+ let _e7 = a_4;
+ a_4 = (_e7 + 1);
}
}
- let test_4 = (false == true);
+ return;
}
fn whileLexicalScope(a_5: i32) {
diff --git a/tests/out/wgsl/lexical-scopes.wgsl b/tests/out/wgsl/lexical-scopes.wgsl
--- a/tests/out/wgsl/lexical-scopes.wgsl
+++ b/tests/out/wgsl/lexical-scopes.wgsl
@@ -48,7 +49,7 @@ fn whileLexicalScope(a_5: i32) {
{
}
}
- let test_5 = (a_5 == 1);
+ return;
}
fn switchLexicalScope(a_6: i32) {
diff --git a/tests/out/wgsl/lexical-scopes.wgsl b/tests/out/wgsl/lexical-scopes.wgsl
--- a/tests/out/wgsl/lexical-scopes.wgsl
+++ b/tests/out/wgsl/lexical-scopes.wgsl
@@ -60,6 +61,6 @@ fn switchLexicalScope(a_6: i32) {
default: {
}
}
- let test_6 = (a_6 == 2);
+ let test = (a_6 == 2);
}
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -1883,6 +1883,44 @@ fn function_returns_void() {
)
}
+#[test]
+fn function_param_redefinition_as_param() {
+ check(
+ "
+ fn x(a: f32, a: vec2<f32>) {}
+ ",
+ r###"error: redefinition of `a`
+ ┌─ wgsl:2:14
+ │
+2 │ fn x(a: f32, a: vec2<f32>) {}
+ │ ^ ^ redefinition of `a`
+ │ │
+ │ previous definition of `a`
+
+"###,
+ )
+}
+
+#[test]
+fn function_param_redefinition_as_local() {
+ check(
+ "
+ fn x(a: f32) {
+ let a = 0.0;
+ }
+ ",
+ r###"error: redefinition of `a`
+ ┌─ wgsl:2:14
+ │
+2 │ fn x(a: f32) {
+ │ ^ previous definition of `a`
+3 │ let a = 0.0;
+ │ ^ redefinition of `a`
+
+"###,
+ )
+}
+
#[test]
fn binding_array_local() {
check_validation! {
|
[wgsl-in] Redefining parameter is incorreclty allowed
The following snippet redefines an incoming parameter which should not compile (and Tint will complain about it!):
```
fn fun(t: f32) -> f32 {
let t = t + 1.0;
return t;
}
```
|
2023-05-15T23:41:22Z
|
0.12
|
2023-05-30T11:55:39Z
|
04ef22f6dc8d9c4b958dc6575bbb3be9d7719ee0
|
[
"function_param_redefinition_as_local",
"function_param_redefinition_as_param"
] |
[
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::layout::test_logical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::nan_handling",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::expressions",
"front::spv::test::parse",
"back::msl::writer::test_stack_size",
"front::wgsl::parse::lexer::test_tokens",
"front::wgsl::parse::lexer::test_numbers",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::function_overloading",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::parse::lexer::test_variable_decl",
"front::wgsl::tests::parse_alias",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_parentheses_switch",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_switch_default_in_case",
"front::wgsl::tests::parse_postfix",
"proc::namer::test",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"proc::typifier::test_error_size",
"span::span_location",
"proc::test_matrix_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_types",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_type_cast",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"convert_wgsl",
"storage1d",
"cube_array",
"sampler1d",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"bad_for_initializer",
"assign_to_expr",
"binary_statement",
"bad_texture_sample_type",
"binding_array_local",
"binding_array_non_struct",
"binding_array_private",
"bad_type_cast",
"bad_texture",
"break_if_bad_condition",
"function_without_identifier",
"cyclic_function",
"constructor_parameter_type_mismatch",
"inconsistent_binding",
"dead_code",
"assign_to_let",
"function_returns_void",
"invalid_texture_sample_type",
"invalid_integer",
"invalid_float",
"invalid_structs",
"invalid_access",
"invalid_runtime_sized_arrays",
"discard_in_wrong_stage",
"invalid_local_vars",
"invalid_arrays",
"misplaced_break_if",
"let_type_mismatch",
"matrix_with_bad_type",
"local_var_missing_type",
"reserved_identifier_prefix",
"missing_default_case",
"missing_bindings2",
"recursive_function",
"negative_index",
"invalid_functions",
"struct_member_align_too_low",
"struct_member_size_too_low",
"struct_member_non_po2_align",
"postfix_pointers",
"missing_bindings",
"module_scope_identifier_redefinition",
"switch_signed_unsigned_mismatch",
"type_not_inferrable",
"unexpected_constructor_parameters",
"pointer_type_equivalence",
"reserved_keyword",
"unknown_access",
"unknown_attribute",
"unknown_built_in",
"unknown_conservative_depth",
"type_not_constructible",
"unknown_scalar_type",
"unknown_local_function",
"unknown_storage_format",
"unknown_storage_class",
"swizzle_assignment",
"unknown_type",
"host_shareable_types",
"var_type_mismatch",
"select",
"unknown_identifier",
"unknown_ident",
"wrong_access_mode",
"valid_access",
"io_shareable_types",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 693)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 672)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/mod.rs - front::SymbolTable (line 211)",
"src/front/glsl/mod.rs - front::glsl::Frontend (line 142)"
] |
[] |
[] |
|
gfx-rs/naga
| 2,233
|
gfx-rs__naga-2233
|
[
"2169"
] |
6be394dac31bc9796d4ae4bb450a40c6b6ee0b08
|
diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs
--- a/src/front/wgsl/error.rs
+++ b/src/front/wgsl/error.rs
@@ -134,7 +134,7 @@ pub enum NumberError {
pub enum InvalidAssignmentType {
Other,
Swizzle,
- ImmutableBinding,
+ ImmutableBinding(Span),
}
#[derive(Clone, Debug)]
diff --git a/src/front/wgsl/error.rs b/src/front/wgsl/error.rs
--- a/src/front/wgsl/error.rs
+++ b/src/front/wgsl/error.rs
@@ -536,21 +536,33 @@ impl<'a> Error<'a> {
labels: vec![(span, "expression is not a reference".into())],
notes: vec![],
},
- Error::InvalidAssignment { span, ty } => ParseError {
- message: "invalid left-hand side of assignment".into(),
- labels: vec![(span, "cannot assign to this expression".into())],
- notes: match ty {
- InvalidAssignmentType::Swizzle => vec![
- "WGSL does not support assignments to swizzles".into(),
- "consider assigning each component individually".into(),
- ],
- InvalidAssignmentType::ImmutableBinding => vec![
- format!("'{}' is an immutable binding", &source[span]),
- "consider declaring it with `var` instead of `let`".into(),
- ],
- InvalidAssignmentType::Other => vec![],
- },
- },
+ Error::InvalidAssignment { span, ty } => {
+ let (extra_label, notes) = match ty {
+ InvalidAssignmentType::Swizzle => (
+ None,
+ vec![
+ "WGSL does not support assignments to swizzles".into(),
+ "consider assigning each component individually".into(),
+ ],
+ ),
+ InvalidAssignmentType::ImmutableBinding(binding_span) => (
+ Some((binding_span, "this is an immutable binding".into())),
+ vec![format!(
+ "consider declaring '{}' with `var` instead of `let`",
+ &source[binding_span]
+ )],
+ ),
+ InvalidAssignmentType::Other => (None, vec![]),
+ };
+
+ ParseError {
+ message: "invalid left-hand side of assignment".into(),
+ labels: std::iter::once((span, "cannot assign to this expression".into()))
+ .chain(extra_label)
+ .collect(),
+ notes,
+ }
+ }
Error::Pointer(what, span) => ParseError {
message: format!("{what} must not be a pointer"),
labels: vec![(span, "expression is a pointer".into())],
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -5,6 +5,7 @@ use crate::front::wgsl::parse::{ast, conv};
use crate::front::{Emitter, Typifier};
use crate::proc::{ensure_block_returns, Alignment, Layouter, ResolveContext, TypeResolution};
use crate::{Arena, FastHashMap, Handle, Span};
+use indexmap::IndexMap;
mod construction;
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -74,7 +75,9 @@ pub struct StatementContext<'source, 'temp, 'out> {
typifier: &'temp mut Typifier,
variables: &'out mut Arena<crate::LocalVariable>,
naga_expressions: &'out mut Arena<crate::Expression>,
- named_expressions: &'out mut crate::NamedExpressions,
+ /// Stores the names of expressions that are assigned in `let` statement
+ /// Also stores the spans of the names, for use in errors.
+ named_expressions: &'out mut IndexMap<Handle<crate::Expression>, (String, Span)>,
arguments: &'out [crate::FunctionArgument],
module: &'out mut crate::Module,
}
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -126,6 +129,19 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> {
module: self.module,
}
}
+
+ fn invalid_assignment_type(&self, expr: Handle<crate::Expression>) -> InvalidAssignmentType {
+ if let Some(&(_, span)) = self.named_expressions.get(&expr) {
+ InvalidAssignmentType::ImmutableBinding(span)
+ } else {
+ match self.naga_expressions[expr] {
+ crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle,
+ crate::Expression::Access { base, .. } => self.invalid_assignment_type(base),
+ crate::Expression::AccessIndex { base, .. } => self.invalid_assignment_type(base),
+ _ => InvalidAssignmentType::Other,
+ }
+ }
+ }
}
/// State for lowering an `ast::Expression` to Naga IR.
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -352,10 +368,10 @@ impl<'a> ExpressionContext<'a, '_, '_> {
}
crate::TypeInner::Vector { size, kind, width } => {
let scalar_ty = self.ensure_type_exists(crate::TypeInner::Scalar { width, kind });
- let component = self.create_zero_value_constant(scalar_ty);
+ let component = self.create_zero_value_constant(scalar_ty)?;
crate::ConstantInner::Composite {
ty,
- components: (0..size as u8).map(|_| component).collect::<Option<_>>()?,
+ components: (0..size as u8).map(|_| component).collect(),
}
}
crate::TypeInner::Matrix {
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -368,12 +384,10 @@ impl<'a> ExpressionContext<'a, '_, '_> {
kind: crate::ScalarKind::Float,
size: rows,
});
- let component = self.create_zero_value_constant(vec_ty);
+ let component = self.create_zero_value_constant(vec_ty)?;
crate::ConstantInner::Composite {
ty,
- components: (0..columns as u8)
- .map(|_| component)
- .collect::<Option<_>>()?,
+ components: (0..columns as u8).map(|_| component).collect(),
}
}
crate::TypeInner::Array {
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -381,12 +395,11 @@ impl<'a> ExpressionContext<'a, '_, '_> {
size: crate::ArraySize::Constant(size),
..
} => {
- let component = self.create_zero_value_constant(base);
+ let size = self.module.constants[size].to_array_length()?;
+ let component = self.create_zero_value_constant(base)?;
crate::ConstantInner::Composite {
ty,
- components: (0..self.module.constants[size].to_array_length().unwrap())
- .map(|_| component)
- .collect::<Option<_>>()?,
+ components: (0..size).map(|_| component).collect(),
}
}
crate::TypeInner::Struct { ref members, .. } => {
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -740,7 +753,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
let mut local_table = FastHashMap::default();
let mut local_variables = Arena::new();
let mut expressions = Arena::new();
- let mut named_expressions = crate::NamedExpressions::default();
+ let mut named_expressions = IndexMap::default();
let arguments = f
.arguments
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -751,7 +764,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
let expr = expressions
.append(crate::Expression::FunctionArgument(i as u32), arg.name.span);
local_table.insert(arg.handle, TypedExpression::non_reference(expr));
- named_expressions.insert(expr, arg.name.name.to_string());
+ named_expressions.insert(expr, (arg.name.name.to_string(), arg.name.span));
Ok(crate::FunctionArgument {
name: Some(arg.name.name.to_string()),
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -797,7 +810,10 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
result,
local_variables,
expressions,
- named_expressions,
+ named_expressions: named_expressions
+ .into_iter()
+ .map(|(key, (name, _))| (key, name))
+ .collect(),
body,
};
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -870,7 +886,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
block.extend(emitter.finish(ctx.naga_expressions));
ctx.local_table
.insert(l.handle, TypedExpression::non_reference(value));
- ctx.named_expressions.insert(value, l.name.name.to_string());
+ ctx.named_expressions
+ .insert(value, (l.name.name.to_string(), l.name.span));
return Ok(());
}
diff --git a/src/front/wgsl/lower/mod.rs b/src/front/wgsl/lower/mod.rs
--- a/src/front/wgsl/lower/mod.rs
+++ b/src/front/wgsl/lower/mod.rs
@@ -1071,14 +1088,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
let mut value = self.expression(value, ctx.as_expression(block, &mut emitter))?;
if !expr.is_reference {
- let ty = if ctx.named_expressions.contains_key(&expr.handle) {
- InvalidAssignmentType::ImmutableBinding
- } else {
- match ctx.naga_expressions[expr.handle] {
- crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle,
- _ => InvalidAssignmentType::Other,
- }
- };
+ let ty = ctx.invalid_assignment_type(expr.handle);
return Err(Error::InvalidAssignment {
span: ctx.ast_expressions.get_span(target),
diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs
--- a/src/front/wgsl/parse/mod.rs
+++ b/src/front/wgsl/parse/mod.rs
@@ -1661,14 +1661,17 @@ impl Parser {
let span = span.until(&peeked_span);
return Err(Error::InvalidBreakIf(span));
}
+ lexer.expect(Token::Separator(';'))?;
ast::StatementKind::Break
}
"continue" => {
let _ = lexer.next();
+ lexer.expect(Token::Separator(';'))?;
ast::StatementKind::Continue
}
"discard" => {
let _ = lexer.next();
+ lexer.expect(Token::Separator(';'))?;
ast::StatementKind::Kill
}
// assignment or a function call
diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs
--- a/src/front/wgsl/parse/mod.rs
+++ b/src/front/wgsl/parse/mod.rs
@@ -1685,6 +1688,7 @@ impl Parser {
}
_ => {
self.assignment_statement(lexer, ctx.reborrow(), block)?;
+ lexer.expect(Token::Separator(';'))?;
self.pop_rule_span(lexer);
}
}
diff --git a/src/front/wgsl/parse/mod.rs b/src/front/wgsl/parse/mod.rs
--- a/src/front/wgsl/parse/mod.rs
+++ b/src/front/wgsl/parse/mod.rs
@@ -1776,7 +1780,7 @@ impl Parser {
ctx.local_table.push_scope();
- let _ = lexer.next();
+ lexer.expect(Token::Paren('{'))?;
let mut statements = ast::Block::default();
while !lexer.skip(Token::Paren('}')) {
self.statement(lexer, ctx.reborrow(), &mut statements)?;
|
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -1624,13 +1624,56 @@ fn assign_to_let() {
}
",
r###"error: invalid left-hand side of assignment
- ┌─ wgsl:4:10
+ ┌─ wgsl:3:17
│
+3 │ let a = 10;
+ │ ^ this is an immutable binding
4 │ a = 20;
│ ^ cannot assign to this expression
│
- = note: 'a' is an immutable binding
- = note: consider declaring it with `var` instead of `let`
+ = note: consider declaring 'a' with `var` instead of `let`
+
+"###,
+ );
+
+ check(
+ "
+ fn f() {
+ let a = array(1, 2);
+ a[0] = 1;
+ }
+ ",
+ r###"error: invalid left-hand side of assignment
+ ┌─ wgsl:3:17
+ │
+3 │ let a = array(1, 2);
+ │ ^ this is an immutable binding
+4 │ a[0] = 1;
+ │ ^^^^ cannot assign to this expression
+ │
+ = note: consider declaring 'a' with `var` instead of `let`
+
+"###,
+ );
+
+ check(
+ "
+ struct S { a: i32 }
+
+ fn f() {
+ let a = S(10);
+ a.a = 20;
+ }
+ ",
+ r###"error: invalid left-hand side of assignment
+ ┌─ wgsl:5:17
+ │
+5 │ let a = S(10);
+ │ ^ this is an immutable binding
+6 │ a.a = 20;
+ │ ^^^ cannot assign to this expression
+ │
+ = note: consider declaring 'a' with `var` instead of `let`
"###,
);
|
[wgsl-in] Invalid assignment diagnostic doesn't extend to derived expressions
Given this code:
```rs
fn main() {
let a = 1;
a = 2;
}
```
Naga errors with:
```rs
error: invalid left-hand side of assignment
┌─ wgsl:3:2
│
3 │ a = 2;
│ ^ cannot assign to this expression
│
= note: 'a' is an immutable binding
= note: consider declaring it with `var` instead of `let`
```
This lets us know exactly the issue and how to fix it. However, when given:
```rs
fn main() {
let a = array(1, 2);
a[0] = 2;
}
```
We error with:
```rs
error: invalid left-hand side of assignment
┌─ wgsl:3:2
│
3 │ a[0] = 2;
│ ^^^^ cannot assign to this expression
```
The error is the same as the above, however, we do not catch the fact that `a[0]` is derived from a `let`, and thus, don't tell the user how to fix it.
When validating assignments, we should recursively check if any of the arguments to a specific instruction is present in `ctx.named_expressions`.
|
2023-02-01T00:50:40Z
|
0.11
|
2023-02-01T11:38:30Z
|
da8e911d9d207a7571241e875f7ac066856e8b3f
|
[
"assign_to_let"
] |
[
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::nan_handling",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::version",
"front::spv::test::parse",
"front::wgsl::parse::lexer::test_tokens",
"front::glsl::parser_tests::structs",
"front::wgsl::parse::lexer::test_variable_decl",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::declarations",
"front::glsl::parser_tests::control_flow",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::tests::parse_parentheses_switch",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_statement",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_expressions",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_switch_default_in_case",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_struct_instantiation",
"proc::namer::test",
"proc::test_matrix_size",
"proc::typifier::test_error_size",
"span::span_location",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::parse::lexer::test_numbers",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"convert_wgsl",
"cube_array",
"sampler1d",
"geometry",
"storage1d",
"sample_rate_shading",
"storage_image_formats",
"image_queries",
"bad_for_initializer",
"assign_to_expr",
"bad_texture_sample_type",
"binary_statement",
"bad_type_cast",
"break_if_bad_condition",
"function_without_identifier",
"inconsistent_binding",
"bad_texture",
"cyclic_function",
"invalid_float",
"function_returns_void",
"constructor_parameter_type_mismatch",
"dead_code",
"invalid_integer",
"invalid_texture_sample_type",
"invalid_arrays",
"local_var_missing_type",
"invalid_runtime_sized_arrays",
"invalid_local_vars",
"invalid_access",
"invalid_structs",
"let_type_mismatch",
"misplaced_break_if",
"matrix_with_bad_type",
"missing_default_case",
"negative_index",
"invalid_functions",
"recursive_function",
"pointer_type_equivalence",
"struct_member_align_too_low",
"struct_member_size_too_low",
"struct_member_non_po2_align",
"type_not_constructible",
"postfix_pointers",
"type_not_inferrable",
"swizzle_assignment",
"missing_bindings",
"switch_signed_unsigned_mismatch",
"module_scope_identifier_redefinition",
"unknown_access",
"unknown_attribute",
"unknown_conservative_depth",
"unexpected_constructor_parameters",
"unknown_built_in",
"unknown_scalar_type",
"unknown_identifier",
"unknown_local_function",
"unknown_storage_class",
"unknown_storage_format",
"unknown_type",
"unknown_ident",
"var_type_mismatch",
"host_shareable_types",
"select",
"wrong_access_mode",
"reserved_identifier_prefix",
"valid_access",
"reserved_keyword",
"io_shareable_types",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 585)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 564)",
"src/front/mod.rs - front::SymbolTable (line 210)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/glsl/mod.rs - front::glsl::Frontend (line 142)"
] |
[] |
[] |
|
gfx-rs/naga
| 2,056
|
gfx-rs__naga-2056
|
[
"2052"
] |
4f8db997b0b1e73fc1e2cac070485333a5b61925
|
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -273,7 +273,7 @@ impl<'a> Lexer<'a> {
if next.0 == expected {
Ok(next.1)
} else {
- Err(Error::Unexpected(next, ExpectedToken::Token(expected)))
+ Err(Error::Unexpected(next.1, ExpectedToken::Token(expected)))
}
}
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -288,7 +288,7 @@ impl<'a> Lexer<'a> {
Ok(())
} else {
Err(Error::Unexpected(
- next,
+ next.1,
ExpectedToken::Token(Token::Paren(expected)),
))
}
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -314,7 +314,7 @@ impl<'a> Lexer<'a> {
Err(Error::ReservedIdentifierPrefix(span))
}
(Token::Word(word), span) => Ok((word, span)),
- other => Err(Error::Unexpected(other, ExpectedToken::Identifier)),
+ other => Err(Error::Unexpected(other.1, ExpectedToken::Identifier)),
}
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -71,6 +71,8 @@ pub enum ExpectedToken<'a> {
Constant,
/// Expected: constant, parenthesized expression, identifier
PrimaryExpression,
+ /// Expected: assignment, increment/decrement expression
+ Assignment,
/// Expected: '}', identifier
FieldName,
/// Expected: attribute for a type
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -95,9 +97,16 @@ pub enum NumberError {
UnimplementedF16,
}
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub enum InvalidAssignmentType {
+ Other,
+ Swizzle,
+ ImmutableBinding,
+}
+
#[derive(Clone, Debug)]
pub enum Error<'a> {
- Unexpected(TokenSpan<'a>, ExpectedToken<'a>),
+ Unexpected(Span, ExpectedToken<'a>),
UnexpectedComponents(Span),
BadNumber(Span, NumberError),
/// A negative signed integer literal where both signed and unsigned,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -151,6 +160,10 @@ pub enum Error<'a> {
Pointer(&'static str, Span),
NotPointer(Span),
NotReference(&'static str, Span),
+ InvalidAssignment {
+ span: Span,
+ ty: InvalidAssignmentType,
+ },
ReservedKeyword(Span),
Redefinition {
previous: Span,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -162,7 +175,7 @@ pub enum Error<'a> {
impl<'a> Error<'a> {
fn as_parse_error(&self, source: &'a str) -> ParseError {
match *self {
- Error::Unexpected((_, ref unexpected_span), expected) => {
+ Error::Unexpected(ref unexpected_span, expected) => {
let expected_str = match expected {
ExpectedToken::Token(token) => {
match token {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -195,6 +208,7 @@ impl<'a> Error<'a> {
ExpectedToken::Integer => "unsigned/signed integer literal".to_string(),
ExpectedToken::Constant => "constant".to_string(),
ExpectedToken::PrimaryExpression => "expression".to_string(),
+ ExpectedToken::Assignment => "assignment or increment/decrement".to_string(),
ExpectedToken::FieldName => "field name or a closing curly bracket to signify the end of the struct".to_string(),
ExpectedToken::TypeAttribute => "type attribute".to_string(),
ExpectedToken::Statement => "statement".to_string(),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -439,6 +453,20 @@ impl<'a> Error<'a> {
labels: vec![(span.clone(), "expression is not a reference".into())],
notes: vec![],
},
+ Error::InvalidAssignment{ ref span, ty} => ParseError {
+ message: "invalid left-hand side of assignment".into(),
+ labels: vec![(span.clone(), "cannot assign to this expression".into())],
+ notes: match ty {
+ InvalidAssignmentType::Swizzle => vec![
+ "WGSL does not support assignments to swizzles".into(),
+ "consider assigning each component individually".into()
+ ],
+ InvalidAssignmentType::ImmutableBinding => vec![
+ format!("'{}' is an immutable binding", &source[span.clone()]), "consider declaring it with `var` instead of `let`".into()
+ ],
+ InvalidAssignmentType::Other => vec![],
+ },
+ },
Error::Pointer(what, ref span) => ParseError {
message: format!("{} must not be a pointer", what),
labels: vec![(span.clone(), "expression is a pointer".into())],
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1409,7 +1437,7 @@ impl Parser {
Token::Number(Ok(Number::U32(num))) if uint => Ok(num as i32),
Token::Number(Ok(Number::I32(num))) if !uint => Ok(num),
Token::Number(Err(e)) => Err(Error::BadNumber(token_span.1, e)),
- _ => Err(Error::Unexpected(token_span, ExpectedToken::Integer)),
+ _ => Err(Error::Unexpected(token_span.1, ExpectedToken::Integer)),
}
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1422,7 +1450,7 @@ impl Parser {
}
(Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)),
other => Err(Error::Unexpected(
- other,
+ other.1,
ExpectedToken::Number(NumberType::I32),
)),
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1439,7 +1467,7 @@ impl Parser {
(Token::Number(Ok(Number::U32(num))), _) => Ok(num),
(Token::Number(Err(e)), span) => Err(Error::BadNumber(span, e)),
other => Err(Error::Unexpected(
- other,
+ other.1,
ExpectedToken::Number(NumberType::I32),
)),
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2239,7 +2267,7 @@ impl Parser {
components,
}
}
- other => return Err(Error::Unexpected(other, ExpectedToken::Constant)),
+ other => return Err(Error::Unexpected(other.1, ExpectedToken::Constant)),
};
// Only set span if it's a named constant. Otherwise, the enclosing Expression should have
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2330,7 +2358,7 @@ impl Parser {
}
}
}
- other => return Err(Error::Unexpected(other, ExpectedToken::PrimaryExpression)),
+ other => return Err(Error::Unexpected(other.1, ExpectedToken::PrimaryExpression)),
};
Ok(expr)
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2831,7 +2859,7 @@ impl Parser {
while !lexer.skip(Token::Paren('}')) {
if !ready {
return Err(Error::Unexpected(
- lexer.next(),
+ lexer.next().1,
ExpectedToken::Token(Token::Separator(',')),
));
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2863,7 +2891,7 @@ impl Parser {
let (name, span) = match lexer.next() {
(Token::Word(word), span) => (word, span),
- other => return Err(Error::Unexpected(other, ExpectedToken::FieldName)),
+ other => return Err(Error::Unexpected(other.1, ExpectedToken::FieldName)),
};
if crate::keywords::wgsl::RESERVED.contains(&name) {
return Err(Error::ReservedKeyword(span));
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3276,7 +3304,7 @@ impl Parser {
if lexer.skip(Token::Attribute) {
let other = lexer.next();
- return Err(Error::Unexpected(other, ExpectedToken::TypeAttribute));
+ return Err(Error::Unexpected(other.1, ExpectedToken::TypeAttribute));
}
let (name, name_span) = lexer.next_ident_with_span()?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3300,23 +3328,42 @@ impl Parser {
fn parse_assignment_statement<'a, 'out>(
&mut self,
lexer: &mut Lexer<'a>,
- mut context: ExpressionContext<'a, '_, 'out>,
+ mut context: StatementContext<'a, '_, 'out>,
+ block: &mut crate::Block,
+ emitter: &mut super::Emitter,
) -> Result<(), Error<'a>> {
use crate::BinaryOperator as Bo;
let span_start = lexer.start_byte_offset();
- context.emitter.start(context.expressions);
- let reference = self.parse_unary_expression(lexer, context.reborrow())?;
+ emitter.start(context.expressions);
+ let (reference, lhs_span) = self
+ .parse_general_expression_for_reference(lexer, context.as_expression(block, emitter))?;
+ let op = lexer.next();
// The left hand side of an assignment must be a reference.
- let lhs_span = span_start..lexer.end_byte_offset();
- if !reference.is_reference {
- return Err(Error::NotReference(
- "the left-hand side of an assignment",
- lhs_span,
- ));
+ if !matches!(
+ op.0,
+ Token::Operation('=')
+ | Token::AssignmentOperation(_)
+ | Token::IncrementOperation
+ | Token::DecrementOperation
+ ) {
+ return Err(Error::Unexpected(lhs_span, ExpectedToken::Assignment));
+ } else if !reference.is_reference {
+ let ty = if context.named_expressions.contains_key(&reference.handle) {
+ InvalidAssignmentType::ImmutableBinding
+ } else {
+ match *context.expressions.get_mut(reference.handle) {
+ crate::Expression::Swizzle { .. } => InvalidAssignmentType::Swizzle,
+ _ => InvalidAssignmentType::Other,
+ }
+ };
+
+ return Err(Error::InvalidAssignment { span: lhs_span, ty });
}
- let value = match lexer.next() {
+ let mut context = context.as_expression(block, emitter);
+
+ let value = match op {
(Token::Operation('='), _) => {
self.parse_general_expression(lexer, context.reborrow())?
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3406,7 +3453,7 @@ impl Parser {
op_span.into(),
)
}
- other => return Err(Error::Unexpected(other, ExpectedToken::SwitchItem)),
+ other => return Err(Error::Unexpected(other.1, ExpectedToken::SwitchItem)),
};
let span_end = lexer.end_byte_offset();
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3843,7 +3890,10 @@ impl Parser {
}
(Token::Paren('}'), _) => break,
other => {
- return Err(Error::Unexpected(other, ExpectedToken::SwitchItem))
+ return Err(Error::Unexpected(
+ other.1,
+ ExpectedToken::SwitchItem,
+ ))
}
}
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3954,7 +4004,9 @@ impl Parser {
}
_ => self.parse_assignment_statement(
lexer,
- context.as_expression(&mut continuing, &mut emitter),
+ context.reborrow(),
+ &mut continuing,
+ &mut emitter,
)?,
}
lexer.expect(Token::Paren(')'))?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4059,7 +4111,9 @@ impl Parser {
match context.symbol_table.lookup(ident) {
Some(_) => self.parse_assignment_statement(
lexer,
- context.as_expression(block, &mut emitter),
+ context,
+ block,
+ &mut emitter,
)?,
None => self.parse_function_statement(
lexer,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4078,7 +4132,7 @@ impl Parser {
}
_ => {
let mut emitter = super::Emitter::default();
- self.parse_assignment_statement(lexer, context.as_expression(block, &mut emitter))?;
+ self.parse_assignment_statement(lexer, context, block, &mut emitter)?;
self.pop_rule_span(lexer);
}
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4262,7 +4316,7 @@ impl Parser {
while !lexer.skip(Token::Paren(')')) {
if !ready {
return Err(Error::Unexpected(
- lexer.next(),
+ lexer.next().1,
ExpectedToken::Token(Token::Separator(',')),
));
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4391,7 +4445,7 @@ impl Parser {
(Token::Separator(','), _) if i != 2 => (),
other => {
return Err(Error::Unexpected(
- other,
+ other.1,
ExpectedToken::WorkgroupSizeSeparator,
))
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4577,7 +4631,7 @@ impl Parser {
}
}
(Token::End, _) => return Ok(false),
- other => return Err(Error::Unexpected(other, ExpectedToken::GlobalItem)),
+ other => return Err(Error::Unexpected(other.1, ExpectedToken::GlobalItem)),
}
match binding {
|
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -1597,3 +1597,83 @@ fn break_if_bad_condition() {
)
}
}
+
+#[test]
+fn swizzle_assignment() {
+ check(
+ "
+ fn f() {
+ var v = vec2(0);
+ v.xy = vec2(1);
+ }
+ ",
+ r###"error: invalid left-hand side of assignment
+ ┌─ wgsl:4:13
+ │
+4 │ v.xy = vec2(1);
+ │ ^^^^ cannot assign to this expression
+ │
+ = note: WGSL does not support assignments to swizzles
+ = note: consider assigning each component individually
+
+"###,
+ );
+}
+
+#[test]
+fn binary_statement() {
+ check(
+ "
+ fn f() {
+ 3 + 5;
+ }
+ ",
+ r###"error: expected assignment or increment/decrement, found '3 + 5'
+ ┌─ wgsl:3:13
+ │
+3 │ 3 + 5;
+ │ ^^^^^ expected assignment or increment/decrement
+
+"###,
+ );
+}
+
+#[test]
+fn assign_to_expr() {
+ check(
+ "
+ fn f() {
+ 3 + 5 = 10;
+ }
+ ",
+ r###"error: invalid left-hand side of assignment
+ ┌─ wgsl:3:13
+ │
+3 │ 3 + 5 = 10;
+ │ ^^^^^ cannot assign to this expression
+
+"###,
+ );
+}
+
+#[test]
+fn assign_to_let() {
+ check(
+ "
+ fn f() {
+ let a = 10;
+ a = 20;
+ }
+ ",
+ r###"error: invalid left-hand side of assignment
+ ┌─ wgsl:4:10
+ │
+4 │ a = 20;
+ │ ^ cannot assign to this expression
+ │
+ = note: 'a' is an immutable binding
+ = note: consider declaring it with `var` instead of `let`
+
+"###,
+ );
+}
|
Assignment to swizzle produces unhelpful error message
Given the program:
```
fn f() {
var v = vec2(0);
v.xy = vec2(1);
}
```
Naga complains:
```
error: the left-hand side of an assignment must be a reference
┌─ assign-to-swizzle.wgsl:2:20
│
2 │ var v = vec2(0);
│ ╭───────────────────^
3 │ │ v.xy = vec2(1);
│ ╰───────^ expression is not a reference
Could not parse WGSL
```
This leads to questions in chat like:
> Hi. What's the equivalent WGSL code to this?
>
> p.xy = f(p.xy)
>
> I get this error and have no idea how to write this nicely...
The error message did not convey to the user that swizzle assignment is simply unsupported.
|
We could bake in some detection for this case and add it as note to the diagnostic, it would look something like this:
```
error: the left-hand side of an assignment must be a reference
┌─ test.wgsl:3:4
│
3 │ v.xy = vec2(1);
│ ^^^^ expression is not a reference
│
= You seem to be trying to assign to a swizzle
wgsl doesn't support assignments to swizzles
```
If we wanted something fancier we could try adding suggested fixes like rustc has, but that would be more complicated
```
error: the left-hand side of an assignment must be a reference
┌─ test.wgsl:3:4
│
3 │ v.xy = vec2(1);
│ ^^^^ expression is not a reference
│
= You seem to be trying to assign to a swizzle
wgsl doesn't support assignments to swizzles
help: try using assigning each component individually
┌─ test.wgsl:3:4
│
3 │ let a = vec2(1);
4 │ v.xy = a.x;
5 │ v.xy = a.y;
│ ^^^
│
```
|
2022-09-14T16:05:36Z
|
0.9
|
2023-02-01T17:40:31Z
|
4f8db997b0b1e73fc1e2cac070485333a5b61925
|
[
"assign_to_expr",
"assign_to_let",
"binary_statement",
"swizzle_assignment"
] |
[
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::nan_handling",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"back::msl::writer::test_stack_size",
"front::spv::test::parse",
"front::glsl::parser_tests::version",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::expressions",
"front::wgsl::lexer::test_numbers",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::control_flow",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_parentheses_switch",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_statement",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::namer::test",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"proc::test_matrix_size",
"front::wgsl::tests::parse_switch",
"proc::typifier::test_error_size",
"span::span_location",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_texture_query",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_type_cast",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"convert_wgsl",
"cube_array",
"sampler1d",
"storage1d",
"geometry",
"sample_rate_shading",
"storage_image_formats",
"image_queries",
"bad_for_initializer",
"bad_texture_sample_type",
"function_without_identifier",
"inconsistent_binding",
"invalid_float",
"break_if_bad_condition",
"invalid_arrays",
"invalid_integer",
"bad_type_cast",
"bad_texture",
"dead_code",
"constructor_parameter_type_mismatch",
"invalid_texture_sample_type",
"invalid_local_vars",
"invalid_runtime_sized_arrays",
"last_case_falltrough",
"local_var_missing_type",
"let_type_mismatch",
"invalid_access",
"invalid_structs",
"matrix_with_bad_type",
"reserved_identifier_prefix",
"misplaced_break_if",
"missing_default_case",
"invalid_functions",
"negative_index",
"struct_member_align_too_low",
"pointer_type_equivalence",
"struct_member_size_too_low",
"struct_member_non_po2_align",
"missing_bindings",
"type_not_constructible",
"postfix_pointers",
"type_not_inferrable",
"unknown_attribute",
"reserved_keyword",
"unexpected_constructor_parameters",
"module_scope_identifier_redefinition",
"unknown_conservative_depth",
"unknown_scalar_type",
"unknown_storage_class",
"unknown_ident",
"unknown_local_function",
"unknown_type",
"unknown_identifier",
"unknown_storage_format",
"unknown_built_in",
"var_type_mismatch",
"select",
"host_shareable_types",
"wrong_access_mode",
"valid_access",
"unknown_access",
"io_shareable_types",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 565)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 586)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/mod.rs - front::SymbolTable (line 151)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 142)"
] |
[] |
[] |
gfx-rs/naga
| 2,055
|
gfx-rs__naga-2055
|
[
"2053"
] |
1a99c1cf066de8d660904f1fb681f5647bc45205
|
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -163,6 +163,8 @@ fn is_word_part(c: char) -> bool {
pub(super) struct Lexer<'a> {
input: &'a str,
pub(super) source: &'a str,
+ // The byte offset of the end of the last non-trivia token.
+ last_end_offset: usize,
}
impl<'a> Lexer<'a> {
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -170,6 +172,7 @@ impl<'a> Lexer<'a> {
Lexer {
input,
source: input,
+ last_end_offset: 0,
}
}
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -196,6 +199,22 @@ impl<'a> Lexer<'a> {
Ok((res, start..end))
}
+ pub(super) fn start_byte_offset(&mut self) -> usize {
+ loop {
+ // Eat all trivia because `next` doesn't eat trailing trivia.
+ let (token, rest) = consume_token(self.input, false);
+ if let Token::Trivia = token {
+ self.input = rest;
+ } else {
+ return self.current_byte_offset();
+ }
+ }
+ }
+
+ pub(super) const fn end_byte_offset(&self) -> usize {
+ self.last_end_offset
+ }
+
fn peek_token_and_rest(&mut self) -> (TokenSpan<'a>, &'a str) {
let mut cloned = self.clone();
let token = cloned.next();
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -203,12 +222,12 @@ impl<'a> Lexer<'a> {
(token, rest)
}
- pub(super) const fn current_byte_offset(&self) -> usize {
+ const fn current_byte_offset(&self) -> usize {
self.source.len() - self.input.len()
}
pub(super) const fn span_from(&self, offset: usize) -> Span {
- offset..self.current_byte_offset()
+ offset..self.end_byte_offset()
}
#[must_use]
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -219,7 +238,10 @@ impl<'a> Lexer<'a> {
self.input = rest;
match token {
Token::Trivia => start_byte_offset = self.current_byte_offset(),
- _ => return (token, start_byte_offset..self.current_byte_offset()),
+ _ => {
+ self.last_end_offset = self.current_byte_offset();
+ return (token, start_byte_offset..self.last_end_offset);
+ }
}
}
}
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -237,22 +259,6 @@ impl<'a> Lexer<'a> {
}
}
- /// Consumes [`Trivia`] tokens until another token is encountered, returns
- /// the byte offset after consuming the tokens.
- ///
- /// [`Trivia`]: Token::Trivia
- #[must_use]
- pub(super) fn consume_blankspace(&mut self) -> usize {
- loop {
- let (token, rest) = consume_token(self.input, false);
- if let Token::Trivia = token {
- self.input = rest;
- } else {
- return self.current_byte_offset();
- }
- }
- }
-
#[must_use]
pub(super) fn peek(&mut self) -> TokenSpan<'a> {
let (token, _) = self.peek_token_and_rest();
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -223,7 +223,7 @@ impl<'a> Error<'a> {
Error::BadNumber(ref bad_span, ref err) => ParseError {
message: format!(
"{}: `{}`",
- err,&source[bad_span.clone()],
+ err, &source[bad_span.clone()],
),
labels: vec![(bad_span.clone(), err.to_string().into())],
notes: vec![],
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -878,7 +878,7 @@ impl<'a> ExpressionContext<'a, '_, '_> {
ExpressionContext<'a, '_, '_>,
) -> Result<TypedExpression, Error<'a>>,
) -> Result<TypedExpression, Error<'a>> {
- let start = lexer.current_byte_offset() as u32;
+ let start = lexer.start_byte_offset() as u32;
let mut accumulator = parser(lexer, self.reborrow())?;
while let Some(op) = classifier(lexer.peek().0) {
let _ = lexer.next();
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -886,7 +886,7 @@ impl<'a> ExpressionContext<'a, '_, '_> {
let mut left = self.apply_load_rule(accumulator);
let unloaded_right = parser(lexer, self.reborrow())?;
let right = self.apply_load_rule(unloaded_right);
- let end = lexer.current_byte_offset() as u32;
+ let end = lexer.end_byte_offset() as u32;
left = self.expressions.append(
crate::Expression::Binary { op, left, right },
NagaSpan::new(start, end),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -906,7 +906,7 @@ impl<'a> ExpressionContext<'a, '_, '_> {
ExpressionContext<'a, '_, '_>,
) -> Result<TypedExpression, Error<'a>>,
) -> Result<TypedExpression, Error<'a>> {
- let start = lexer.current_byte_offset() as u32;
+ let start = lexer.start_byte_offset() as u32;
let mut accumulator = parser(lexer, self.reborrow())?;
while let Some(op) = classifier(lexer.peek().0) {
let _ = lexer.next();
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -914,7 +914,7 @@ impl<'a> ExpressionContext<'a, '_, '_> {
let mut left = self.apply_load_rule(accumulator);
let unloaded_right = parser(lexer, self.reborrow())?;
let mut right = self.apply_load_rule(unloaded_right);
- let end = lexer.current_byte_offset() as u32;
+ let end = lexer.end_byte_offset() as u32;
self.binary_op_splat(op, &mut left, &mut right)?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1389,8 +1389,8 @@ impl Parser {
self.layouter.clear();
}
- fn push_rule_span(&mut self, rule: Rule, lexer: &Lexer<'_>) {
- self.rules.push((rule, lexer.current_byte_offset()));
+ fn push_rule_span(&mut self, rule: Rule, lexer: &mut Lexer<'_>) {
+ self.rules.push((rule, lexer.start_byte_offset()));
}
fn pop_rule_span(&mut self, lexer: &Lexer<'_>) -> Span {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2589,7 +2589,7 @@ impl Parser {
lexer: &mut Lexer<'a>,
mut ctx: ExpressionContext<'a, '_, '_>,
) -> Result<TypedExpression, Error<'a>> {
- let start = lexer.current_byte_offset();
+ let start = lexer.start_byte_offset();
self.push_rule_span(Rule::SingularExpr, lexer);
let primary_expr = self.parse_primary_expression(lexer, ctx.reborrow())?;
let singular_expr = self.parse_postfix(start, lexer, ctx.reborrow(), primary_expr)?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3249,7 +3249,7 @@ impl Parser {
None => {
match self.parse_type_decl_impl(lexer, attribute, name, type_arena, const_arena)? {
Some(inner) => {
- let span = name_span.start..lexer.current_byte_offset();
+ let span = name_span.start..lexer.end_byte_offset();
type_arena.insert(
crate::Type {
name: debug_name.map(|s| s.to_string()),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3304,11 +3304,11 @@ impl Parser {
) -> Result<(), Error<'a>> {
use crate::BinaryOperator as Bo;
- let span_start = lexer.consume_blankspace();
+ let span_start = lexer.start_byte_offset();
context.emitter.start(context.expressions);
let reference = self.parse_unary_expression(lexer, context.reborrow())?;
// The left hand side of an assignment must be a reference.
- let lhs_span = span_start..lexer.current_byte_offset();
+ let lhs_span = span_start..lexer.end_byte_offset();
if !reference.is_reference {
return Err(Error::NotReference(
"the left-hand side of an assignment",
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3409,7 +3409,7 @@ impl Parser {
other => return Err(Error::Unexpected(other, ExpectedToken::SwitchItem)),
};
- let span_end = lexer.current_byte_offset();
+ let span_end = lexer.end_byte_offset();
context
.block
.extend(context.emitter.finish(context.expressions));
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3732,7 +3732,7 @@ impl Parser {
let accept = self.parse_block(lexer, context.reborrow(), false)?;
let mut elsif_stack = Vec::new();
- let mut elseif_span_start = lexer.current_byte_offset();
+ let mut elseif_span_start = lexer.start_byte_offset();
let mut reject = loop {
if !lexer.skip(Token::Word("else")) {
break crate::Block::new();
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3759,10 +3759,10 @@ impl Parser {
other_emit,
other_block,
));
- elseif_span_start = lexer.current_byte_offset();
+ elseif_span_start = lexer.start_byte_offset();
};
- let span_end = lexer.current_byte_offset();
+ let span_end = lexer.end_byte_offset();
// reverse-fold the else-if blocks
//Note: we may consider uplifting this to the IR
for (other_span_start, other_cond, other_emit, other_block) in
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4427,7 +4427,7 @@ impl Parser {
}
// read items
- let start = lexer.current_byte_offset();
+ let start = lexer.start_byte_offset();
match lexer.next() {
(Token::Separator(';'), _) => {}
(Token::Word("struct"), _) => {
|
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -640,11 +640,11 @@ fn reserved_keyword() {
r#"
var bool: bool = true;
"#,
- r###"error: name ` bool: bool = true;` is a reserved keyword
- ┌─ wgsl:2:16
+ r###"error: name `bool: bool = true;` is a reserved keyword
+ ┌─ wgsl:2:17
│
2 │ var bool: bool = true;
- │ ^^^^^^^^^^^^^^^^^^^ definition of ` bool: bool = true;`
+ │ ^^^^^^^^^^^^^^^^^^ definition of `bool: bool = true;`
"###,
);
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -765,13 +765,13 @@ fn module_scope_identifier_redefinition() {
var foo: bool = true;
var foo: bool = true;
"#,
- r###"error: redefinition of ` foo: bool = true;`
- ┌─ wgsl:2:16
+ r###"error: redefinition of `foo: bool = true;`
+ ┌─ wgsl:2:17
│
2 │ var foo: bool = true;
- │ ^^^^^^^^^^^^^^^^^^ previous definition of ` foo: bool = true;`
+ │ ^^^^^^^^^^^^^^^^^ previous definition of `foo: bool = true;`
3 │ var foo: bool = true;
- │ ^^^^^^^^^^^^^^^^^^ redefinition of ` foo: bool = true;`
+ │ ^^^^^^^^^^^^^^^^^ redefinition of `foo: bool = true;`
"###,
);
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -783,10 +783,10 @@ fn module_scope_identifier_redefinition() {
let foo: bool = true;
"#,
r###"error: redefinition of `foo`
- ┌─ wgsl:2:16
+ ┌─ wgsl:2:17
│
2 │ var foo: bool = true;
- │ ^^^^^^^^^^^^^^^^^^ previous definition of ` foo: bool = true;`
+ │ ^^^^^^^^^^^^^^^^^ previous definition of `foo: bool = true;`
3 │ let foo: bool = true;
│ ^^^ redefinition of `foo`
|
Spans on expressions are bad
Given the input:
```
fn f() {
var v = vec2(0);
v.xy = vec2(1);
}
```
Naga produces the error message:
```
error: the left-hand side of an assignment must be a reference
┌─ assign-to-swizzle.wgsl:2:20
│
2 │ var v = vec2(0);
│ ╭───────────────────^
3 │ │ v.xy = vec2(1);
│ ╰───────^ expression is not a reference
Could not parse WGSL
```
That span is terrible. It should simply refer to the `v.xy`, or ideally just the `.xy`.
The quality of the error message itself is addressed in #2052.
|
2022-09-14T02:11:09Z
|
0.9
|
2022-09-15T07:19:20Z
|
4f8db997b0b1e73fc1e2cac070485333a5b61925
|
[
"module_scope_identifier_redefinition",
"reserved_keyword"
] |
[
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::nan_handling",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::glsl::parser_tests::version",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::swizzles",
"front::spv::test::parse",
"front::wgsl::lexer::test_numbers",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::function_overloading",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_pointers",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_parentheses_switch",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_switch",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::namer::test",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"proc::typifier::test_error_size",
"proc::test_matrix_size",
"front::glsl::parser_tests::declarations",
"span::span_location",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_texture_load",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"convert_wgsl",
"cube_array",
"geometry",
"storage1d",
"sampler1d",
"sample_rate_shading",
"storage_image_formats",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"break_if_bad_condition",
"bad_texture_sample_type",
"inconsistent_binding",
"invalid_float",
"bad_type_cast",
"constructor_parameter_type_mismatch",
"invalid_arrays",
"bad_texture",
"invalid_integer",
"dead_code",
"invalid_texture_sample_type",
"invalid_access",
"invalid_local_vars",
"last_case_falltrough",
"local_var_missing_type",
"invalid_runtime_sized_arrays",
"invalid_structs",
"let_type_mismatch",
"misplaced_break_if",
"missing_default_case",
"reserved_identifier_prefix",
"matrix_with_bad_type",
"invalid_functions",
"negative_index",
"struct_member_align_too_low",
"struct_member_non_po2_align",
"struct_member_size_too_low",
"type_not_inferrable",
"type_not_constructible",
"pointer_type_equivalence",
"unknown_access",
"unknown_conservative_depth",
"unexpected_constructor_parameters",
"unknown_attribute",
"missing_bindings",
"unknown_ident",
"unknown_built_in",
"postfix_pointers",
"unknown_storage_format",
"unknown_local_function",
"unknown_type",
"unknown_storage_class",
"unknown_scalar_type",
"unknown_identifier",
"var_type_mismatch",
"host_shareable_types",
"select",
"wrong_access_mode",
"valid_access",
"io_shareable_types",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 586)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 565)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/mod.rs - front::SymbolTable (line 151)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 142)"
] |
[] |
[] |
|
gfx-rs/naga
| 2,024
|
gfx-rs__naga-2024
|
[
"2021"
] |
b209d911681c4ef563f7d9048623667743e6248f
|
diff --git a/src/front/mod.rs b/src/front/mod.rs
--- a/src/front/mod.rs
+++ b/src/front/mod.rs
@@ -14,6 +14,7 @@ pub mod wgsl;
use crate::{
arena::{Arena, Handle, UniqueArena},
proc::{ResolveContext, ResolveError, TypeResolution},
+ FastHashMap,
};
use std::ops;
diff --git a/src/front/mod.rs b/src/front/mod.rs
--- a/src/front/mod.rs
+++ b/src/front/mod.rs
@@ -133,3 +134,157 @@ impl ops::Index<Handle<crate::Expression>> for Typifier {
&self.resolutions[handle.index()]
}
}
+
+/// Type representing a lexical scope, associating a name to a single variable
+///
+/// The scope is generic over the variable representation and name representaion
+/// in order to allow larger flexibility on the frontends on how they might
+/// represent them.
+type Scope<Name, Var> = FastHashMap<Name, Var>;
+
+/// Structure responsible for managing variable lookups and keeping track of
+/// lexical scopes
+///
+/// The symbol table is generic over the variable representation and its name
+/// to allow larger flexibility on the frontends on how they might represent them.
+///
+/// ```
+/// use naga::front::SymbolTable;
+///
+/// // Create a new symbol table with `u32`s representing the variable
+/// let mut symbol_table: SymbolTable<&str, u32> = SymbolTable::default();
+///
+/// // Add two variables named `var1` and `var2` with 0 and 2 respectively
+/// symbol_table.add("var1", 0);
+/// symbol_table.add("var2", 2);
+///
+/// // Check that `var1` exists and is `0`
+/// assert_eq!(symbol_table.lookup("var1"), Some(&0));
+///
+/// // Push a new scope and add a variable to it named `var1` shadowing the
+/// // variable of our previous scope
+/// symbol_table.push_scope();
+/// symbol_table.add("var1", 1);
+///
+/// // Check that `var1` now points to the new value of `1` and `var2` still
+/// // exists with its value of `2`
+/// assert_eq!(symbol_table.lookup("var1"), Some(&1));
+/// assert_eq!(symbol_table.lookup("var2"), Some(&2));
+///
+/// // Pop the scope
+/// symbol_table.pop_scope();
+///
+/// // Check that `var1` now refers to our initial variable with value `0`
+/// assert_eq!(symbol_table.lookup("var1"), Some(&0));
+/// ```
+///
+/// Scopes are ordered as a LIFO stack so a variable defined in a later scope
+/// with the same name as another variable defined in a earlier scope will take
+/// precedence in the lookup. Scopes can be added with [`push_scope`] and
+/// removed with [`pop_scope`].
+///
+/// A root scope is added when the symbol table is created and must always be
+/// present. Trying to pop it will result in a panic.
+///
+/// Variables can be added with [`add`] and looked up with [`lookup`]. Adding a
+/// variable will do so in the currently active scope and as mentioned
+/// previously a lookup will search from the current scope to the root scope.
+///
+/// [`push_scope`]: Self::push_scope
+/// [`pop_scope`]: Self::push_scope
+/// [`add`]: Self::add
+/// [`lookup`]: Self::lookup
+pub struct SymbolTable<Name, Var> {
+ /// Stack of lexical scopes. Not all scopes are active; see [`cursor`].
+ ///
+ /// [`cursor`]: Self::cursor
+ scopes: Vec<Scope<Name, Var>>,
+ /// Limit of the [`scopes`] stack (exclusive). By using a separate value for
+ /// the stack length instead of `Vec`'s own internal length, the scopes can
+ /// be reused to cache memory allocations.
+ ///
+ /// [`scopes`]: Self::scopes
+ cursor: usize,
+}
+
+impl<Name, Var> SymbolTable<Name, Var> {
+ /// Adds a new lexical scope.
+ ///
+ /// All variables declared after this point will be added to this scope
+ /// until another scope is pushed or [`pop_scope`] is called, causing this
+ /// scope to be removed along with all variables added to it.
+ ///
+ /// [`pop_scope`]: Self::pop_scope
+ pub fn push_scope(&mut self) {
+ // If the cursor is equal to the scope's stack length then we need to
+ // push another empty scope. Otherwise we can reuse the already existing
+ // scope.
+ if self.scopes.len() == self.cursor {
+ self.scopes.push(FastHashMap::default())
+ } else {
+ self.scopes[self.cursor].clear();
+ }
+
+ self.cursor += 1;
+ }
+
+ /// Removes the current lexical scope and all its variables
+ ///
+ /// # PANICS
+ /// - If the current lexical scope is the root scope
+ pub fn pop_scope(&mut self) {
+ // Despite the method title, the variables are only deleted when the
+ // scope is reused. This is because while a clear is inevitable if the
+ // scope needs to be reused, there are cases where the scope might be
+ // popped and not reused, i.e. if another scope with the same nesting
+ // level is never pushed again.
+ assert!(self.cursor != 1, "Tried to pop the root scope");
+
+ self.cursor -= 1;
+ }
+}
+
+impl<Name, Var> SymbolTable<Name, Var>
+where
+ Name: std::hash::Hash + Eq,
+{
+ /// Perform a lookup for a variable named `name`.
+ ///
+ /// As stated in the struct level documentation the lookup will proceed from
+ /// the current scope to the root scope, returning `Some` when a variable is
+ /// found or `None` if there doesn't exist a variable with `name` in any
+ /// scope.
+ pub fn lookup<Q: ?Sized>(&mut self, name: &Q) -> Option<&Var>
+ where
+ Name: std::borrow::Borrow<Q>,
+ Q: std::hash::Hash + Eq,
+ {
+ // Iterate backwards trough the scopes and try to find the variable
+ for scope in self.scopes[..self.cursor].iter().rev() {
+ if let Some(var) = scope.get(name) {
+ return Some(var);
+ }
+ }
+
+ None
+ }
+
+ /// Adds a new variable to the current scope.
+ ///
+ /// Returns the previous variable with the same name in this scope if it
+ /// exists, so that the frontend might handle it in case variable shadowing
+ /// is disallowed.
+ pub fn add(&mut self, name: Name, var: Var) -> Option<Var> {
+ self.scopes[self.cursor - 1].insert(name, var)
+ }
+}
+
+impl<Name, Var> Default for SymbolTable<Name, Var> {
+ /// Constructs a new symbol table with a root scope
+ fn default() -> Self {
+ Self {
+ scopes: vec![FastHashMap::default()],
+ cursor: 1,
+ }
+ }
+}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -749,7 +749,7 @@ impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, TypedExpression> {
}
struct StatementContext<'input, 'temp, 'out> {
- lookup_ident: &'temp mut FastHashMap<&'input str, TypedExpression>,
+ symbol_table: &'temp mut super::SymbolTable<&'input str, TypedExpression>,
typifier: &'temp mut super::Typifier,
variables: &'out mut Arena<crate::LocalVariable>,
expressions: &'out mut Arena<crate::Expression>,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -764,7 +764,7 @@ struct StatementContext<'input, 'temp, 'out> {
impl<'a, 'temp> StatementContext<'a, 'temp, '_> {
fn reborrow(&mut self) -> StatementContext<'a, '_, '_> {
StatementContext {
- lookup_ident: self.lookup_ident,
+ symbol_table: self.symbol_table,
typifier: self.typifier,
variables: self.variables,
expressions: self.expressions,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -786,7 +786,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> {
'temp: 't,
{
ExpressionContext {
- lookup_ident: self.lookup_ident,
+ symbol_table: self.symbol_table,
typifier: self.typifier,
expressions: self.expressions,
types: self.types,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -807,7 +807,7 @@ struct SamplingContext {
}
struct ExpressionContext<'input, 'temp, 'out> {
- lookup_ident: &'temp FastHashMap<&'input str, TypedExpression>,
+ symbol_table: &'temp mut super::SymbolTable<&'input str, TypedExpression>,
typifier: &'temp mut super::Typifier,
expressions: &'out mut Arena<crate::Expression>,
types: &'out mut UniqueArena<crate::Type>,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -823,7 +823,7 @@ struct ExpressionContext<'input, 'temp, 'out> {
impl<'a> ExpressionContext<'a, '_, '_> {
fn reborrow(&mut self) -> ExpressionContext<'a, '_, '_> {
ExpressionContext {
- lookup_ident: self.lookup_ident,
+ symbol_table: self.symbol_table,
typifier: self.typifier,
expressions: self.expressions,
types: self.types,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2286,7 +2286,7 @@ impl Parser {
)
}
(Token::Word(word), span) => {
- if let Some(definition) = ctx.lookup_ident.get(word) {
+ if let Some(definition) = ctx.symbol_table.lookup(word) {
let _ = lexer.next();
self.pop_scope(lexer);
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3432,6 +3432,9 @@ impl Parser {
mut context: StatementContext<'a, '_, 'out>,
) -> Result<(bool, crate::Block), Error<'a>> {
let mut body = crate::Block::new();
+ // Push a new lexical scope for the switch case body
+ context.symbol_table.push_scope();
+
lexer.expect(Token::Paren('{'))?;
let fall_through = loop {
// default statements
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3445,6 +3448,8 @@ impl Parser {
}
self.parse_statement(lexer, context.reborrow(), &mut body, false)?;
};
+ // Pop the switch case body lexical scope
+ context.symbol_table.pop_scope();
Ok((fall_through, body))
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3465,6 +3470,9 @@ impl Parser {
}
(Token::Paren('{'), _) => {
self.push_scope(Scope::Block, lexer);
+ // Push a new lexical scope for the block statement
+ context.symbol_table.push_scope();
+
let _ = lexer.next();
let mut statements = crate::Block::new();
while !lexer.skip(Token::Paren('}')) {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3475,6 +3483,9 @@ impl Parser {
is_uniform_control_flow,
)?;
}
+ // Pop the block statement lexical scope
+ context.symbol_table.pop_scope();
+
self.pop_scope(lexer);
let span = NagaSpan::from(self.pop_scope(lexer));
block.push(crate::Statement::Block(statements), span);
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3539,7 +3550,7 @@ impl Parser {
}
}
block.extend(emitter.finish(context.expressions));
- context.lookup_ident.insert(
+ context.symbol_table.add(
name,
TypedExpression {
handle: expr_id,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3655,7 +3666,7 @@ impl Parser {
let expr_id = context
.expressions
.append(crate::Expression::LocalVariable(var_id), Default::default());
- context.lookup_ident.insert(
+ context.symbol_table.add(
name,
TypedExpression {
handle: expr_id,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3843,10 +3854,14 @@ impl Parser {
},
NagaSpan::from(span),
);
+ // Push a lexical scope for the while loop body
+ context.symbol_table.push_scope();
while !lexer.skip(Token::Paren('}')) {
self.parse_statement(lexer, context.reborrow(), &mut body, false)?;
}
+ // Pop the while loop body lexical scope
+ context.symbol_table.pop_scope();
Some(crate::Statement::Loop {
body,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3857,6 +3872,9 @@ impl Parser {
"for" => {
let _ = lexer.next();
lexer.expect(Token::Paren('('))?;
+ // Push a lexical scope for the for loop
+ context.symbol_table.push_scope();
+
if !lexer.skip(Token::Separator(';')) {
let num_statements = block.len();
let (_, span) = lexer.capture_span(|lexer| {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3904,7 +3922,9 @@ impl Parser {
let mut continuing = crate::Block::new();
if !lexer.skip(Token::Paren(')')) {
match lexer.peek().0 {
- Token::Word(ident) if context.lookup_ident.get(ident).is_none() => {
+ Token::Word(ident)
+ if context.symbol_table.lookup(ident).is_none() =>
+ {
self.parse_function_statement(
lexer,
ident,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3923,6 +3943,8 @@ impl Parser {
while !lexer.skip(Token::Paren('}')) {
self.parse_statement(lexer, context.reborrow(), &mut body, false)?;
}
+ // Pop the for loop lexical scope
+ context.symbol_table.pop_scope();
Some(crate::Statement::Loop {
body,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4013,7 +4035,7 @@ impl Parser {
}
// assignment or a function call
ident => {
- match context.lookup_ident.get(ident) {
+ match context.symbol_table.lookup(ident) {
Some(_) => self.parse_assignment_statement(
lexer,
context.as_expression(block, &mut emitter),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4052,6 +4074,10 @@ impl Parser {
let mut body = crate::Block::new();
let mut continuing = crate::Block::new();
let mut break_if = None;
+
+ // Push a lexical scope for the loop body
+ context.symbol_table.push_scope();
+
lexer.expect(Token::Paren('{'))?;
loop {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4113,6 +4139,9 @@ impl Parser {
self.parse_statement(lexer, context.reborrow(), &mut body, false)?;
}
+ // Pop the loop body lexical scope
+ context.symbol_table.pop_scope();
+
Ok(crate::Statement::Loop {
body,
continuing,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4127,6 +4156,9 @@ impl Parser {
is_uniform_control_flow: bool,
) -> Result<crate::Block, Error<'a>> {
self.push_scope(Scope::Block, lexer);
+ // Push a lexical scope for the block
+ context.symbol_table.push_scope();
+
lexer.expect(Token::Paren('{'))?;
let mut block = crate::Block::new();
while !lexer.skip(Token::Paren('}')) {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4137,6 +4169,9 @@ impl Parser {
is_uniform_control_flow,
)?;
}
+ //Pop the block lexical scope
+ context.symbol_table.pop_scope();
+
self.pop_scope(lexer);
Ok(block)
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4165,7 +4200,7 @@ impl Parser {
) -> Result<(crate::Function, &'a str), Error<'a>> {
self.push_scope(Scope::FunctionDecl, lexer);
// read function name
- let mut lookup_ident = FastHashMap::default();
+ let mut symbol_table = super::SymbolTable::default();
let (fun_name, span) = lexer.next_ident_with_span()?;
if crate::keywords::wgsl::RESERVED.contains(&fun_name) {
return Err(Error::ReservedKeyword(span));
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4191,7 +4226,7 @@ impl Parser {
_ => unreachable!(),
};
let expression = expressions.append(expression.clone(), span);
- lookup_ident.insert(
+ symbol_table.add(
name,
TypedExpression {
handle: expression,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4221,7 +4256,7 @@ impl Parser {
crate::Expression::FunctionArgument(param_index),
NagaSpan::from(param_name_span),
);
- lookup_ident.insert(
+ symbol_table.add(
param_name,
TypedExpression {
handle: expression,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4266,7 +4301,7 @@ impl Parser {
fun.body = self.parse_block(
lexer,
StatementContext {
- lookup_ident: &mut lookup_ident,
+ symbol_table: &mut symbol_table,
typifier: &mut typifier,
variables: &mut fun.local_variables,
expressions: &mut fun.expressions,
|
diff --git /dev/null b/tests/in/lexical-scopes.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/in/lexical-scopes.wgsl
@@ -0,0 +1,58 @@
+fn blockLexicalScope(a: bool) {
+ let a = 1.0;
+ {
+ let a = 2;
+ {
+ let a = true;
+ }
+ let test = a == 3;
+ }
+ let test = a == 2.0;
+}
+
+fn ifLexicalScope(a: bool) {
+ let a = 1.0;
+ if (a == 1.0) {
+ let a = true;
+ }
+ let test = a == 2.0;
+}
+
+
+fn loopLexicalScope(a: bool) {
+ let a = 1.0;
+ loop {
+ let a = true;
+ }
+ let test = a == 2.0;
+}
+
+fn forLexicalScope(a: f32) {
+ let a = false;
+ for (var a = 0; a < 1; a++) {
+ let a = 3.0;
+ }
+ let test = a == true;
+}
+
+fn whileLexicalScope(a: i32) {
+ while (a > 2) {
+ let a = false;
+ }
+ let test = a == 1;
+}
+
+fn switchLexicalScope(a: i32) {
+ switch (a) {
+ case 0 {
+ let a = false;
+ }
+ case 1 {
+ let a = 2.0;
+ }
+ default {
+ let a = true;
+ }
+ }
+ let test = a == 2;
+}
diff --git /dev/null b/tests/out/wgsl/lexical-scopes.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/out/wgsl/lexical-scopes.wgsl
@@ -0,0 +1,60 @@
+fn blockLexicalScope(a: bool) {
+ {
+ {
+ }
+ let test = (2 == 3);
+ }
+ let test_1 = (1.0 == 2.0);
+}
+
+fn ifLexicalScope(a_1: bool) {
+ if (1.0 == 1.0) {
+ }
+ let test_2 = (1.0 == 2.0);
+}
+
+fn loopLexicalScope(a_2: bool) {
+ loop {
+ }
+ let test_3 = (1.0 == 2.0);
+}
+
+fn forLexicalScope(a_3: f32) {
+ var a_4: i32 = 0;
+
+ loop {
+ let _e4 = a_4;
+ if (_e4 < 1) {
+ } else {
+ break;
+ }
+ continuing {
+ let _e7 = a_4;
+ a_4 = (_e7 + 1);
+ }
+ }
+ let test_4 = (false == true);
+}
+
+fn whileLexicalScope(a_5: i32) {
+ loop {
+ if (a_5 > 2) {
+ } else {
+ break;
+ }
+ }
+ let test_5 = (a_5 == 1);
+}
+
+fn switchLexicalScope(a_6: i32) {
+ switch a_6 {
+ case 0: {
+ }
+ case 1: {
+ }
+ default: {
+ }
+ }
+ let test_6 = (a_6 == 2);
+}
+
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -543,6 +543,7 @@ fn convert_wgsl() {
"break-if",
Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL,
),
+ ("lexical-scopes", Targets::WGSL),
];
for &(name, targets) in inputs.iter() {
|
[wgsl-in] let declarations from different scopes merged?
Shadowed let declarations can get incorrectly hoisted out of conditional scopes.
See example WGSL:
```
@vertex
fn main(@location(0) cond: f32) -> @location(0) f32 {
let value = 1.;
if cond > 0. {
let value = 2.;
return 3.;
}
return value;
}
```
This shader always returns 2 when the if condition evaluates to false.
Same shader translated to GLSL by Naga:
```
#version 310 es
precision highp float;
precision highp int;
layout(location = 0) in float _p2vs_location0;
layout(location = 0) smooth out float _vs2fs_location0;
void main() {
float cond = _p2vs_location0;
if ((cond > 0.0)) {
_vs2fs_location0 = 3.0;
gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);
return;
}
_vs2fs_location0 = 2.0;
gl_Position.yz = vec2(-gl_Position.y, gl_Position.z * 2.0 - gl_Position.w);
return;
}
```
Tested this happens on 0.9 and HEAD.
|
2022-08-07T03:59:14Z
|
0.9
|
2022-09-03T15:30:55Z
|
4f8db997b0b1e73fc1e2cac070485333a5b61925
|
[
"convert_wgsl"
] |
[
"arena::tests::fetch_or_append_unique",
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"back::msl::test_error_size",
"front::glsl::constants::tests::cast",
"back::spv::layout::test_logical_layout_in_words",
"back::spv::layout::test_physical_layout_in_words",
"front::glsl::constants::tests::nan_handling",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::constants::tests::access",
"front::glsl::parser_tests::constants",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::version",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::swizzles",
"front::spv::test::parse",
"front::wgsl::lexer::test_numbers",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_parentheses_switch",
"front::wgsl::tests::parse_parentheses_if",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_texture_store",
"proc::namer::test",
"front::wgsl::tests::parse_texture_query",
"proc::test_matrix_size",
"front::wgsl::tests::parse_loop",
"proc::typifier::test_error_size",
"span::span_location",
"front::glsl::parser_tests::declarations",
"valid::analyzer::uniform_control_flow",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"cube_array",
"sampler1d",
"geometry",
"storage1d",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"function_without_identifier",
"bad_texture_sample_type",
"bad_for_initializer",
"break_if_bad_condition",
"inconsistent_binding",
"bad_type_cast",
"invalid_float",
"invalid_integer",
"invalid_arrays",
"constructor_parameter_type_mismatch",
"dead_code",
"bad_texture",
"invalid_access",
"invalid_texture_sample_type",
"last_case_falltrough",
"misplaced_break_if",
"local_var_missing_type",
"invalid_structs",
"invalid_local_vars",
"invalid_runtime_sized_arrays",
"missing_default_case",
"reserved_identifier_prefix",
"let_type_mismatch",
"matrix_with_bad_type",
"struct_member_align_too_low",
"struct_member_non_po2_align",
"struct_member_size_too_low",
"type_not_constructible",
"missing_bindings",
"postfix_pointers",
"invalid_functions",
"module_scope_identifier_redefinition",
"unknown_attribute",
"unknown_access",
"reserved_keyword",
"type_not_inferrable",
"unknown_conservative_depth",
"unknown_built_in",
"unexpected_constructor_parameters",
"negative_index",
"unknown_scalar_type",
"pointer_type_equivalence",
"select",
"unknown_ident",
"unknown_storage_class",
"unknown_type",
"unknown_identifier",
"unknown_storage_format",
"unknown_local_function",
"host_shareable_types",
"var_type_mismatch",
"wrong_access_mode",
"valid_access",
"io_shareable_types",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 565)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 586)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 142)"
] |
[] |
[] |
|
gfx-rs/naga
| 2,005
|
gfx-rs__naga-2005
|
[
"1782"
] |
e7ddd3564c214d8acf554a03915d9bb179e0b772
|
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -69,7 +69,7 @@ validate-wgsl: $(SNAPSHOTS_BASE_OUT)/wgsl/*.wgsl
cargo run $${file}; \
done
-validate-hlsl-dxc: SHELL:=/bin/bash # required because config files uses arrays
+validate-hlsl-dxc: SHELL:=/usr/bin/env bash # required because config files uses arrays
validate-hlsl-dxc: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl
@set -e && for file in $^ ; do \
DXC_PARAMS="-Wno-parentheses-equality -Zi -Qembed_debug -Od"; \
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -94,7 +94,7 @@ validate-hlsl-dxc: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl
echo "======================"; \
done
-validate-hlsl-fxc: SHELL:=/bin/bash # required because config files uses arrays
+validate-hlsl-fxc: SHELL:=/usr/bin/env bash # required because config files uses arrays
validate-hlsl-fxc: $(SNAPSHOTS_BASE_OUT)/hlsl/*.hlsl
@set -e && for file in $^ ; do \
FXC_PARAMS="-Zi -Od"; \
diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs
--- a/src/back/hlsl/mod.rs
+++ b/src/back/hlsl/mod.rs
@@ -189,6 +189,8 @@ pub struct Options {
/// Add special constants to `SV_VertexIndex` and `SV_InstanceIndex`,
/// to make them work like in Vulkan/Metal, with help of the host.
pub special_constants_binding: Option<BindTarget>,
+ /// Bind target of the push constant buffer
+ pub push_constants_target: Option<BindTarget>,
}
impl Default for Options {
diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs
--- a/src/back/hlsl/mod.rs
+++ b/src/back/hlsl/mod.rs
@@ -198,6 +200,7 @@ impl Default for Options {
binding_map: BindingMap::default(),
fake_missing_bindings: true,
special_constants_binding: None,
+ push_constants_target: None,
}
}
}
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -623,12 +623,45 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
self.write_type(module, global.ty)?;
register
}
- crate::AddressSpace::PushConstant => unimplemented!("Push constants"),
+ crate::AddressSpace::PushConstant => {
+ // The type of the push constants will be wrapped in `ConstantBuffer`
+ write!(self.out, "ConstantBuffer<")?;
+ "b"
+ }
};
+ // If the global is a push constant write the type now because it will be a
+ // generic argument to `ConstantBuffer`
+ if global.space == crate::AddressSpace::PushConstant {
+ self.write_global_type(module, global.ty)?;
+
+ // need to write the array size if the type was emitted with `write_type`
+ if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner {
+ self.write_array_size(module, base, size)?;
+ }
+
+ // Close the angled brackets for the generic argument
+ write!(self.out, ">")?;
+ }
+
let name = &self.names[&NameKey::GlobalVariable(handle)];
write!(self.out, " {}", name)?;
+ // Push constants need to be assigned a binding explicitly by the consumer
+ // since naga has no way to know the binding from the shader alone
+ if global.space == crate::AddressSpace::PushConstant {
+ let target = self
+ .options
+ .push_constants_target
+ .as_ref()
+ .expect("No bind target was defined for the push constants block");
+ write!(self.out, ": register(b{}", target.register)?;
+ if target.space != 0 {
+ write!(self.out, ", space{}", target.space)?;
+ }
+ write!(self.out, ")")?;
+ }
+
if let Some(ref binding) = global.binding {
// this was already resolved earlier when we started evaluating an entry point.
let bt = self.options.resolve_resource_binding(binding).unwrap();
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -665,34 +698,13 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
if global.space == crate::AddressSpace::Uniform {
write!(self.out, " {{ ")?;
- let matrix_data = get_inner_matrix_data(module, global.ty);
-
- // We treat matrices of the form `matCx2` as a sequence of C `vec2`s.
- // See the module-level block comment in mod.rs for details.
- if let Some(MatrixType {
- columns,
- rows: crate::VectorSize::Bi,
- width: 4,
- }) = matrix_data
- {
- write!(
- self.out,
- "__mat{}x2 {}",
- columns as u8,
- &self.names[&NameKey::GlobalVariable(handle)]
- )?;
- } else {
- // Even though Naga IR matrices are column-major, we must describe
- // matrices passed from the CPU as being in row-major order.
- // See the module-level block comment in mod.rs for details.
- if matrix_data.is_some() {
- write!(self.out, "row_major ")?;
- }
+ self.write_global_type(module, global.ty)?;
- self.write_type(module, global.ty)?;
- let sub_name = &self.names[&NameKey::GlobalVariable(handle)];
- write!(self.out, " {}", sub_name)?;
- }
+ write!(
+ self.out,
+ " {}",
+ &self.names[&NameKey::GlobalVariable(handle)]
+ )?;
// need to write the array size if the type was emitted with `write_type`
if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner {
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -829,27 +841,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
TypeInner::Array { base, size, .. } => {
// HLSL arrays are written as `type name[size]`
- let matrix_data = get_inner_matrix_data(module, member.ty);
-
- // We treat matrices of the form `matCx2` as a sequence of C `vec2`s.
- // See the module-level block comment in mod.rs for details.
- if let Some(MatrixType {
- columns,
- rows: crate::VectorSize::Bi,
- width: 4,
- }) = matrix_data
- {
- write!(self.out, "__mat{}x2", columns as u8)?;
- } else {
- // Even though Naga IR matrices are column-major, we must describe
- // matrices passed from the CPU as being in row-major order.
- // See the module-level block comment in mod.rs for details.
- if matrix_data.is_some() {
- write!(self.out, "row_major ")?;
- }
-
- self.write_type(module, base)?;
- }
+ self.write_global_type(module, member.ty)?;
// Write `name`
write!(
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -923,6 +915,40 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
Ok(())
}
+ /// Helper method used to write global/structs non image/sampler types
+ ///
+ /// # Notes
+ /// Adds no trailing or leading whitespace
+ pub(super) fn write_global_type(
+ &mut self,
+ module: &Module,
+ ty: Handle<crate::Type>,
+ ) -> BackendResult {
+ let matrix_data = get_inner_matrix_data(module, ty);
+
+ // We treat matrices of the form `matCx2` as a sequence of C `vec2`s.
+ // See the module-level block comment in mod.rs for details.
+ if let Some(MatrixType {
+ columns,
+ rows: crate::VectorSize::Bi,
+ width: 4,
+ }) = matrix_data
+ {
+ write!(self.out, "__mat{}x2", columns as u8)?;
+ } else {
+ // Even though Naga IR matrices are column-major, we must describe
+ // matrices passed from the CPU as being in row-major order.
+ // See the module-level block comment in mod.rs for details.
+ if matrix_data.is_some() {
+ write!(self.out, "row_major ")?;
+ }
+
+ self.write_type(module, ty)?;
+ }
+
+ Ok(())
+ }
+
/// Helper method used to write non image/sampler types
///
/// # Notes
|
diff --git a/tests/in/push-constants.param.ron b/tests/in/push-constants.param.ron
--- a/tests/in/push-constants.param.ron
+++ b/tests/in/push-constants.param.ron
@@ -8,4 +8,11 @@
writer_flags: (bits: 0),
binding_map: {},
),
+ hlsl: (
+ shader_model: V5_1,
+ binding_map: {},
+ fake_missing_bindings: true,
+ special_constants_binding: Some((space: 1, register: 0)),
+ push_constants_target: Some((space: 0, register: 0)),
+ ),
)
diff --git a/tests/in/push-constants.wgsl b/tests/in/push-constants.wgsl
--- a/tests/in/push-constants.wgsl
+++ b/tests/in/push-constants.wgsl
@@ -7,6 +7,14 @@ struct FragmentIn {
@location(0) color: vec4<f32>
}
+@vertex
+fn vert_main(
+ @location(0) pos : vec2<f32>,
+ @builtin(vertex_index) vi: u32,
+) -> @builtin(position) vec4<f32> {
+ return vec4<f32>(f32(vi) * pc.multiplier * pos, 0.0, 1.0);
+}
+
@fragment
fn main(in: FragmentIn) -> @location(0) vec4<f32> {
return in.color * pc.multiplier;
diff --git /dev/null b/tests/out/glsl/push-constants.vert_main.Vertex.glsl
new file mode 100644
--- /dev/null
+++ b/tests/out/glsl/push-constants.vert_main.Vertex.glsl
@@ -0,0 +1,23 @@
+#version 320 es
+
+precision highp float;
+precision highp int;
+
+struct PushConstants {
+ float multiplier;
+};
+struct FragmentIn {
+ vec4 color;
+};
+uniform PushConstants pc;
+
+layout(location = 0) in vec2 _p2vs_location0;
+
+void main() {
+ vec2 pos = _p2vs_location0;
+ uint vi = uint(gl_VertexID);
+ float _e5 = pc.multiplier;
+ gl_Position = vec4(((float(vi) * _e5) * pos), 0.0, 1.0);
+ return;
+}
+
diff --git /dev/null b/tests/out/hlsl/push-constants.hlsl
new file mode 100644
--- /dev/null
+++ b/tests/out/hlsl/push-constants.hlsl
@@ -0,0 +1,33 @@
+struct NagaConstants {
+ int base_vertex;
+ int base_instance;
+ uint other;
+};
+ConstantBuffer<NagaConstants> _NagaConstants: register(b0, space1);
+
+struct PushConstants {
+ float multiplier;
+};
+
+struct FragmentIn {
+ float4 color : LOC0;
+};
+
+ConstantBuffer<PushConstants> pc: register(b0);
+
+struct FragmentInput_main {
+ float4 color : LOC0;
+};
+
+float4 vert_main(float2 pos : LOC0, uint vi : SV_VertexID) : SV_Position
+{
+ float _expr5 = pc.multiplier;
+ return float4(((float((_NagaConstants.base_vertex + vi)) * _expr5) * pos), 0.0, 1.0);
+}
+
+float4 main(FragmentInput_main fragmentinput_main) : SV_Target0
+{
+ FragmentIn in_ = { fragmentinput_main.color };
+ float _expr4 = pc.multiplier;
+ return (in_.color * _expr4);
+}
diff --git /dev/null b/tests/out/hlsl/push-constants.hlsl.config
new file mode 100644
--- /dev/null
+++ b/tests/out/hlsl/push-constants.hlsl.config
@@ -0,0 +1,3 @@
+vertex=(vert_main:vs_5_1 )
+fragment=(main:ps_5_1 )
+compute=()
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -471,7 +471,7 @@ fn convert_wgsl() {
Targets::SPIRV | Targets::METAL | Targets::HLSL | Targets::WGSL | Targets::GLSL,
),
("extra", Targets::SPIRV | Targets::METAL | Targets::WGSL),
- ("push-constants", Targets::GLSL),
+ ("push-constants", Targets::GLSL | Targets::HLSL),
(
"operators",
Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL,
|
[hlsl-out] Implement push constants
Tracking issue for implementing push constants for the HLSL backend
https://github.com/gfx-rs/naga/blob/f90e563c281cfc71c794e0426ebcced9e3999202/src/back/hlsl/writer.rs#L583
|
2022-07-11T01:36:08Z
|
0.9
|
2022-08-29T10:58:03Z
|
4f8db997b0b1e73fc1e2cac070485333a5b61925
|
[
"convert_wgsl"
] |
[
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::layout::test_logical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::nan_handling",
"front::glsl::constants::tests::unary_op",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_numbers",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::tests::parse_parentheses_switch",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::test_matrix_size",
"proc::namer::test",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_struct_instantiation",
"proc::typifier::test_error_size",
"front::glsl::parser_tests::declarations",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_query",
"span::span_location",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"sampler1d",
"geometry",
"storage1d",
"cube_array",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"break_if_bad_condition",
"bad_texture_sample_type",
"inconsistent_binding",
"invalid_integer",
"invalid_float",
"bad_type_cast",
"constructor_parameter_type_mismatch",
"invalid_arrays",
"bad_texture",
"dead_code",
"invalid_texture_sample_type",
"last_case_falltrough",
"invalid_local_vars",
"local_var_missing_type",
"invalid_access",
"invalid_structs",
"matrix_with_bad_type",
"let_type_mismatch",
"invalid_runtime_sized_arrays",
"missing_default_case",
"reserved_identifier_prefix",
"negative_index",
"struct_member_align_too_low",
"misplaced_break_if",
"pointer_type_equivalence",
"missing_bindings",
"type_not_constructible",
"struct_member_non_po2_align",
"struct_member_size_too_low",
"invalid_functions",
"unknown_attribute",
"postfix_pointers",
"module_scope_identifier_redefinition",
"unknown_access",
"reserved_keyword",
"unknown_built_in",
"type_not_inferrable",
"unknown_ident",
"unexpected_constructor_parameters",
"unknown_conservative_depth",
"unknown_storage_class",
"unknown_type",
"unknown_scalar_type",
"select",
"unknown_local_function",
"unknown_identifier",
"unknown_storage_format",
"var_type_mismatch",
"valid_access",
"host_shareable_types",
"wrong_access_mode",
"io_shareable_types",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 565)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 586)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 142)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,993
|
gfx-rs__naga-1993
|
[
"1831"
] |
ea832a9eec13560560c017072d4318d5d942e5e5
|
diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs
--- a/src/back/dot/mod.rs
+++ b/src/back/dot/mod.rs
@@ -81,11 +81,15 @@ impl StatementGraph {
S::Loop {
ref body,
ref continuing,
+ break_if,
} => {
let body_id = self.add(body);
self.flow.push((id, body_id, "body"));
let continuing_id = self.add(continuing);
self.flow.push((body_id, continuing_id, "continuing"));
+ if let Some(expr) = break_if {
+ self.dependencies.push((id, expr, "break if"));
+ }
"Loop"
}
S::Return { value } => {
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1800,15 +1800,24 @@ impl<'a, W: Write> Writer<'a, W> {
Statement::Loop {
ref body,
ref continuing,
+ break_if,
} => {
- if !continuing.is_empty() {
+ if !continuing.is_empty() || break_if.is_some() {
let gate_name = self.namer.call("loop_init");
writeln!(self.out, "{}bool {} = true;", level, gate_name)?;
writeln!(self.out, "{}while(true) {{", level)?;
let l2 = level.next();
+ let l3 = l2.next();
writeln!(self.out, "{}if (!{}) {{", l2, gate_name)?;
for sta in continuing {
- self.write_stmt(sta, ctx, l2.next())?;
+ self.write_stmt(sta, ctx, l3)?;
+ }
+ if let Some(condition) = break_if {
+ write!(self.out, "{}if (", l3)?;
+ self.write_expr(condition, ctx)?;
+ writeln!(self.out, ") {{")?;
+ writeln!(self.out, "{}break;", l3.next())?;
+ writeln!(self.out, "{}}}", l3)?;
}
writeln!(self.out, "{}}}", l2)?;
writeln!(self.out, "{}{} = false;", level.next(), gate_name)?;
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -1497,18 +1497,27 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
Statement::Loop {
ref body,
ref continuing,
+ break_if,
} => {
let l2 = level.next();
- if !continuing.is_empty() {
+ if !continuing.is_empty() || break_if.is_some() {
let gate_name = self.namer.call("loop_init");
writeln!(self.out, "{}bool {} = true;", level, gate_name)?;
writeln!(self.out, "{}while(true) {{", level)?;
writeln!(self.out, "{}if (!{}) {{", l2, gate_name)?;
+ let l3 = l2.next();
for sta in continuing.iter() {
- self.write_stmt(module, sta, func_ctx, l2.next())?;
+ self.write_stmt(module, sta, func_ctx, l3)?;
}
- writeln!(self.out, "{}}}", level.next())?;
- writeln!(self.out, "{}{} = false;", level.next(), gate_name)?;
+ if let Some(condition) = break_if {
+ write!(self.out, "{}if (", l3)?;
+ self.write_expr(module, condition, func_ctx)?;
+ writeln!(self.out, ") {{")?;
+ writeln!(self.out, "{}break;", l3.next())?;
+ writeln!(self.out, "{}}}", l3)?;
+ }
+ writeln!(self.out, "{}}}", l2)?;
+ writeln!(self.out, "{}{} = false;", l2, gate_name)?;
} else {
writeln!(self.out, "{}while(true) {{", level)?;
}
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -2552,14 +2552,23 @@ impl<W: Write> Writer<W> {
crate::Statement::Loop {
ref body,
ref continuing,
+ break_if,
} => {
- if !continuing.is_empty() {
+ if !continuing.is_empty() || break_if.is_some() {
let gate_name = self.namer.call("loop_init");
writeln!(self.out, "{}bool {} = true;", level, gate_name)?;
writeln!(self.out, "{}while(true) {{", level)?;
let lif = level.next();
+ let lcontinuing = lif.next();
writeln!(self.out, "{}if (!{}) {{", lif, gate_name)?;
- self.put_block(lif.next(), continuing, context)?;
+ self.put_block(lcontinuing, continuing, context)?;
+ if let Some(condition) = break_if {
+ write!(self.out, "{}if (", lcontinuing)?;
+ self.put_expression(condition, &context.expression, true)?;
+ writeln!(self.out, ") {{")?;
+ writeln!(self.out, "{}break;", lcontinuing.next())?;
+ writeln!(self.out, "{}}}", lcontinuing)?;
+ }
writeln!(self.out, "{}}}", lif)?;
writeln!(self.out, "{}{} = false;", lif, gate_name)?;
} else {
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -37,6 +37,28 @@ enum ExpressionPointer {
},
}
+/// The termination statement to be added to the end of the block
+pub enum BlockExit {
+ /// Generates an OpReturn (void return)
+ Return,
+ /// Generates an OpBranch to the specified block
+ Branch {
+ /// The branch target block
+ target: Word,
+ },
+ /// Translates a loop `break if` into an `OpBranchConditional` to the
+ /// merge block if true (the merge block is passed through [`LoopContext::break_id`]
+ /// or else to the loop header (passed through [`preamble_id`])
+ ///
+ /// [`preamble_id`]: Self::BreakIf::preamble_id
+ BreakIf {
+ /// The condition of the `break if`
+ condition: Handle<crate::Expression>,
+ /// The loop header block id
+ preamble_id: Word,
+ },
+}
+
impl Writer {
// Flip Y coordinate to adjust for coordinate space difference
// between SPIR-V and our IR.
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1491,7 +1513,7 @@ impl<'w> BlockContext<'w> {
&mut self,
label_id: Word,
statements: &[crate::Statement],
- exit_id: Option<Word>,
+ exit: BlockExit,
loop_context: LoopContext,
) -> Result<(), Error> {
let mut block = Block::new(label_id);
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1508,7 +1530,12 @@ impl<'w> BlockContext<'w> {
self.function.consume(block, Instruction::branch(scope_id));
let merge_id = self.gen_id();
- self.write_block(scope_id, block_statements, Some(merge_id), loop_context)?;
+ self.write_block(
+ scope_id,
+ block_statements,
+ BlockExit::Branch { target: merge_id },
+ loop_context,
+ )?;
block = Block::new(merge_id);
}
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1546,10 +1573,20 @@ impl<'w> BlockContext<'w> {
);
if let Some(block_id) = accept_id {
- self.write_block(block_id, accept, Some(merge_id), loop_context)?;
+ self.write_block(
+ block_id,
+ accept,
+ BlockExit::Branch { target: merge_id },
+ loop_context,
+ )?;
}
if let Some(block_id) = reject_id {
- self.write_block(block_id, reject, Some(merge_id), loop_context)?;
+ self.write_block(
+ block_id,
+ reject,
+ BlockExit::Branch { target: merge_id },
+ loop_context,
+ )?;
}
block = Block::new(merge_id);
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1611,7 +1648,9 @@ impl<'w> BlockContext<'w> {
self.write_block(
*label_id,
&case.body,
- Some(case_finish_id),
+ BlockExit::Branch {
+ target: case_finish_id,
+ },
inner_context,
)?;
}
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1619,7 +1658,12 @@ impl<'w> BlockContext<'w> {
// If no default was encountered write a empty block to satisfy the presence of
// a block the default label
if !reached_default {
- self.write_block(default_id, &[], Some(merge_id), inner_context)?;
+ self.write_block(
+ default_id,
+ &[],
+ BlockExit::Branch { target: merge_id },
+ inner_context,
+ )?;
}
block = Block::new(merge_id);
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1627,6 +1671,7 @@ impl<'w> BlockContext<'w> {
crate::Statement::Loop {
ref body,
ref continuing,
+ break_if,
} => {
let preamble_id = self.gen_id();
self.function
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1649,17 +1694,29 @@ impl<'w> BlockContext<'w> {
self.write_block(
body_id,
body,
- Some(continuing_id),
+ BlockExit::Branch {
+ target: continuing_id,
+ },
LoopContext {
continuing_id: Some(continuing_id),
break_id: Some(merge_id),
},
)?;
+ let exit = match break_if {
+ Some(condition) => BlockExit::BreakIf {
+ condition,
+ preamble_id,
+ },
+ None => BlockExit::Branch {
+ target: preamble_id,
+ },
+ };
+
self.write_block(
continuing_id,
continuing,
- Some(preamble_id),
+ exit,
LoopContext {
continuing_id: None,
break_id: Some(merge_id),
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1955,12 +2012,10 @@ impl<'w> BlockContext<'w> {
}
}
- let termination = match exit_id {
- Some(id) => Instruction::branch(id),
- // This can happen if the last branch had all the paths
- // leading out of the graph (i.e. returning).
- // Or it may be the end of the self.function.
- None => match self.ir_function.result {
+ let termination = match exit {
+ // We're generating code for the top-level Block of the function, so we
+ // need to end it with some kind of return instruction.
+ BlockExit::Return => match self.ir_function.result {
Some(ref result) if self.function.entry_point_context.is_none() => {
let type_id = self.get_type_id(LookupType::Handle(result.ty));
let null_id = self.writer.write_constant_null(type_id);
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1968,6 +2023,19 @@ impl<'w> BlockContext<'w> {
}
_ => Instruction::return_void(),
},
+ BlockExit::Branch { target } => Instruction::branch(target),
+ BlockExit::BreakIf {
+ condition,
+ preamble_id,
+ } => {
+ let condition_id = self.cached[condition];
+
+ Instruction::branch_conditional(
+ condition_id,
+ loop_context.break_id.unwrap(),
+ preamble_id,
+ )
+ }
};
self.function.consume(block, termination);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -574,7 +574,12 @@ impl Writer {
context
.function
.consume(prelude, Instruction::branch(main_id));
- context.write_block(main_id, &ir_function.body, None, LoopContext::default())?;
+ context.write_block(
+ main_id,
+ &ir_function.body,
+ super::block::BlockExit::Return,
+ LoopContext::default(),
+ )?;
// Consume the `BlockContext`, ending its borrows and letting the
// `Writer` steal back its cached expression table and temp_list.
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -908,6 +908,7 @@ impl<W: Write> Writer<W> {
Statement::Loop {
ref body,
ref continuing,
+ break_if,
} => {
write!(self.out, "{}", level)?;
writeln!(self.out, "loop {{")?;
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -917,11 +918,26 @@ impl<W: Write> Writer<W> {
self.write_stmt(module, sta, func_ctx, l2)?;
}
- if !continuing.is_empty() {
+ // The continuing is optional so we don't need to write it if
+ // it is empty, but the `break if` counts as a continuing statement
+ // so even if `continuing` is empty we must generate it if a
+ // `break if` exists
+ if !continuing.is_empty() || break_if.is_some() {
writeln!(self.out, "{}continuing {{", l2)?;
for sta in continuing.iter() {
self.write_stmt(module, sta, func_ctx, l2.next())?;
}
+
+ // The `break if` is always the last
+ // statement of the `continuing` block
+ if let Some(condition) = break_if {
+ // The trailing space is important
+ write!(self.out, "{}break if ", l2.next())?;
+ self.write_expr(module, condition, func_ctx)?;
+ // Close the `break if` statement
+ writeln!(self.out, ";")?;
+ }
+
writeln!(self.out, "{}}}", l2)?;
}
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -358,6 +358,7 @@ impl<'source> ParsingContext<'source> {
Statement::Loop {
body: loop_body,
continuing: Block::new(),
+ break_if: None,
},
meta,
);
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -411,6 +412,7 @@ impl<'source> ParsingContext<'source> {
Statement::Loop {
body: loop_body,
continuing: Block::new(),
+ break_if: None,
},
meta,
);
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -513,6 +515,7 @@ impl<'source> ParsingContext<'source> {
Statement::Loop {
body: block,
continuing,
+ break_if: None,
},
meta,
);
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -556,7 +556,11 @@ impl<'function> BlockContext<'function> {
let continuing = lower_impl(blocks, bodies, continuing);
block.push(
- crate::Statement::Loop { body, continuing },
+ crate::Statement::Loop {
+ body,
+ continuing,
+ break_if: None,
+ },
crate::Span::default(),
)
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -3565,6 +3565,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
S::Loop {
ref mut body,
ref mut continuing,
+ break_if: _,
} => {
self.patch_statements(body, expressions, fun_parameter_sampling)?;
self.patch_statements(continuing, expressions, fun_parameter_sampling)?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -125,6 +125,8 @@ pub enum Error<'a> {
BadIncrDecrReferenceType(Span),
InvalidResolve(ResolveError),
InvalidForInitializer(Span),
+ /// A break if appeared outside of a continuing block
+ InvalidBreakIf(Span),
InvalidGatherComponent(Span, u32),
InvalidConstructorComponentType(Span, i32),
InvalidIdentifierUnderscore(Span),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -307,6 +309,11 @@ impl<'a> Error<'a> {
labels: vec![(bad_span.clone(), "not an assignment or function call".into())],
notes: vec![],
},
+ Error::InvalidBreakIf(ref bad_span) => ParseError {
+ message: "A break if is only allowed in a continuing block".to_string(),
+ labels: vec![(bad_span.clone(), "not in a continuing block".into())],
+ notes: vec![],
+ },
Error::InvalidGatherComponent(ref bad_span, component) => ParseError {
message: format!("textureGather component {} doesn't exist, must be 0, 1, 2, or 3", component),
labels: vec![(bad_span.clone(), "invalid component".into())],
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3811,26 +3818,7 @@ impl Parser {
Some(crate::Statement::Switch { selector, cases })
}
- "loop" => {
- let _ = lexer.next();
- let mut body = crate::Block::new();
- let mut continuing = crate::Block::new();
- lexer.expect(Token::Paren('{'))?;
-
- loop {
- if lexer.skip(Token::Word("continuing")) {
- continuing = self.parse_block(lexer, context.reborrow(), false)?;
- lexer.expect(Token::Paren('}'))?;
- break;
- }
- if lexer.skip(Token::Paren('}')) {
- break;
- }
- self.parse_statement(lexer, context.reborrow(), &mut body, false)?;
- }
-
- Some(crate::Statement::Loop { body, continuing })
- }
+ "loop" => Some(self.parse_loop(lexer, context.reborrow(), &mut emitter)?),
"while" => {
let _ = lexer.next();
let mut body = crate::Block::new();
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3863,6 +3851,7 @@ impl Parser {
Some(crate::Statement::Loop {
body,
continuing: crate::Block::new(),
+ break_if: None,
})
}
"for" => {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3935,10 +3924,22 @@ impl Parser {
self.parse_statement(lexer, context.reborrow(), &mut body, false)?;
}
- Some(crate::Statement::Loop { body, continuing })
+ Some(crate::Statement::Loop {
+ body,
+ continuing,
+ break_if: None,
+ })
}
"break" => {
- let _ = lexer.next();
+ let (_, mut span) = lexer.next();
+ // Check if the next token is an `if`, this indicates
+ // that the user tried to type out a `break if` which
+ // is illegal in this position.
+ let (peeked_token, peeked_span) = lexer.peek();
+ if let Token::Word("if") = peeked_token {
+ span.end = peeked_span.end;
+ return Err(Error::InvalidBreakIf(span));
+ }
Some(crate::Statement::Break)
}
"continue" => {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4041,6 +4042,84 @@ impl Parser {
Ok(())
}
+ fn parse_loop<'a>(
+ &mut self,
+ lexer: &mut Lexer<'a>,
+ mut context: StatementContext<'a, '_, '_>,
+ emitter: &mut super::Emitter,
+ ) -> Result<crate::Statement, Error<'a>> {
+ let _ = lexer.next();
+ let mut body = crate::Block::new();
+ let mut continuing = crate::Block::new();
+ let mut break_if = None;
+ lexer.expect(Token::Paren('{'))?;
+
+ loop {
+ if lexer.skip(Token::Word("continuing")) {
+ // Branch for the `continuing` block, this must be
+ // the last thing in the loop body
+
+ // Expect a opening brace to start the continuing block
+ lexer.expect(Token::Paren('{'))?;
+ loop {
+ if lexer.skip(Token::Word("break")) {
+ // Branch for the `break if` statement, this statement
+ // has the form `break if <expr>;` and must be the last
+ // statement in a continuing block
+
+ // The break must be followed by an `if` to form
+ // the break if
+ lexer.expect(Token::Word("if"))?;
+
+ // Start the emitter to begin parsing an expression
+ emitter.start(context.expressions);
+ let condition = self.parse_general_expression(
+ lexer,
+ context.as_expression(&mut body, emitter),
+ )?;
+ // Add all emits to the continuing body
+ continuing.extend(emitter.finish(context.expressions));
+ // Set the condition of the break if to the newly parsed
+ // expression
+ break_if = Some(condition);
+
+ // Expext a semicolon to close the statement
+ lexer.expect(Token::Separator(';'))?;
+ // Expect a closing brace to close the continuing block,
+ // since the break if must be the last statement
+ lexer.expect(Token::Paren('}'))?;
+ // Stop parsing the continuing block
+ break;
+ } else if lexer.skip(Token::Paren('}')) {
+ // If we encounter a closing brace it means we have reached
+ // the end of the continuing block and should stop processing
+ break;
+ } else {
+ // Otherwise try to parse a statement
+ self.parse_statement(lexer, context.reborrow(), &mut continuing, false)?;
+ }
+ }
+ // Since the continuing block must be the last part of the loop body,
+ // we expect to see a closing brace to end the loop body
+ lexer.expect(Token::Paren('}'))?;
+ break;
+ }
+ if lexer.skip(Token::Paren('}')) {
+ // If we encounter a closing brace it means we have reached
+ // the end of the loop body and should stop processing
+ break;
+ }
+ // Otherwise try to parse a statement
+ self.parse_statement(lexer, context.reborrow(), &mut body, false)?;
+ }
+
+ Ok(crate::Statement::Loop {
+ body,
+ continuing,
+ break_if,
+ })
+ }
+
fn parse_block<'a>(
&mut self,
lexer: &mut Lexer<'a>,
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1439,11 +1439,23 @@ pub enum Statement {
/// this loop. (It may have `Break` and `Continue` statements targeting
/// loops or switches nested within the `continuing` block.)
///
+ /// If present, `break_if` is an expression which is evaluated after the
+ /// continuing block. If its value is true, control continues after the
+ /// `Loop` statement, rather than branching back to the top of body as
+ /// usual. The `break_if` expression corresponds to a "break if" statement
+ /// in WGSL, or a loop whose back edge is an `OpBranchConditional`
+ /// instruction in SPIR-V.
+ ///
/// [`Break`]: Statement::Break
/// [`Continue`]: Statement::Continue
/// [`Kill`]: Statement::Kill
/// [`Return`]: Statement::Return
- Loop { body: Block, continuing: Block },
+ /// [`break if`]: Self::Loop::break_if
+ Loop {
+ body: Block,
+ continuing: Block,
+ break_if: Option<Handle<Expression>>,
+ },
/// Exits the innermost enclosing [`Loop`] or [`Switch`].
///
diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs
--- a/src/valid/analyzer.rs
+++ b/src/valid/analyzer.rs
@@ -841,6 +841,7 @@ impl FunctionInfo {
S::Loop {
ref body,
ref continuing,
+ break_if: _,
} => {
let body_uniformity =
self.process_block(body, other_functions, disruptor, expression_arena)?;
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -499,6 +499,7 @@ impl super::Validator {
S::Loop {
ref body,
ref continuing,
+ break_if,
} => {
// special handling for block scoping is needed here,
// because the continuing{} block inherits the scope
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -520,6 +521,20 @@ impl super::Validator {
&context.with_abilities(ControlFlowAbility::empty()),
)?
.stages;
+
+ if let Some(condition) = break_if {
+ match *context.resolve_type(condition, &self.valid_expression_set)? {
+ Ti::Scalar {
+ kind: crate::ScalarKind::Bool,
+ width: _,
+ } => {}
+ _ => {
+ return Err(FunctionError::InvalidIfType(condition)
+ .with_span_handle(condition, context.expressions))
+ }
+ }
+ }
+
for handle in self.valid_expression_list.drain(base_expression_count..) {
self.valid_expression_set.remove(handle.index());
}
|
diff --git /dev/null b/tests/in/break-if.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/in/break-if.wgsl
@@ -0,0 +1,32 @@
+@compute @workgroup_size(1)
+fn main() {}
+
+fn breakIfEmpty() {
+ loop {
+ continuing {
+ break if true;
+ }
+ }
+}
+
+fn breakIfEmptyBody(a: bool) {
+ loop {
+ continuing {
+ var b = a;
+ var c = a != b;
+
+ break if a == c;
+ }
+ }
+}
+
+fn breakIf(a: bool) {
+ loop {
+ var d = a;
+ var e = a != d;
+
+ continuing {
+ break if a == e;
+ }
+ }
+}
diff --git /dev/null b/tests/out/glsl/break-if.main.Compute.glsl
new file mode 100644
--- /dev/null
+++ b/tests/out/glsl/break-if.main.Compute.glsl
@@ -0,0 +1,65 @@
+#version 310 es
+
+precision highp float;
+precision highp int;
+
+layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
+
+
+void breakIfEmpty() {
+ bool loop_init = true;
+ while(true) {
+ if (!loop_init) {
+ if (true) {
+ break;
+ }
+ }
+ loop_init = false;
+ }
+ return;
+}
+
+void breakIfEmptyBody(bool a) {
+ bool b = false;
+ bool c = false;
+ bool loop_init_1 = true;
+ while(true) {
+ if (!loop_init_1) {
+ b = a;
+ bool _e2 = b;
+ c = (a != _e2);
+ bool _e5 = c;
+ bool unnamed = (a == _e5);
+ if (unnamed) {
+ break;
+ }
+ }
+ loop_init_1 = false;
+ }
+ return;
+}
+
+void breakIf(bool a_1) {
+ bool d = false;
+ bool e = false;
+ bool loop_init_2 = true;
+ while(true) {
+ if (!loop_init_2) {
+ bool _e5 = e;
+ bool unnamed_1 = (a_1 == _e5);
+ if (unnamed_1) {
+ break;
+ }
+ }
+ loop_init_2 = false;
+ d = a_1;
+ bool _e2 = d;
+ e = (a_1 != _e2);
+ }
+ return;
+}
+
+void main() {
+ return;
+}
+
diff --git /dev/null b/tests/out/hlsl/break-if.hlsl
new file mode 100644
--- /dev/null
+++ b/tests/out/hlsl/break-if.hlsl
@@ -0,0 +1,64 @@
+
+void breakIfEmpty()
+{
+ bool loop_init = true;
+ while(true) {
+ if (!loop_init) {
+ if (true) {
+ break;
+ }
+ }
+ loop_init = false;
+ }
+ return;
+}
+
+void breakIfEmptyBody(bool a)
+{
+ bool b = (bool)0;
+ bool c = (bool)0;
+
+ bool loop_init_1 = true;
+ while(true) {
+ if (!loop_init_1) {
+ b = a;
+ bool _expr2 = b;
+ c = (a != _expr2);
+ bool _expr5 = c;
+ bool unnamed = (a == _expr5);
+ if (unnamed) {
+ break;
+ }
+ }
+ loop_init_1 = false;
+ }
+ return;
+}
+
+void breakIf(bool a_1)
+{
+ bool d = (bool)0;
+ bool e = (bool)0;
+
+ bool loop_init_2 = true;
+ while(true) {
+ if (!loop_init_2) {
+ bool _expr5 = e;
+ bool unnamed_1 = (a_1 == _expr5);
+ if (unnamed_1) {
+ break;
+ }
+ }
+ loop_init_2 = false;
+ d = a_1;
+ bool _expr2 = d;
+ e = (a_1 != _expr2);
+ }
+ return;
+}
+
+[numthreads(1, 1, 1)]
+void main()
+{
+ return;
+}
diff --git /dev/null b/tests/out/hlsl/break-if.hlsl.config
new file mode 100644
--- /dev/null
+++ b/tests/out/hlsl/break-if.hlsl.config
@@ -0,0 +1,3 @@
+vertex=()
+fragment=()
+compute=(main:cs_5_1 )
diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron
--- a/tests/out/ir/collatz.ron
+++ b/tests/out/ir/collatz.ron
@@ -261,6 +261,7 @@
),
],
continuing: [],
+ break_if: None,
),
Emit((
start: 24,
diff --git a/tests/out/ir/shadow.ron b/tests/out/ir/shadow.ron
--- a/tests/out/ir/shadow.ron
+++ b/tests/out/ir/shadow.ron
@@ -1320,6 +1320,7 @@
value: 120,
),
],
+ break_if: None,
),
Emit((
start: 120,
diff --git /dev/null b/tests/out/msl/break-if.msl
new file mode 100644
--- /dev/null
+++ b/tests/out/msl/break-if.msl
@@ -0,0 +1,69 @@
+// language: metal2.0
+#include <metal_stdlib>
+#include <simd/simd.h>
+
+using metal::uint;
+
+
+void breakIfEmpty(
+) {
+ bool loop_init = true;
+ while(true) {
+ if (!loop_init) {
+ if (true) {
+ break;
+ }
+ }
+ loop_init = false;
+ }
+ return;
+}
+
+void breakIfEmptyBody(
+ bool a
+) {
+ bool b = {};
+ bool c = {};
+ bool loop_init_1 = true;
+ while(true) {
+ if (!loop_init_1) {
+ b = a;
+ bool _e2 = b;
+ c = a != _e2;
+ bool _e5 = c;
+ bool unnamed = a == _e5;
+ if (a == c) {
+ break;
+ }
+ }
+ loop_init_1 = false;
+ }
+ return;
+}
+
+void breakIf(
+ bool a_1
+) {
+ bool d = {};
+ bool e = {};
+ bool loop_init_2 = true;
+ while(true) {
+ if (!loop_init_2) {
+ bool _e5 = e;
+ bool unnamed_1 = a_1 == _e5;
+ if (a_1 == e) {
+ break;
+ }
+ }
+ loop_init_2 = false;
+ d = a_1;
+ bool _e2 = d;
+ e = a_1 != _e2;
+ }
+ return;
+}
+
+kernel void main_(
+) {
+ return;
+}
diff --git /dev/null b/tests/out/spv/break-if.spvasm
new file mode 100644
--- /dev/null
+++ b/tests/out/spv/break-if.spvasm
@@ -0,0 +1,88 @@
+; SPIR-V
+; Version: 1.1
+; Generator: rspirv
+; Bound: 50
+OpCapability Shader
+%1 = OpExtInstImport "GLSL.std.450"
+OpMemoryModel Logical GLSL450
+OpEntryPoint GLCompute %48 "main"
+OpExecutionMode %48 LocalSize 1 1 1
+%2 = OpTypeVoid
+%4 = OpTypeBool
+%3 = OpConstantTrue %4
+%7 = OpTypeFunction %2
+%14 = OpTypePointer Function %4
+%15 = OpConstantNull %4
+%17 = OpConstantNull %4
+%21 = OpTypeFunction %2 %4
+%32 = OpConstantNull %4
+%34 = OpConstantNull %4
+%6 = OpFunction %2 None %7
+%5 = OpLabel
+OpBranch %8
+%8 = OpLabel
+OpBranch %9
+%9 = OpLabel
+OpLoopMerge %10 %12 None
+OpBranch %11
+%11 = OpLabel
+OpBranch %12
+%12 = OpLabel
+OpBranchConditional %3 %10 %9
+%10 = OpLabel
+OpReturn
+OpFunctionEnd
+%20 = OpFunction %2 None %21
+%19 = OpFunctionParameter %4
+%18 = OpLabel
+%13 = OpVariable %14 Function %15
+%16 = OpVariable %14 Function %17
+OpBranch %22
+%22 = OpLabel
+OpBranch %23
+%23 = OpLabel
+OpLoopMerge %24 %26 None
+OpBranch %25
+%25 = OpLabel
+OpBranch %26
+%26 = OpLabel
+OpStore %13 %19
+%27 = OpLoad %4 %13
+%28 = OpLogicalNotEqual %4 %19 %27
+OpStore %16 %28
+%29 = OpLoad %4 %16
+%30 = OpLogicalEqual %4 %19 %29
+OpBranchConditional %30 %24 %23
+%24 = OpLabel
+OpReturn
+OpFunctionEnd
+%37 = OpFunction %2 None %21
+%36 = OpFunctionParameter %4
+%35 = OpLabel
+%31 = OpVariable %14 Function %32
+%33 = OpVariable %14 Function %34
+OpBranch %38
+%38 = OpLabel
+OpBranch %39
+%39 = OpLabel
+OpLoopMerge %40 %42 None
+OpBranch %41
+%41 = OpLabel
+OpStore %31 %36
+%43 = OpLoad %4 %31
+%44 = OpLogicalNotEqual %4 %36 %43
+OpStore %33 %44
+OpBranch %42
+%42 = OpLabel
+%45 = OpLoad %4 %33
+%46 = OpLogicalEqual %4 %36 %45
+OpBranchConditional %46 %40 %39
+%40 = OpLabel
+OpReturn
+OpFunctionEnd
+%48 = OpFunction %2 None %7
+%47 = OpLabel
+OpBranch %49
+%49 = OpLabel
+OpReturn
+OpFunctionEnd
\ No newline at end of file
diff --git /dev/null b/tests/out/wgsl/break-if.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/out/wgsl/break-if.wgsl
@@ -0,0 +1,47 @@
+fn breakIfEmpty() {
+ loop {
+ continuing {
+ break if true;
+ }
+ }
+ return;
+}
+
+fn breakIfEmptyBody(a: bool) {
+ var b: bool;
+ var c: bool;
+
+ loop {
+ continuing {
+ b = a;
+ let _e2 = b;
+ c = (a != _e2);
+ let _e5 = c;
+ _ = (a == _e5);
+ break if (a == _e5);
+ }
+ }
+ return;
+}
+
+fn breakIf(a_1: bool) {
+ var d: bool;
+ var e: bool;
+
+ loop {
+ d = a_1;
+ let _e2 = d;
+ e = (a_1 != _e2);
+ continuing {
+ let _e5 = e;
+ _ = (a_1 == _e5);
+ break if (a_1 == _e5);
+ }
+ }
+ return;
+}
+
+@compute @workgroup_size(1, 1, 1)
+fn main() {
+ return;
+}
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -527,6 +527,10 @@ fn convert_wgsl() {
"binding-arrays",
Targets::WGSL | Targets::HLSL | Targets::METAL | Targets::SPIRV,
),
+ (
+ "break-if",
+ Targets::WGSL | Targets::GLSL | Targets::SPIRV | Targets::HLSL | Targets::METAL,
+ ),
];
for &(name, targets) in inputs.iter() {
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -1556,3 +1556,44 @@ fn host_shareable_types() {
}
}
}
+
+#[test]
+fn misplaced_break_if() {
+ check(
+ "
+ fn test_misplaced_break_if() {
+ loop {
+ break if true;
+ }
+ }
+ ",
+ r###"error: A break if is only allowed in a continuing block
+ ┌─ wgsl:4:17
+ │
+4 │ break if true;
+ │ ^^^^^^^^ not in a continuing block
+
+"###,
+ );
+}
+
+#[test]
+fn break_if_bad_condition() {
+ check_validation! {
+ "
+ fn test_break_if_bad_condition() {
+ loop {
+ continuing {
+ break if 1;
+ }
+ }
+ }
+ ":
+ Err(
+ naga::valid::ValidationError::Function {
+ error: naga::valid::FunctionError::InvalidIfType(_),
+ ..
+ },
+ )
+ }
+}
|
[wgsl-in] Add break-if as optional at end of continuing
Spec PR: https://github.com/gpuweb/gpuweb/pull/2618
|
2022-06-17T23:05:15Z
|
0.8
|
2022-06-25T00:47:08Z
|
ea832a9eec13560560c017072d4318d5d942e5e5
|
[
"convert_wgsl",
"break_if_bad_condition",
"misplaced_break_if"
] |
[
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::msl::test_error_size",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::spv::layout::test_logical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::nan_handling",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::spv::test::parse",
"front::wgsl::lexer::test_numbers",
"front::glsl::parser_tests::version",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::constants",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::tests::parse_parentheses_switch",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_pointers",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_loop",
"proc::namer::test",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::test_matrix_size",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_texture_query",
"front::glsl::parser_tests::declarations",
"span::span_location",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"cube_array",
"sampler1d",
"geometry",
"storage1d",
"sample_rate_shading",
"storage_image_formats",
"image_queries",
"bad_texture_sample_type",
"function_without_identifier",
"bad_for_initializer",
"inconsistent_binding",
"invalid_integer",
"bad_type_cast",
"dead_code",
"invalid_float",
"constructor_parameter_type_mismatch",
"bad_texture",
"invalid_texture_sample_type",
"invalid_arrays",
"invalid_structs",
"local_var_missing_type",
"invalid_local_vars",
"invalid_access",
"last_case_falltrough",
"invalid_runtime_sized_arrays",
"reserved_identifier_prefix",
"matrix_with_bad_type",
"let_type_mismatch",
"missing_default_case",
"negative_index",
"struct_member_align_too_low",
"pointer_type_equivalence",
"struct_member_non_po2_align",
"invalid_functions",
"struct_member_size_too_low",
"type_not_constructible",
"type_not_inferrable",
"unexpected_constructor_parameters",
"missing_bindings",
"postfix_pointers",
"unknown_attribute",
"module_scope_identifier_redefinition",
"unknown_built_in",
"unknown_conservative_depth",
"unknown_access",
"unknown_scalar_type",
"unknown_ident",
"unknown_storage_class",
"unknown_storage_format",
"unknown_identifier",
"unknown_type",
"unknown_local_function",
"reserved_keyword",
"host_shareable_types",
"select",
"var_type_mismatch",
"wrong_access_mode",
"valid_access",
"io_shareable_types",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 586)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 565)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 142)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,917
|
gfx-rs__naga-1917
|
[
"1896"
] |
ab2806e05fbd69a502b4b25a85f99ae4d3e82278
|
diff --git a/src/front/wgsl/construction.rs b/src/front/wgsl/construction.rs
--- a/src/front/wgsl/construction.rs
+++ b/src/front/wgsl/construction.rs
@@ -184,12 +184,15 @@ fn parse_constructor_type<'a>(
Ok(Some(ConstructorType::Vector { size, kind, width }))
}
(Token::Paren('<'), ConstructorType::PartialMatrix { columns, rows }) => {
- let (_, width) = lexer.next_scalar_generic()?;
- Ok(Some(ConstructorType::Matrix {
- columns,
- rows,
- width,
- }))
+ let (kind, width, span) = lexer.next_scalar_generic_with_span()?;
+ match kind {
+ ScalarKind::Float => Ok(Some(ConstructorType::Matrix {
+ columns,
+ rows,
+ width,
+ })),
+ _ => Err(Error::BadMatrixScalarKind(span, kind, width)),
+ }
}
(Token::Paren('<'), ConstructorType::PartialArray) => {
lexer.expect_generic_paren('<')?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -130,6 +130,7 @@ pub enum Error<'a> {
BadFloat(Span, BadFloatError),
BadU32Constant(Span),
BadScalarWidth(Span, Bytes),
+ BadMatrixScalarKind(Span, crate::ScalarKind, u8),
BadAccessor(Span),
BadTexture(Span),
BadTypeCast {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -296,12 +297,20 @@ impl<'a> Error<'a> {
labels: vec![(bad_span.clone(), "expected unsigned integer".into())],
notes: vec![],
},
-
Error::BadScalarWidth(ref bad_span, width) => ParseError {
message: format!("invalid width of `{}` bits for literal", width as u32 * 8,),
labels: vec![(bad_span.clone(), "invalid width".into())],
notes: vec!["the only valid width is 32 for now".to_string()],
},
+ Error::BadMatrixScalarKind(
+ ref span,
+ kind,
+ width,
+ ) => ParseError {
+ message: format!("matrix scalar type must be floating-point, but found `{}`", kind.to_wgsl(width)),
+ labels: vec![(span.clone(), "must be floating-point (e.g. `f32`)".into())],
+ notes: vec![],
+ },
Error::BadAccessor(ref accessor_span) => ParseError {
message: format!(
"invalid field accessor `{}`",
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2901,6 +2910,23 @@ impl Parser {
Ok((members, span))
}
+ fn parse_matrix_scalar_type<'a>(
+ &mut self,
+ lexer: &mut Lexer<'a>,
+ columns: crate::VectorSize,
+ rows: crate::VectorSize,
+ ) -> Result<crate::TypeInner, Error<'a>> {
+ let (kind, width, span) = lexer.next_scalar_generic_with_span()?;
+ match kind {
+ crate::ScalarKind::Float => Ok(crate::TypeInner::Matrix {
+ columns,
+ rows,
+ width,
+ }),
+ _ => Err(Error::BadMatrixScalarKind(span, kind, width)),
+ }
+ }
+
fn parse_type_decl_impl<'a>(
&mut self,
lexer: &mut Lexer<'a>,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2912,6 +2938,7 @@ impl Parser {
if let Some((kind, width)) = conv::get_scalar_type(word) {
return Ok(Some(crate::TypeInner::Scalar { kind, width }));
}
+
Ok(Some(match word {
"vec2" => {
let (kind, width) = lexer.next_scalar_generic()?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2938,77 +2965,44 @@ impl Parser {
}
}
"mat2x2" => {
- let (_, width) = lexer.next_scalar_generic()?;
- crate::TypeInner::Matrix {
- columns: crate::VectorSize::Bi,
- rows: crate::VectorSize::Bi,
- width,
- }
+ self.parse_matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Bi)?
}
"mat2x3" => {
- let (_, width) = lexer.next_scalar_generic()?;
- crate::TypeInner::Matrix {
- columns: crate::VectorSize::Bi,
- rows: crate::VectorSize::Tri,
- width,
- }
- }
- "mat2x4" => {
- let (_, width) = lexer.next_scalar_generic()?;
- crate::TypeInner::Matrix {
- columns: crate::VectorSize::Bi,
- rows: crate::VectorSize::Quad,
- width,
- }
+ self.parse_matrix_scalar_type(lexer, crate::VectorSize::Bi, crate::VectorSize::Tri)?
}
+ "mat2x4" => self.parse_matrix_scalar_type(
+ lexer,
+ crate::VectorSize::Bi,
+ crate::VectorSize::Quad,
+ )?,
"mat3x2" => {
- let (_, width) = lexer.next_scalar_generic()?;
- crate::TypeInner::Matrix {
- columns: crate::VectorSize::Tri,
- rows: crate::VectorSize::Bi,
- width,
- }
- }
- "mat3x3" => {
- let (_, width) = lexer.next_scalar_generic()?;
- crate::TypeInner::Matrix {
- columns: crate::VectorSize::Tri,
- rows: crate::VectorSize::Tri,
- width,
- }
- }
- "mat3x4" => {
- let (_, width) = lexer.next_scalar_generic()?;
- crate::TypeInner::Matrix {
- columns: crate::VectorSize::Tri,
- rows: crate::VectorSize::Quad,
- width,
- }
- }
- "mat4x2" => {
- let (_, width) = lexer.next_scalar_generic()?;
- crate::TypeInner::Matrix {
- columns: crate::VectorSize::Quad,
- rows: crate::VectorSize::Bi,
- width,
- }
- }
- "mat4x3" => {
- let (_, width) = lexer.next_scalar_generic()?;
- crate::TypeInner::Matrix {
- columns: crate::VectorSize::Quad,
- rows: crate::VectorSize::Tri,
- width,
- }
- }
- "mat4x4" => {
- let (_, width) = lexer.next_scalar_generic()?;
- crate::TypeInner::Matrix {
- columns: crate::VectorSize::Quad,
- rows: crate::VectorSize::Quad,
- width,
- }
+ self.parse_matrix_scalar_type(lexer, crate::VectorSize::Tri, crate::VectorSize::Bi)?
}
+ "mat3x3" => self.parse_matrix_scalar_type(
+ lexer,
+ crate::VectorSize::Tri,
+ crate::VectorSize::Tri,
+ )?,
+ "mat3x4" => self.parse_matrix_scalar_type(
+ lexer,
+ crate::VectorSize::Tri,
+ crate::VectorSize::Quad,
+ )?,
+ "mat4x2" => self.parse_matrix_scalar_type(
+ lexer,
+ crate::VectorSize::Quad,
+ crate::VectorSize::Bi,
+ )?,
+ "mat4x3" => self.parse_matrix_scalar_type(
+ lexer,
+ crate::VectorSize::Quad,
+ crate::VectorSize::Tri,
+ )?,
+ "mat4x4" => self.parse_matrix_scalar_type(
+ lexer,
+ crate::VectorSize::Quad,
+ crate::VectorSize::Quad,
+ )?,
"atomic" => {
let (kind, width) = lexer.next_scalar_generic()?;
crate::TypeInner::Atomic { kind, width }
|
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -810,6 +810,39 @@ fn module_scope_identifier_redefinition() {
);
}
+#[test]
+fn matrix_with_bad_type() {
+ check(
+ r#"
+ fn main() {
+ let m = mat2x2<i32>();
+ }
+ "#,
+ r#"error: matrix scalar type must be floating-point, but found `i32`
+ ┌─ wgsl:3:32
+ │
+3 │ let m = mat2x2<i32>();
+ │ ^^^ must be floating-point (e.g. `f32`)
+
+"#,
+ );
+
+ check(
+ r#"
+ fn main() {
+ let m: mat3x3<i32>;
+ }
+ "#,
+ r#"error: matrix scalar type must be floating-point, but found `i32`
+ ┌─ wgsl:3:31
+ │
+3 │ let m: mat3x3<i32>;
+ │ ^^^ must be floating-point (e.g. `f32`)
+
+"#,
+ );
+}
+
/// Check the result of validating a WGSL program against a pattern.
///
/// Unless you are generating code programmatically, the
|
[wgsl-in] Error on matrices with non float scalar kinds
The following works (on naga master cf32c2b):
````wgsl
@group(0) @binding(0)
var<storage, write> output_0: vec3<f32>;
@compute @workgroup_size(1)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
let zero: f32 = 0.0;
let zero_vec = vec3<f32>(zero,zero,zero);
let m = mat3x3<f32>(zero_vec, zero_vec, zero_vec);
}
````
````bash
% cargo run -- ./test.wgsl
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/naga ./test.wgsl`
Validation successful
````
The following shows an error (`f32` is replaced with `i32`):
````wgsl
@group(0) @binding(0)
var<storage, write> output_0: vec3<i32>;
@compute @workgroup_size(1)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
let zero: i32 = 0;
let zero_vec = vec3<i32>(zero,zero,zero);
let m = mat3x3<i32>(zero_vec, zero_vec, zero_vec);
}
````
````bash
% cargo run -- ./test.wgsl
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/naga ./test.wgsl`
[2022-05-09T19:06:29Z ERROR naga::valid::compose] Matrix component[0] type Handle([1])
error:
┌─ test.wgsl:8:9
│
8 │ let m = mat3x3<i32>(zero_vec, zero_vec, zero_vec);
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ naga::Expression [5]
Entry point main at Compute is invalid:
Expression [5] is invalid
Composing 0's component type is not expected
````
This seems... a bug, or is this just a counterintuitive aspect of the spec?
Use case: in [wonnx](https://github.com/webonnx/wonnx) we generate shaders using templates (e.g. [this one for generalized matrix multiplication](https://github.com/webonnx/wonnx/blob/master/wonnx/templates/matrix/gemm.wgsl)) to implement machine learning operators, which may use different data types (typically f32, i32 or i64) and would like to make the shaders work on all types. We often need to construct zero values (or other statically initialized values).
|
According to the latest version of the WGSL spec only floating point matrices are allowed.
See https://gpuweb.github.io/gpuweb/wgsl/#matrix-types
OK, thanks, that makes sense (I guess there's probably some platform that doesn't support it and WGSL therefore restricts to floats).
I would then suggest to improve the error messaging here (mayne it should throw an error even when just naming the type `mat3x3<i32>` as that can never be used?).
Looks like we are currently ignoring the `ScalarKind` returned by `next_scalar_generic()`.
This could be handled by introducing a new error type `BadScalarKind` (akin to the existing `BadScalarWidth`) and if we encounter any scalar kind other than `ScalarKind::Float` return the `BadScalarKind` error.
https://github.com/gfx-rs/naga/blob/cf32c2b7f38c985e1c770eeff05a91e0cd15ee04/src/front/wgsl/construction.rs#L187
https://github.com/gfx-rs/naga/blob/cf32c2b7f38c985e1c770eeff05a91e0cd15ee04/src/front/wgsl/mod.rs#L2940-L3011
|
2022-05-14T10:47:25Z
|
0.8
|
2022-05-14T15:00:16Z
|
ea832a9eec13560560c017072d4318d5d942e5e5
|
[
"matrix_with_bad_type"
] |
[
"back::msl::test_error_size",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::nan_handling",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::version",
"front::spv::test::parse",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::expressions",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_decimal_floats",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_hex_floats",
"front::glsl::parser_tests::function_overloading",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_hex_ints",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::tests::parse_decimal_ints",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_parentheses_switch",
"front::wgsl::tests::parse_pointers",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_switch",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::namer::test",
"proc::test_matrix_size",
"front::glsl::parser_tests::functions",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_switch_optional_colon_in_case",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"convert_wgsl",
"sampler1d",
"cube_array",
"storage1d",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"bad_texture_sample_type",
"inconsistent_binding",
"invalid_float",
"invalid_integer",
"bad_type_cast",
"constructor_parameter_type_mismatch",
"dead_code",
"invalid_texture_sample_type",
"last_case_falltrough",
"invalid_arrays",
"bad_texture",
"invalid_runtime_sized_arrays",
"invalid_functions",
"invalid_local_vars",
"local_var_missing_type",
"invalid_structs",
"let_type_mismatch",
"reserved_identifier_prefix",
"missing_default_case",
"invalid_access",
"module_scope_identifier_redefinition",
"missing_bindings",
"struct_member_zero_align",
"struct_member_zero_size",
"host_shareable_types",
"reserved_keyword",
"type_not_constructible",
"type_not_inferrable",
"negative_index",
"pointer_type_equivalence",
"unknown_access",
"unknown_attribute",
"unknown_conservative_depth",
"unknown_ident",
"unknown_storage_class",
"unknown_identifier",
"postfix_pointers",
"unknown_built_in",
"unknown_type",
"unknown_local_function",
"unknown_scalar_type",
"select",
"unexpected_constructor_parameters",
"var_type_mismatch",
"wrong_access_mode",
"valid_access",
"unknown_storage_format",
"io_shareable_types",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_min (line 586)",
"src/front/glsl/constants.rs - front::glsl::constants::glsl_float_max (line 565)",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 142)"
] |
[] |
[] |
gfx-rs/naga
| 1,790
|
gfx-rs__naga-1790
|
[
"1774"
] |
012f2a6b2e9328e93939429705fdf9102d9f69b7
|
diff --git /dev/null b/src/front/wgsl/construction.rs
new file mode 100644
--- /dev/null
+++ b/src/front/wgsl/construction.rs
@@ -0,0 +1,649 @@
+use crate::{
+ proc::TypeResolution, Arena, ArraySize, Bytes, Constant, ConstantInner, Expression, Handle,
+ ScalarKind, ScalarValue, Span as NagaSpan, Type, TypeInner, UniqueArena, VectorSize,
+};
+
+use super::{Error, ExpressionContext, Lexer, Parser, Scope, Span, Token};
+
+/// Represents the type of the constructor
+///
+/// Vectors, Matrices and Arrays can have partial type information
+/// which later gets inferred from the constructor parameters
+enum ConstructorType {
+ Scalar {
+ kind: ScalarKind,
+ width: Bytes,
+ },
+ PartialVector {
+ size: VectorSize,
+ },
+ Vector {
+ size: VectorSize,
+ kind: ScalarKind,
+ width: Bytes,
+ },
+ PartialMatrix {
+ columns: VectorSize,
+ rows: VectorSize,
+ },
+ Matrix {
+ columns: VectorSize,
+ rows: VectorSize,
+ width: Bytes,
+ },
+ PartialArray,
+ Array {
+ base: Handle<Type>,
+ size: ArraySize,
+ stride: u32,
+ },
+ Struct(Handle<Type>),
+}
+
+impl ConstructorType {
+ fn to_type_resolution(&self) -> Option<TypeResolution> {
+ Some(match *self {
+ ConstructorType::Scalar { kind, width } => {
+ TypeResolution::Value(TypeInner::Scalar { kind, width })
+ }
+ ConstructorType::Vector { size, kind, width } => {
+ TypeResolution::Value(TypeInner::Vector { size, kind, width })
+ }
+ ConstructorType::Matrix {
+ columns,
+ rows,
+ width,
+ } => TypeResolution::Value(TypeInner::Matrix {
+ columns,
+ rows,
+ width,
+ }),
+ ConstructorType::Array { base, size, stride } => {
+ TypeResolution::Value(TypeInner::Array { base, size, stride })
+ }
+ ConstructorType::Struct(handle) => TypeResolution::Handle(handle),
+ _ => return None,
+ })
+ }
+}
+
+impl ConstructorType {
+ fn to_error_string(&self, types: &UniqueArena<Type>, constants: &Arena<Constant>) -> String {
+ match *self {
+ ConstructorType::Scalar { kind, width } => kind.to_wgsl(width),
+ ConstructorType::PartialVector { size } => {
+ format!("vec{}<?>", size as u32,)
+ }
+ ConstructorType::Vector { size, kind, width } => {
+ format!("vec{}<{}>", size as u32, kind.to_wgsl(width))
+ }
+ ConstructorType::PartialMatrix { columns, rows } => {
+ format!("mat{}x{}<?>", columns as u32, rows as u32,)
+ }
+ ConstructorType::Matrix {
+ columns,
+ rows,
+ width,
+ } => {
+ format!(
+ "mat{}x{}<{}>",
+ columns as u32,
+ rows as u32,
+ ScalarKind::Float.to_wgsl(width)
+ )
+ }
+ ConstructorType::PartialArray => "array<?, ?>".to_string(),
+ ConstructorType::Array { base, size, .. } => {
+ format!(
+ "array<{}, {}>",
+ types[base].name.as_deref().unwrap_or("?"),
+ match size {
+ ArraySize::Constant(size) => {
+ constants[size]
+ .to_array_length()
+ .map(|len| len.to_string())
+ .unwrap_or_else(|| "?".to_string())
+ }
+ _ => unreachable!(),
+ }
+ )
+ }
+ ConstructorType::Struct(handle) => types[handle]
+ .name
+ .clone()
+ .unwrap_or_else(|| "?".to_string()),
+ }
+ }
+}
+
+fn parse_constructor_type<'a>(
+ parser: &mut Parser,
+ lexer: &mut Lexer<'a>,
+ word: &'a str,
+ type_arena: &mut UniqueArena<Type>,
+ const_arena: &mut Arena<Constant>,
+) -> Result<Option<ConstructorType>, Error<'a>> {
+ if let Some((kind, width)) = super::conv::get_scalar_type(word) {
+ return Ok(Some(ConstructorType::Scalar { kind, width }));
+ }
+
+ let partial = match word {
+ "vec2" => ConstructorType::PartialVector {
+ size: VectorSize::Bi,
+ },
+ "vec3" => ConstructorType::PartialVector {
+ size: VectorSize::Tri,
+ },
+ "vec4" => ConstructorType::PartialVector {
+ size: VectorSize::Quad,
+ },
+ "mat2x2" => ConstructorType::PartialMatrix {
+ columns: VectorSize::Bi,
+ rows: VectorSize::Bi,
+ },
+ "mat2x3" => ConstructorType::PartialMatrix {
+ columns: VectorSize::Bi,
+ rows: VectorSize::Tri,
+ },
+ "mat2x4" => ConstructorType::PartialMatrix {
+ columns: VectorSize::Bi,
+ rows: VectorSize::Quad,
+ },
+ "mat3x2" => ConstructorType::PartialMatrix {
+ columns: VectorSize::Tri,
+ rows: VectorSize::Bi,
+ },
+ "mat3x3" => ConstructorType::PartialMatrix {
+ columns: VectorSize::Tri,
+ rows: VectorSize::Tri,
+ },
+ "mat3x4" => ConstructorType::PartialMatrix {
+ columns: VectorSize::Tri,
+ rows: VectorSize::Quad,
+ },
+ "mat4x2" => ConstructorType::PartialMatrix {
+ columns: VectorSize::Quad,
+ rows: VectorSize::Bi,
+ },
+ "mat4x3" => ConstructorType::PartialMatrix {
+ columns: VectorSize::Quad,
+ rows: VectorSize::Tri,
+ },
+ "mat4x4" => ConstructorType::PartialMatrix {
+ columns: VectorSize::Quad,
+ rows: VectorSize::Quad,
+ },
+ "array" => ConstructorType::PartialArray,
+ _ => return Ok(None),
+ };
+
+ // parse component type if present
+ match (lexer.peek().0, partial) {
+ (Token::Paren('<'), ConstructorType::PartialVector { size }) => {
+ let (kind, width) = lexer.next_scalar_generic()?;
+ Ok(Some(ConstructorType::Vector { size, kind, width }))
+ }
+ (Token::Paren('<'), ConstructorType::PartialMatrix { columns, rows }) => {
+ let (_, width) = lexer.next_scalar_generic()?;
+ Ok(Some(ConstructorType::Matrix {
+ columns,
+ rows,
+ width,
+ }))
+ }
+ (Token::Paren('<'), ConstructorType::PartialArray) => {
+ lexer.expect_generic_paren('<')?;
+ let base = parser
+ .parse_type_decl(lexer, None, type_arena, const_arena)?
+ .0;
+ let size = if lexer.skip(Token::Separator(',')) {
+ let const_handle = parser.parse_const_expression(lexer, type_arena, const_arena)?;
+ ArraySize::Constant(const_handle)
+ } else {
+ ArraySize::Dynamic
+ };
+ lexer.expect_generic_paren('>')?;
+
+ let stride = {
+ parser.layouter.update(type_arena, const_arena).unwrap();
+ parser.layouter[base].to_stride()
+ };
+
+ Ok(Some(ConstructorType::Array { base, size, stride }))
+ }
+ (_, partial) => Ok(Some(partial)),
+ }
+}
+
+/// Expects [`Scope::PrimaryExpr`] scope on top; if returning Some(_), pops it.
+pub(super) fn parse_construction<'a>(
+ parser: &mut Parser,
+ lexer: &mut Lexer<'a>,
+ type_name: &'a str,
+ type_span: Span,
+ mut ctx: ExpressionContext<'a, '_, '_>,
+) -> Result<Option<Handle<Expression>>, Error<'a>> {
+ assert_eq!(
+ parser.scopes.last().map(|&(ref scope, _)| scope.clone()),
+ Some(Scope::PrimaryExpr)
+ );
+ let dst_ty = match parser.lookup_type.get(type_name) {
+ Some(&handle) => ConstructorType::Struct(handle),
+ None => match parse_constructor_type(parser, lexer, type_name, ctx.types, ctx.constants)? {
+ Some(inner) => inner,
+ None => {
+ match parser.parse_type_decl_impl(
+ lexer,
+ super::TypeAttributes::default(),
+ type_name,
+ ctx.types,
+ ctx.constants,
+ )? {
+ Some(_) => {
+ return Err(Error::TypeNotConstructible(type_span));
+ }
+ None => return Ok(None),
+ }
+ }
+ },
+ };
+
+ lexer.open_arguments()?;
+
+ let mut components = Vec::new();
+ let mut spans = Vec::new();
+
+ if lexer.peek().0 == Token::Paren(')') {
+ let _ = lexer.next();
+ } else {
+ while components.is_empty() || lexer.next_argument()? {
+ let (component, span) = lexer
+ .capture_span(|lexer| parser.parse_general_expression(lexer, ctx.reborrow()))?;
+ components.push(component);
+ spans.push(span);
+ }
+ }
+
+ enum Components<'a> {
+ None,
+ One {
+ component: Handle<Expression>,
+ span: Span,
+ ty: &'a TypeInner,
+ },
+ Many {
+ components: Vec<Handle<Expression>>,
+ spans: Vec<Span>,
+ first_component_ty: &'a TypeInner,
+ },
+ }
+
+ impl<'a> Components<'a> {
+ fn into_components_vec(self) -> Vec<Handle<Expression>> {
+ match self {
+ Components::None => vec![],
+ Components::One { component, .. } => vec![component],
+ Components::Many { components, .. } => components,
+ }
+ }
+ }
+
+ let components = match *components.as_slice() {
+ [] => Components::None,
+ [component] => {
+ ctx.resolve_type(component)?;
+ Components::One {
+ component,
+ span: spans[0].clone(),
+ ty: ctx.typifier.get(component, ctx.types),
+ }
+ }
+ [component, ..] => {
+ ctx.resolve_type(component)?;
+ Components::Many {
+ components,
+ spans,
+ first_component_ty: ctx.typifier.get(component, ctx.types),
+ }
+ }
+ };
+
+ let expr = match (components, dst_ty) {
+ // Empty constructor
+ (Components::None, dst_ty) => {
+ let ty = match dst_ty.to_type_resolution() {
+ Some(TypeResolution::Handle(handle)) => handle,
+ Some(TypeResolution::Value(inner)) => ctx
+ .types
+ .insert(Type { name: None, inner }, Default::default()),
+ None => return Err(Error::TypeNotInferrable(type_span)),
+ };
+
+ return match ctx.create_zero_value_constant(ty) {
+ Some(constant) => {
+ let span = parser.pop_scope(lexer);
+ Ok(Some(ctx.interrupt_emitter(
+ Expression::Constant(constant),
+ span.into(),
+ )))
+ }
+ None => Err(Error::TypeNotConstructible(type_span)),
+ };
+ }
+
+ // Scalar constructor & conversion (scalar -> scalar)
+ (
+ Components::One {
+ component,
+ ty: &TypeInner::Scalar { .. },
+ ..
+ },
+ ConstructorType::Scalar { kind, width },
+ ) => Expression::As {
+ expr: component,
+ kind,
+ convert: Some(width),
+ },
+
+ // Vector conversion (vector -> vector)
+ (
+ Components::One {
+ component,
+ ty: &TypeInner::Vector { size: src_size, .. },
+ ..
+ },
+ ConstructorType::Vector {
+ size: dst_size,
+ kind: dst_kind,
+ width: dst_width,
+ },
+ ) if dst_size == src_size => Expression::As {
+ expr: component,
+ kind: dst_kind,
+ convert: Some(dst_width),
+ },
+
+ // Matrix conversion (matrix -> matrix)
+ (
+ Components::One {
+ component,
+ ty:
+ &TypeInner::Matrix {
+ columns: src_columns,
+ rows: src_rows,
+ ..
+ },
+ ..
+ },
+ ConstructorType::Matrix {
+ columns: dst_columns,
+ rows: dst_rows,
+ width: dst_width,
+ },
+ ) if dst_columns == src_columns && dst_rows == src_rows => Expression::As {
+ expr: component,
+ kind: ScalarKind::Float,
+ convert: Some(dst_width),
+ },
+
+ // Vector constructor (splat) - infer type
+ (
+ Components::One {
+ component,
+ ty: &TypeInner::Scalar { .. },
+ ..
+ },
+ ConstructorType::PartialVector { size },
+ ) => Expression::Splat {
+ size,
+ value: component,
+ },
+
+ // Vector constructor (splat)
+ (
+ Components::One {
+ component,
+ ty:
+ &TypeInner::Scalar {
+ kind: src_kind,
+ width: src_width,
+ ..
+ },
+ ..
+ },
+ ConstructorType::Vector {
+ size,
+ kind: dst_kind,
+ width: dst_width,
+ },
+ ) if dst_kind == src_kind || dst_width == src_width => Expression::Splat {
+ size,
+ value: component,
+ },
+
+ // Vector constructor (by elements)
+ (
+ Components::Many {
+ components,
+ first_component_ty: &TypeInner::Scalar { kind, width },
+ ..
+ },
+ ConstructorType::PartialVector { size },
+ )
+ | (
+ Components::Many {
+ components,
+ first_component_ty: &TypeInner::Vector { kind, width, .. },
+ ..
+ },
+ ConstructorType::PartialVector { size },
+ )
+ | (
+ Components::Many {
+ components,
+ first_component_ty: &TypeInner::Scalar { .. },
+ ..
+ },
+ ConstructorType::Vector { size, width, kind },
+ )
+ | (
+ Components::Many {
+ components,
+ first_component_ty: &TypeInner::Vector { .. },
+ ..
+ },
+ ConstructorType::Vector { size, width, kind },
+ ) => {
+ let ty = ctx.types.insert(
+ Type {
+ name: None,
+ inner: TypeInner::Vector { size, kind, width },
+ },
+ Default::default(),
+ );
+ Expression::Compose { ty, components }
+ }
+
+ // Matrix constructor (by elements)
+ (
+ Components::Many {
+ components,
+ first_component_ty: &TypeInner::Scalar { width, .. },
+ ..
+ },
+ ConstructorType::PartialMatrix { columns, rows },
+ )
+ | (
+ Components::Many {
+ components,
+ first_component_ty: &TypeInner::Scalar { .. },
+ ..
+ },
+ ConstructorType::Matrix {
+ columns,
+ rows,
+ width,
+ },
+ ) => {
+ let vec_ty = ctx.types.insert(
+ Type {
+ name: None,
+ inner: TypeInner::Vector {
+ width,
+ kind: ScalarKind::Float,
+ size: rows,
+ },
+ },
+ Default::default(),
+ );
+
+ let components = components
+ .chunks(rows as usize)
+ .map(|vec_components| {
+ ctx.expressions.append(
+ Expression::Compose {
+ ty: vec_ty,
+ components: Vec::from(vec_components),
+ },
+ Default::default(),
+ )
+ })
+ .collect();
+
+ let ty = ctx.types.insert(
+ Type {
+ name: None,
+ inner: TypeInner::Matrix {
+ columns,
+ rows,
+ width,
+ },
+ },
+ Default::default(),
+ );
+ Expression::Compose { ty, components }
+ }
+
+ // Matrix constructor (by columns)
+ (
+ Components::Many {
+ components,
+ first_component_ty: &TypeInner::Vector { width, .. },
+ ..
+ },
+ ConstructorType::PartialMatrix { columns, rows },
+ )
+ | (
+ Components::Many {
+ components,
+ first_component_ty: &TypeInner::Vector { .. },
+ ..
+ },
+ ConstructorType::Matrix {
+ columns,
+ rows,
+ width,
+ },
+ ) => {
+ let ty = ctx.types.insert(
+ Type {
+ name: None,
+ inner: TypeInner::Matrix {
+ columns,
+ rows,
+ width,
+ },
+ },
+ Default::default(),
+ );
+ Expression::Compose { ty, components }
+ }
+
+ // Array constructor - infer type
+ (components, ConstructorType::PartialArray) => {
+ let components = components.into_components_vec();
+
+ let base = match ctx.typifier[components[0]].clone() {
+ TypeResolution::Handle(ty) => ty,
+ TypeResolution::Value(inner) => ctx
+ .types
+ .insert(Type { name: None, inner }, Default::default()),
+ };
+
+ let size = Constant {
+ name: None,
+ specialization: None,
+ inner: ConstantInner::Scalar {
+ width: 4,
+ value: ScalarValue::Uint(components.len() as u64),
+ },
+ };
+
+ let inner = TypeInner::Array {
+ base,
+ size: ArraySize::Constant(ctx.constants.append(size, Default::default())),
+ stride: {
+ parser.layouter.update(ctx.types, ctx.constants).unwrap();
+ parser.layouter[base].to_stride()
+ },
+ };
+
+ let ty = ctx
+ .types
+ .insert(Type { name: None, inner }, Default::default());
+
+ Expression::Compose { ty, components }
+ }
+
+ // Array constructor
+ (components, ConstructorType::Array { base, size, stride }) => {
+ let components = components.into_components_vec();
+ let inner = TypeInner::Array { base, size, stride };
+ let ty = ctx
+ .types
+ .insert(Type { name: None, inner }, Default::default());
+ Expression::Compose { ty, components }
+ }
+
+ // Struct constructor
+ (components, ConstructorType::Struct(ty)) => Expression::Compose {
+ ty,
+ components: components.into_components_vec(),
+ },
+
+ // ERRORS
+
+ // Bad conversion (type cast)
+ (
+ Components::One {
+ span, ty: src_ty, ..
+ },
+ dst_ty,
+ ) => {
+ return Err(Error::BadTypeCast {
+ span,
+ from_type: src_ty.to_wgsl(ctx.types, ctx.constants),
+ to_type: dst_ty.to_error_string(ctx.types, ctx.constants),
+ });
+ }
+
+ // Too many parameters for scalar constructor
+ (Components::Many { spans, .. }, ConstructorType::Scalar { .. }) => {
+ return Err(Error::UnexpectedComponents(Span {
+ start: spans[1].start,
+ end: spans.last().unwrap().end,
+ }));
+ }
+
+ // Parameters are of the wrong type for vector or matrix constructor
+ (Components::Many { spans, .. }, ConstructorType::Vector { .. })
+ | (Components::Many { spans, .. }, ConstructorType::Matrix { .. })
+ | (Components::Many { spans, .. }, ConstructorType::PartialVector { .. })
+ | (Components::Many { spans, .. }, ConstructorType::PartialMatrix { .. }) => {
+ return Err(Error::InvalidConstructorComponentType(spans[0].clone(), 0));
+ }
+ };
+
+ let span = NagaSpan::from(parser.pop_scope(lexer));
+ Ok(Some(ctx.expressions.append(expr, span)))
+}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4,6 +4,7 @@ Frontend for [WGSL][wgsl] (WebGPU Shading Language).
[wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html
*/
+mod construction;
mod conv;
mod lexer;
mod number_literals;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -124,6 +125,7 @@ pub enum BadFloatError {
#[derive(Clone, Debug)]
pub enum Error<'a> {
Unexpected(TokenSpan<'a>, ExpectedToken<'a>),
+ UnexpectedComponents(Span),
BadU32(Span, BadIntError),
BadI32(Span, BadIntError),
/// A negative signed integer literal where both signed and unsigned,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -148,6 +150,7 @@ pub enum Error<'a> {
InvalidResolve(ResolveError),
InvalidForInitializer(Span),
InvalidGatherComponent(Span, i32),
+ InvalidConstructorComponentType(Span, i32),
ReservedIdentifierPrefix(Span),
UnknownAddressSpace(Span),
UnknownAttribute(Span),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -162,6 +165,8 @@ pub enum Error<'a> {
ZeroSizeOrAlign(Span),
InconsistentBinding(Span),
UnknownLocalFunction(Span),
+ TypeNotConstructible(Span),
+ TypeNotInferrable(Span),
InitializationTypeMismatch(Span, String),
MissingType(Span),
MissingAttribute(&'static str, Span),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -253,6 +258,11 @@ impl<'a> Error<'a> {
notes: vec![],
}
},
+ Error::UnexpectedComponents(ref bad_span) => ParseError {
+ message: "unexpected components".to_string(),
+ labels: vec![(bad_span.clone(), "unexpected components".into())],
+ notes: vec![],
+ },
Error::BadU32(ref bad_span, ref err) => ParseError {
message: format!(
"expected unsigned integer literal, found `{}`",
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -355,6 +365,11 @@ impl<'a> Error<'a> {
labels: vec![(bad_span.clone(), "invalid component".into())],
notes: vec![],
},
+ Error::InvalidConstructorComponentType(ref bad_span, component) => ParseError {
+ message: format!("invalid type for constructor component at index [{}]", component),
+ labels: vec![(bad_span.clone(), "invalid component type".into())],
+ notes: vec![],
+ },
Error::ReservedIdentifierPrefix(ref bad_span) => ParseError {
message: format!("Identifier starts with a reserved prefix: '{}'", &source[bad_span.clone()]),
labels: vec![(bad_span.clone(), "invalid identifier".into())],
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -415,6 +430,16 @@ impl<'a> Error<'a> {
labels: vec![(span.clone(), "unknown local function".into())],
notes: vec![],
},
+ Error::TypeNotConstructible(ref span) => ParseError {
+ message: format!("type `{}` is not constructible", &source[span.clone()]),
+ labels: vec![(span.clone(), "type is not constructible".into())],
+ notes: vec![],
+ },
+ Error::TypeNotInferrable(ref span) => ParseError {
+ message: "type can't be inferred".to_string(),
+ labels: vec![(span.clone(), "type can't be inferred".into())],
+ notes: vec![],
+ },
Error::InitializationTypeMismatch(ref name_span, ref expected_ty) => ParseError {
message: format!("the type of `{}` is expected to be `{}`", &source[name_span.clone()], expected_ty),
labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())],
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -969,6 +994,98 @@ impl<'a> ExpressionContext<'a, '_, '_> {
expr.handle
}
}
+
+ /// Creates a zero value constant of type `ty`
+ ///
+ /// Returns `None` if the given `ty` is not a constructible type
+ fn create_zero_value_constant(
+ &mut self,
+ ty: Handle<crate::Type>,
+ ) -> Option<Handle<crate::Constant>> {
+ let inner = match self.types[ty].inner {
+ crate::TypeInner::Scalar { kind, width } => {
+ let value = match kind {
+ crate::ScalarKind::Sint => crate::ScalarValue::Sint(0),
+ crate::ScalarKind::Uint => crate::ScalarValue::Uint(0),
+ crate::ScalarKind::Float => crate::ScalarValue::Float(0.),
+ crate::ScalarKind::Bool => crate::ScalarValue::Bool(false),
+ };
+ crate::ConstantInner::Scalar { width, value }
+ }
+ crate::TypeInner::Vector { size, kind, width } => {
+ let scalar_ty = self.types.insert(
+ crate::Type {
+ name: None,
+ inner: crate::TypeInner::Scalar { width, kind },
+ },
+ Default::default(),
+ );
+ let component = self.create_zero_value_constant(scalar_ty);
+ crate::ConstantInner::Composite {
+ ty,
+ components: (0..size as u8).map(|_| component).collect::<Option<_>>()?,
+ }
+ }
+ crate::TypeInner::Matrix {
+ columns,
+ rows,
+ width,
+ } => {
+ let vec_ty = self.types.insert(
+ crate::Type {
+ name: None,
+ inner: crate::TypeInner::Vector {
+ width,
+ kind: crate::ScalarKind::Float,
+ size: rows,
+ },
+ },
+ Default::default(),
+ );
+ let component = self.create_zero_value_constant(vec_ty);
+ crate::ConstantInner::Composite {
+ ty,
+ components: (0..columns as u8)
+ .map(|_| component)
+ .collect::<Option<_>>()?,
+ }
+ }
+ crate::TypeInner::Array {
+ base,
+ size: crate::ArraySize::Constant(size),
+ ..
+ } => {
+ let component = self.create_zero_value_constant(base);
+ crate::ConstantInner::Composite {
+ ty,
+ components: (0..self.constants[size].to_array_length().unwrap())
+ .map(|_| component)
+ .collect::<Option<_>>()?,
+ }
+ }
+ crate::TypeInner::Struct { ref members, .. } => {
+ let members = members.clone();
+ crate::ConstantInner::Composite {
+ ty,
+ components: members
+ .iter()
+ .map(|member| self.create_zero_value_constant(member.ty))
+ .collect::<Option<_>>()?,
+ }
+ }
+ _ => return None,
+ };
+
+ let constant = self.constants.fetch_or_append(
+ crate::Constant {
+ name: None,
+ specialization: None,
+ inner,
+ },
+ crate::Span::default(),
+ );
+ Some(constant)
+ }
}
/// A Naga [`Expression`] handle, with WGSL type information.
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2044,158 +2161,6 @@ impl Parser {
}))
}
- /// Expects [`Scope::PrimaryExpr`] scope on top; if returning Some(_), pops it.
- fn parse_construction<'a>(
- &mut self,
- lexer: &mut Lexer<'a>,
- type_name: &'a str,
- mut ctx: ExpressionContext<'a, '_, '_>,
- ) -> Result<Option<Handle<crate::Expression>>, Error<'a>> {
- assert_eq!(
- self.scopes.last().map(|&(ref scope, _)| scope.clone()),
- Some(Scope::PrimaryExpr)
- );
- let ty_resolution = match self.lookup_type.get(type_name) {
- Some(&handle) => TypeResolution::Handle(handle),
- None => match self.parse_type_decl_impl(
- lexer,
- TypeAttributes::default(),
- type_name,
- ctx.types,
- ctx.constants,
- )? {
- Some(inner) => TypeResolution::Value(inner),
- None => return Ok(None),
- },
- };
-
- let mut components = Vec::new();
- let (last_component, arguments_span) = lexer.capture_span(|lexer| {
- lexer.open_arguments()?;
- let mut last_component = self.parse_general_expression(lexer, ctx.reborrow())?;
-
- while lexer.next_argument()? {
- components.push(last_component);
- last_component = self.parse_general_expression(lexer, ctx.reborrow())?;
- }
-
- Ok(last_component)
- })?;
-
- // We can't use the `TypeInner` returned by this because
- // `resolve_type` borrows context mutably.
- // Use it to insert into the right maps,
- // and then grab it again immutably.
- ctx.resolve_type(last_component)?;
-
- let expr = if components.is_empty()
- && ty_resolution.inner_with(ctx.types).scalar_kind().is_some()
- {
- match (
- ty_resolution.inner_with(ctx.types),
- ctx.typifier.get(last_component, ctx.types),
- ) {
- (
- &crate::TypeInner::Vector {
- size, kind, width, ..
- },
- &crate::TypeInner::Scalar {
- kind: arg_kind,
- width: arg_width,
- ..
- },
- ) if arg_kind == kind && arg_width == width => crate::Expression::Splat {
- size,
- value: last_component,
- },
- (
- &crate::TypeInner::Scalar { kind, width, .. },
- &crate::TypeInner::Scalar { .. },
- )
- | (
- &crate::TypeInner::Vector { kind, width, .. },
- &crate::TypeInner::Vector { .. },
- ) => crate::Expression::As {
- expr: last_component,
- kind,
- convert: Some(width),
- },
- (&crate::TypeInner::Matrix { width, .. }, &crate::TypeInner::Matrix { .. }) => {
- crate::Expression::As {
- expr: last_component,
- kind: crate::ScalarKind::Float,
- convert: Some(width),
- }
- }
- (to_type, from_type) => {
- return Err(Error::BadTypeCast {
- span: arguments_span,
- from_type: from_type.to_wgsl(ctx.types, ctx.constants),
- to_type: to_type.to_wgsl(ctx.types, ctx.constants),
- });
- }
- }
- } else {
- components.push(last_component);
- let mut compose_components = Vec::new();
-
- if let (
- &crate::TypeInner::Matrix {
- rows,
- width,
- columns,
- },
- &crate::TypeInner::Scalar {
- kind: crate::ScalarKind::Float,
- ..
- },
- ) = (
- ty_resolution.inner_with(ctx.types),
- ctx.typifier.get(last_component, ctx.types),
- ) {
- let vec_ty = ctx.types.insert(
- crate::Type {
- name: None,
- inner: crate::TypeInner::Vector {
- width,
- kind: crate::ScalarKind::Float,
- size: rows,
- },
- },
- Default::default(),
- );
-
- compose_components.reserve(columns as usize);
- for vec_components in components.chunks(rows as usize) {
- let handle = ctx.expressions.append(
- crate::Expression::Compose {
- ty: vec_ty,
- components: Vec::from(vec_components),
- },
- crate::Span::default(),
- );
- compose_components.push(handle);
- }
- } else {
- compose_components = components;
- }
-
- let ty = match ty_resolution {
- TypeResolution::Handle(handle) => handle,
- TypeResolution::Value(inner) => ctx
- .types
- .insert(crate::Type { name: None, inner }, Default::default()),
- };
- crate::Expression::Compose {
- ty,
- components: compose_components,
- }
- };
-
- let span = NagaSpan::from(self.pop_scope(lexer));
- Ok(Some(ctx.expressions.append(expr, span)))
- }
-
fn parse_const_expression_impl<'a>(
&mut self,
first_token_span: TokenSpan<'a>,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2325,7 +2290,13 @@ impl Parser {
TypedExpression::non_reference(expr)
} else {
let _ = lexer.next();
- if let Some(expr) = self.parse_construction(lexer, word, ctx.reborrow())? {
+ if let Some(expr) = construction::parse_construction(
+ self,
+ lexer,
+ word,
+ span.clone(),
+ ctx.reborrow(),
+ )? {
TypedExpression::non_reference(expr)
} else {
return Err(Error::UnknownIdent(span, word));
|
diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl
--- a/tests/in/operators.wgsl
+++ b/tests/in/operators.wgsl
@@ -58,6 +58,21 @@ fn constructors() -> f32 {
0.0, 0.0, 0.0, 1.0,
);
+ // zero value constructors
+ var _ = bool();
+ var _ = i32();
+ var _ = u32();
+ var _ = f32();
+ var _ = vec2<u32>();
+ var _ = mat2x2<f32>();
+ var _ = array<Foo, 3>();
+ var _ = Foo();
+
+ // constructors that infer their type from their parameters
+ var _ = vec2(0u);
+ var _ = mat2x2(vec2(0.), vec2(0.));
+ var _ = array(0, 1, 2, 3);
+
return foo.a.x;
}
diff --git a/tests/out/glsl/operators.main.Compute.glsl b/tests/out/glsl/operators.main.Compute.glsl
--- a/tests/out/glsl/operators.main.Compute.glsl
+++ b/tests/out/glsl/operators.main.Compute.glsl
@@ -43,11 +43,25 @@ vec3 bool_cast(vec3 x) {
float constructors() {
Foo foo = Foo(vec4(0.0), 0);
+ bool unnamed = false;
+ int unnamed_1 = 0;
+ uint unnamed_2 = 0u;
+ float unnamed_3 = 0.0;
+ uvec2 unnamed_4 = uvec2(0u, 0u);
+ mat2x2 unnamed_5 = mat2x2(vec2(0.0, 0.0), vec2(0.0, 0.0));
+ Foo unnamed_6[3] = Foo[3](Foo(vec4(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4(0.0, 0.0, 0.0, 0.0), 0));
+ Foo unnamed_7 = Foo(vec4(0.0, 0.0, 0.0, 0.0), 0);
+ uvec2 unnamed_8 = uvec2(0u);
+ mat2x2 unnamed_9 = mat2x2(0.0);
+ int unnamed_10[4] = int[4](0, 0, 0, 0);
foo = Foo(vec4(1.0), 1);
mat2x2 mat2comp = mat2x2(vec2(1.0, 0.0), vec2(0.0, 1.0));
mat4x4 mat4comp = mat4x4(vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(0.0, 0.0, 0.0, 1.0));
- float _e39 = foo.a.x;
- return _e39;
+ unnamed_8 = uvec2(0u);
+ unnamed_9 = mat2x2(vec2(0.0), vec2(0.0));
+ unnamed_10 = int[4](0, 1, 2, 3);
+ float _e70 = foo.a.x;
+ return _e70;
}
void modulo() {
diff --git a/tests/out/hlsl/operators.hlsl b/tests/out/hlsl/operators.hlsl
--- a/tests/out/hlsl/operators.hlsl
+++ b/tests/out/hlsl/operators.hlsl
@@ -53,12 +53,29 @@ Foo ConstructFoo(float4 arg0, int arg1) {
float constructors()
{
Foo foo = (Foo)0;
+ bool unnamed = false;
+ int unnamed_1 = 0;
+ uint unnamed_2 = 0u;
+ float unnamed_3 = 0.0;
+ uint2 unnamed_4 = uint2(0u, 0u);
+ float2x2 unnamed_5 = float2x2(float2(0.0, 0.0), float2(0.0, 0.0));
+ Foo unnamed_6[3] = { { float4(0.0, 0.0, 0.0, 0.0), 0 }, { float4(0.0, 0.0, 0.0, 0.0), 0 }, { float4(0.0, 0.0, 0.0, 0.0), 0 } };
+ Foo unnamed_7 = { float4(0.0, 0.0, 0.0, 0.0), 0 };
+ uint2 unnamed_8 = (uint2)0;
+ float2x2 unnamed_9 = (float2x2)0;
+ int unnamed_10[4] = {(int)0,(int)0,(int)0,(int)0};
foo = ConstructFoo(float4(1.0.xxxx), 1);
float2x2 mat2comp = float2x2(float2(1.0, 0.0), float2(0.0, 1.0));
float4x4 mat4comp = float4x4(float4(1.0, 0.0, 0.0, 0.0), float4(0.0, 1.0, 0.0, 0.0), float4(0.0, 0.0, 1.0, 0.0), float4(0.0, 0.0, 0.0, 1.0));
- float _expr39 = foo.a.x;
- return _expr39;
+ unnamed_8 = uint2(0u.xx);
+ unnamed_9 = float2x2(float2(0.0.xx), float2(0.0.xx));
+ {
+ int _result[4]={ 0, 1, 2, 3 };
+ for(int _i=0; _i<4; ++_i) unnamed_10[_i] = _result[_i];
+ }
+ float _expr70 = foo.a.x;
+ return _expr70;
}
void modulo()
diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl
--- a/tests/out/msl/operators.msl
+++ b/tests/out/msl/operators.msl
@@ -8,10 +8,22 @@ struct Foo {
metal::float4 a;
int b;
};
+struct type_12 {
+ Foo inner[3];
+};
+struct type_13 {
+ int inner[4u];
+};
constant metal::float4 v_f32_one = {1.0, 1.0, 1.0, 1.0};
constant metal::float4 v_f32_zero = {0.0, 0.0, 0.0, 0.0};
constant metal::float4 v_f32_half = {0.5, 0.5, 0.5, 0.5};
constant metal::int4 v_i32_one = {1, 1, 1, 1};
+constant metal::uint2 const_type_11_ = {0u, 0u};
+constant metal::float2 const_type_6_ = {0.0, 0.0};
+constant metal::float2x2 const_type_7_ = {const_type_6_, const_type_6_};
+constant metal::float4 const_type = {0.0, 0.0, 0.0, 0.0};
+constant Foo const_Foo = {const_type, 0};
+constant type_12 const_type_12_ = {const_Foo, const_Foo, const_Foo};
metal::float4 builtins(
) {
diff --git a/tests/out/msl/operators.msl b/tests/out/msl/operators.msl
--- a/tests/out/msl/operators.msl
+++ b/tests/out/msl/operators.msl
@@ -52,11 +64,25 @@ metal::float3 bool_cast(
float constructors(
) {
Foo foo;
+ bool unnamed = false;
+ int unnamed_1 = 0;
+ uint unnamed_2 = 0u;
+ float unnamed_3 = 0.0;
+ metal::uint2 unnamed_4 = const_type_11_;
+ metal::float2x2 unnamed_5 = const_type_7_;
+ type_12 unnamed_6 = const_type_12_;
+ Foo unnamed_7 = const_Foo;
+ metal::uint2 unnamed_8;
+ metal::float2x2 unnamed_9;
+ type_13 unnamed_10;
foo = Foo {metal::float4(1.0), 1};
metal::float2x2 mat2comp = metal::float2x2(metal::float2(1.0, 0.0), metal::float2(0.0, 1.0));
metal::float4x4 mat4comp = metal::float4x4(metal::float4(1.0, 0.0, 0.0, 0.0), metal::float4(0.0, 1.0, 0.0, 0.0), metal::float4(0.0, 0.0, 1.0, 0.0), metal::float4(0.0, 0.0, 0.0, 1.0));
- float _e39 = foo.a.x;
- return _e39;
+ unnamed_8 = metal::uint2(0u);
+ unnamed_9 = metal::float2x2(metal::float2(0.0), metal::float2(0.0));
+ for(int _i=0; _i<4; ++_i) unnamed_10.inner[_i] = type_13 {0, 1, 2, 3}.inner[_i];
+ float _e70 = foo.a.x;
+ return _e70;
}
void modulo(
diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm
--- a/tests/out/spv/operators.spvasm
+++ b/tests/out/spv/operators.spvasm
@@ -1,14 +1,16 @@
; SPIR-V
; Version: 1.1
; Generator: rspirv
-; Bound: 180
+; Bound: 214
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
-OpEntryPoint GLCompute %168 "main"
-OpExecutionMode %168 LocalSize 1 1 1
-OpMemberDecorate %23 0 Offset 0
-OpMemberDecorate %23 1 Offset 16
+OpEntryPoint GLCompute %202 "main"
+OpExecutionMode %202 LocalSize 1 1 1
+OpMemberDecorate %27 0 Offset 0
+OpMemberDecorate %27 1 Offset 16
+OpDecorate %32 ArrayStride 32
+OpDecorate %33 ArrayStride 4
%2 = OpTypeVoid
%4 = OpTypeFloat 32
%3 = OpConstant %4 1.0
diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm
--- a/tests/out/spv/operators.spvasm
+++ b/tests/out/spv/operators.spvasm
@@ -26,208 +28,245 @@ OpMemberDecorate %23 1 Offset 16
%16 = OpConstant %4 4.0
%17 = OpConstant %8 5
%18 = OpConstant %8 2
-%19 = OpTypeVector %4 4
-%20 = OpTypeVector %8 4
-%21 = OpTypeVector %10 4
-%22 = OpTypeVector %4 3
-%23 = OpTypeStruct %19 %8
-%24 = OpTypeVector %4 2
-%25 = OpTypeMatrix %24 2
-%26 = OpTypeMatrix %19 4
-%27 = OpConstantComposite %19 %3 %3 %3 %3
-%28 = OpConstantComposite %19 %5 %5 %5 %5
-%29 = OpConstantComposite %19 %6 %6 %6 %6
-%30 = OpConstantComposite %20 %7 %7 %7 %7
-%33 = OpTypeFunction %19
-%74 = OpTypeFunction %8
-%81 = OpConstantNull %8
-%85 = OpTypeFunction %22 %22
-%87 = OpTypeVector %10 3
-%94 = OpTypePointer Function %23
-%97 = OpTypeFunction %4
-%109 = OpTypePointer Function %19
-%110 = OpTypePointer Function %4
-%112 = OpTypeInt 32 0
-%111 = OpConstant %112 0
-%117 = OpTypeFunction %2
-%121 = OpTypeVector %8 3
-%143 = OpTypePointer Function %8
-%32 = OpFunction %19 None %33
-%31 = OpLabel
-OpBranch %34
-%34 = OpLabel
-%35 = OpSelect %8 %9 %7 %11
-%37 = OpCompositeConstruct %21 %9 %9 %9 %9
-%36 = OpSelect %19 %37 %27 %28
-%38 = OpCompositeConstruct %21 %12 %12 %12 %12
-%39 = OpSelect %19 %38 %28 %27
-%40 = OpExtInst %19 %1 FMix %28 %27 %29
-%42 = OpCompositeConstruct %19 %13 %13 %13 %13
-%41 = OpExtInst %19 %1 FMix %28 %27 %42
-%43 = OpCompositeExtract %8 %30 0
-%44 = OpBitcast %4 %43
-%45 = OpBitcast %19 %30
-%46 = OpConvertFToS %20 %28
-%47 = OpCompositeConstruct %20 %35 %35 %35 %35
-%48 = OpIAdd %20 %47 %46
-%49 = OpConvertSToF %19 %48
-%50 = OpFAdd %19 %49 %36
-%51 = OpFAdd %19 %50 %40
-%52 = OpFAdd %19 %51 %41
-%53 = OpCompositeConstruct %19 %44 %44 %44 %44
-%54 = OpFAdd %19 %52 %53
-%55 = OpFAdd %19 %54 %45
-OpReturnValue %55
+%20 = OpTypeInt 32 0
+%19 = OpConstant %20 0
+%21 = OpConstant %8 3
+%22 = OpConstant %20 4
+%23 = OpTypeVector %4 4
+%24 = OpTypeVector %8 4
+%25 = OpTypeVector %10 4
+%26 = OpTypeVector %4 3
+%27 = OpTypeStruct %23 %8
+%28 = OpTypeVector %4 2
+%29 = OpTypeMatrix %28 2
+%30 = OpTypeMatrix %23 4
+%31 = OpTypeVector %20 2
+%32 = OpTypeArray %27 %21
+%33 = OpTypeArray %8 %22
+%34 = OpConstantComposite %23 %3 %3 %3 %3
+%35 = OpConstantComposite %23 %5 %5 %5 %5
+%36 = OpConstantComposite %23 %6 %6 %6 %6
+%37 = OpConstantComposite %24 %7 %7 %7 %7
+%38 = OpConstantComposite %31 %19 %19
+%39 = OpConstantComposite %28 %5 %5
+%40 = OpConstantComposite %29 %39 %39
+%41 = OpConstantComposite %23 %5 %5 %5 %5
+%42 = OpConstantComposite %27 %41 %11
+%43 = OpConstantComposite %32 %42 %42 %42
+%46 = OpTypeFunction %23
+%87 = OpTypeFunction %8
+%94 = OpConstantNull %8
+%98 = OpTypeFunction %26 %26
+%100 = OpTypeVector %10 3
+%107 = OpTypePointer Function %27
+%109 = OpTypePointer Function %10
+%111 = OpTypePointer Function %8
+%113 = OpTypePointer Function %20
+%115 = OpTypePointer Function %4
+%117 = OpTypePointer Function %31
+%119 = OpTypePointer Function %29
+%121 = OpTypePointer Function %32
+%126 = OpTypePointer Function %33
+%129 = OpTypeFunction %4
+%146 = OpTypePointer Function %23
+%147 = OpTypePointer Function %4
+%152 = OpTypeFunction %2
+%156 = OpTypeVector %8 3
+%45 = OpFunction %23 None %46
+%44 = OpLabel
+OpBranch %47
+%47 = OpLabel
+%48 = OpSelect %8 %9 %7 %11
+%50 = OpCompositeConstruct %25 %9 %9 %9 %9
+%49 = OpSelect %23 %50 %34 %35
+%51 = OpCompositeConstruct %25 %12 %12 %12 %12
+%52 = OpSelect %23 %51 %35 %34
+%53 = OpExtInst %23 %1 FMix %35 %34 %36
+%55 = OpCompositeConstruct %23 %13 %13 %13 %13
+%54 = OpExtInst %23 %1 FMix %35 %34 %55
+%56 = OpCompositeExtract %8 %37 0
+%57 = OpBitcast %4 %56
+%58 = OpBitcast %23 %37
+%59 = OpConvertFToS %24 %35
+%60 = OpCompositeConstruct %24 %48 %48 %48 %48
+%61 = OpIAdd %24 %60 %59
+%62 = OpConvertSToF %23 %61
+%63 = OpFAdd %23 %62 %49
+%64 = OpFAdd %23 %63 %53
+%65 = OpFAdd %23 %64 %54
+%66 = OpCompositeConstruct %23 %57 %57 %57 %57
+%67 = OpFAdd %23 %65 %66
+%68 = OpFAdd %23 %67 %58
+OpReturnValue %68
OpFunctionEnd
-%57 = OpFunction %19 None %33
-%56 = OpLabel
-OpBranch %58
-%58 = OpLabel
-%59 = OpCompositeConstruct %24 %14 %14
-%60 = OpCompositeConstruct %24 %3 %3
-%61 = OpFAdd %24 %60 %59
-%62 = OpCompositeConstruct %24 %15 %15
-%63 = OpFSub %24 %61 %62
-%64 = OpCompositeConstruct %24 %16 %16
-%65 = OpFDiv %24 %63 %64
-%66 = OpCompositeConstruct %20 %17 %17 %17 %17
-%67 = OpCompositeConstruct %20 %18 %18 %18 %18
-%68 = OpSMod %20 %66 %67
-%69 = OpVectorShuffle %19 %65 %65 0 1 0 1
-%70 = OpConvertSToF %19 %68
-%71 = OpFAdd %19 %69 %70
-OpReturnValue %71
+%70 = OpFunction %23 None %46
+%69 = OpLabel
+OpBranch %71
+%71 = OpLabel
+%72 = OpCompositeConstruct %28 %14 %14
+%73 = OpCompositeConstruct %28 %3 %3
+%74 = OpFAdd %28 %73 %72
+%75 = OpCompositeConstruct %28 %15 %15
+%76 = OpFSub %28 %74 %75
+%77 = OpCompositeConstruct %28 %16 %16
+%78 = OpFDiv %28 %76 %77
+%79 = OpCompositeConstruct %24 %17 %17 %17 %17
+%80 = OpCompositeConstruct %24 %18 %18 %18 %18
+%81 = OpSMod %24 %79 %80
+%82 = OpVectorShuffle %23 %78 %78 0 1 0 1
+%83 = OpConvertSToF %23 %81
+%84 = OpFAdd %23 %82 %83
+OpReturnValue %84
OpFunctionEnd
-%73 = OpFunction %8 None %74
-%72 = OpLabel
-OpBranch %75
-%75 = OpLabel
-%76 = OpLogicalNot %10 %9
-OpSelectionMerge %77 None
-OpBranchConditional %76 %78 %79
-%78 = OpLabel
+%86 = OpFunction %8 None %87
+%85 = OpLabel
+OpBranch %88
+%88 = OpLabel
+%89 = OpLogicalNot %10 %9
+OpSelectionMerge %90 None
+OpBranchConditional %89 %91 %92
+%91 = OpLabel
OpReturnValue %7
-%79 = OpLabel
-%80 = OpNot %8 %7
-OpReturnValue %80
-%77 = OpLabel
-OpReturnValue %81
+%92 = OpLabel
+%93 = OpNot %8 %7
+OpReturnValue %93
+%90 = OpLabel
+OpReturnValue %94
OpFunctionEnd
-%84 = OpFunction %22 None %85
-%83 = OpFunctionParameter %22
-%82 = OpLabel
-OpBranch %86
-%86 = OpLabel
-%88 = OpCompositeConstruct %22 %5 %5 %5
-%89 = OpFUnordNotEqual %87 %83 %88
-%90 = OpCompositeConstruct %22 %5 %5 %5
-%91 = OpCompositeConstruct %22 %3 %3 %3
-%92 = OpSelect %22 %89 %91 %90
-OpReturnValue %92
-OpFunctionEnd
-%96 = OpFunction %4 None %97
+%97 = OpFunction %26 None %98
+%96 = OpFunctionParameter %26
%95 = OpLabel
-%93 = OpVariable %94 Function
-OpBranch %98
-%98 = OpLabel
-%99 = OpCompositeConstruct %19 %3 %3 %3 %3
-%100 = OpCompositeConstruct %23 %99 %7
-OpStore %93 %100
-%101 = OpCompositeConstruct %24 %3 %5
-%102 = OpCompositeConstruct %24 %5 %3
-%103 = OpCompositeConstruct %25 %101 %102
-%104 = OpCompositeConstruct %19 %3 %5 %5 %5
-%105 = OpCompositeConstruct %19 %5 %3 %5 %5
-%106 = OpCompositeConstruct %19 %5 %5 %3 %5
-%107 = OpCompositeConstruct %19 %5 %5 %5 %3
-%108 = OpCompositeConstruct %26 %104 %105 %106 %107
-%113 = OpAccessChain %110 %93 %111 %111
-%114 = OpLoad %4 %113
-OpReturnValue %114
-OpFunctionEnd
-%116 = OpFunction %2 None %117
-%115 = OpLabel
-OpBranch %118
-%118 = OpLabel
-%119 = OpSMod %8 %7 %7
-%120 = OpFRem %4 %3 %3
-%122 = OpCompositeConstruct %121 %7 %7 %7
-%123 = OpCompositeConstruct %121 %7 %7 %7
-%124 = OpSMod %121 %122 %123
-%125 = OpCompositeConstruct %22 %3 %3 %3
-%126 = OpCompositeConstruct %22 %3 %3 %3
-%127 = OpFRem %22 %125 %126
-OpReturn
+OpBranch %99
+%99 = OpLabel
+%101 = OpCompositeConstruct %26 %5 %5 %5
+%102 = OpFUnordNotEqual %100 %96 %101
+%103 = OpCompositeConstruct %26 %5 %5 %5
+%104 = OpCompositeConstruct %26 %3 %3 %3
+%105 = OpSelect %26 %102 %104 %103
+OpReturnValue %105
OpFunctionEnd
-%129 = OpFunction %2 None %117
-%128 = OpLabel
+%128 = OpFunction %4 None %129
+%127 = OpLabel
+%123 = OpVariable %117 Function
+%118 = OpVariable %119 Function %40
+%112 = OpVariable %113 Function %19
+%106 = OpVariable %107 Function
+%124 = OpVariable %119 Function
+%120 = OpVariable %121 Function %43
+%114 = OpVariable %115 Function %5
+%108 = OpVariable %109 Function %12
+%125 = OpVariable %126 Function
+%122 = OpVariable %107 Function %42
+%116 = OpVariable %117 Function %38
+%110 = OpVariable %111 Function %11
OpBranch %130
%130 = OpLabel
-%131 = OpCompositeConstruct %19 %3 %5 %5 %5
-%132 = OpCompositeConstruct %19 %5 %3 %5 %5
-%133 = OpCompositeConstruct %19 %5 %5 %3 %5
-%134 = OpCompositeConstruct %19 %5 %5 %5 %3
-%135 = OpCompositeConstruct %26 %131 %132 %133 %134
-%136 = OpMatrixTimesScalar %26 %135 %14
+%131 = OpCompositeConstruct %23 %3 %3 %3 %3
+%132 = OpCompositeConstruct %27 %131 %7
+OpStore %106 %132
+%133 = OpCompositeConstruct %28 %3 %5
+%134 = OpCompositeConstruct %28 %5 %3
+%135 = OpCompositeConstruct %29 %133 %134
+%136 = OpCompositeConstruct %23 %3 %5 %5 %5
+%137 = OpCompositeConstruct %23 %5 %3 %5 %5
+%138 = OpCompositeConstruct %23 %5 %5 %3 %5
+%139 = OpCompositeConstruct %23 %5 %5 %5 %3
+%140 = OpCompositeConstruct %30 %136 %137 %138 %139
+%141 = OpCompositeConstruct %31 %19 %19
+OpStore %123 %141
+%142 = OpCompositeConstruct %28 %5 %5
+%143 = OpCompositeConstruct %28 %5 %5
+%144 = OpCompositeConstruct %29 %142 %143
+OpStore %124 %144
+%145 = OpCompositeConstruct %33 %11 %7 %18 %21
+OpStore %125 %145
+%148 = OpAccessChain %147 %106 %19 %19
+%149 = OpLoad %4 %148
+OpReturnValue %149
+OpFunctionEnd
+%151 = OpFunction %2 None %152
+%150 = OpLabel
+OpBranch %153
+%153 = OpLabel
+%154 = OpSMod %8 %7 %7
+%155 = OpFRem %4 %3 %3
+%157 = OpCompositeConstruct %156 %7 %7 %7
+%158 = OpCompositeConstruct %156 %7 %7 %7
+%159 = OpSMod %156 %157 %158
+%160 = OpCompositeConstruct %26 %3 %3 %3
+%161 = OpCompositeConstruct %26 %3 %3 %3
+%162 = OpFRem %26 %160 %161
+OpReturn
+OpFunctionEnd
+%164 = OpFunction %2 None %152
+%163 = OpLabel
+OpBranch %165
+%165 = OpLabel
+%166 = OpCompositeConstruct %23 %3 %5 %5 %5
+%167 = OpCompositeConstruct %23 %5 %3 %5 %5
+%168 = OpCompositeConstruct %23 %5 %5 %3 %5
+%169 = OpCompositeConstruct %23 %5 %5 %5 %3
+%170 = OpCompositeConstruct %30 %166 %167 %168 %169
+%171 = OpMatrixTimesScalar %30 %170 %14
OpReturn
OpFunctionEnd
-%138 = OpFunction %2 None %117
-%137 = OpLabel
-OpBranch %139
-%139 = OpLabel
-%140 = OpLogicalOr %10 %9 %12
-%141 = OpLogicalAnd %10 %9 %12
+%173 = OpFunction %2 None %152
+%172 = OpLabel
+OpBranch %174
+%174 = OpLabel
+%175 = OpLogicalOr %10 %9 %12
+%176 = OpLogicalAnd %10 %9 %12
OpReturn
OpFunctionEnd
-%145 = OpFunction %2 None %117
-%144 = OpLabel
-%142 = OpVariable %143 Function %7
-OpBranch %146
-%146 = OpLabel
-%147 = OpLoad %8 %142
-%148 = OpIAdd %8 %147 %7
-OpStore %142 %148
-%149 = OpLoad %8 %142
-%150 = OpISub %8 %149 %7
-OpStore %142 %150
-%151 = OpLoad %8 %142
-%152 = OpLoad %8 %142
-%153 = OpIMul %8 %151 %152
-OpStore %142 %153
-%154 = OpLoad %8 %142
-%155 = OpLoad %8 %142
-%156 = OpSDiv %8 %154 %155
-OpStore %142 %156
-%157 = OpLoad %8 %142
-%158 = OpSMod %8 %157 %7
-OpStore %142 %158
-%159 = OpLoad %8 %142
-%160 = OpBitwiseXor %8 %159 %11
-OpStore %142 %160
-%161 = OpLoad %8 %142
-%162 = OpBitwiseAnd %8 %161 %11
-OpStore %142 %162
-%163 = OpLoad %8 %142
-%164 = OpIAdd %8 %163 %7
-OpStore %142 %164
-%165 = OpLoad %8 %142
-%166 = OpISub %8 %165 %7
-OpStore %142 %166
+%179 = OpFunction %2 None %152
+%178 = OpLabel
+%177 = OpVariable %111 Function %7
+OpBranch %180
+%180 = OpLabel
+%181 = OpLoad %8 %177
+%182 = OpIAdd %8 %181 %7
+OpStore %177 %182
+%183 = OpLoad %8 %177
+%184 = OpISub %8 %183 %7
+OpStore %177 %184
+%185 = OpLoad %8 %177
+%186 = OpLoad %8 %177
+%187 = OpIMul %8 %185 %186
+OpStore %177 %187
+%188 = OpLoad %8 %177
+%189 = OpLoad %8 %177
+%190 = OpSDiv %8 %188 %189
+OpStore %177 %190
+%191 = OpLoad %8 %177
+%192 = OpSMod %8 %191 %7
+OpStore %177 %192
+%193 = OpLoad %8 %177
+%194 = OpBitwiseXor %8 %193 %11
+OpStore %177 %194
+%195 = OpLoad %8 %177
+%196 = OpBitwiseAnd %8 %195 %11
+OpStore %177 %196
+%197 = OpLoad %8 %177
+%198 = OpIAdd %8 %197 %7
+OpStore %177 %198
+%199 = OpLoad %8 %177
+%200 = OpISub %8 %199 %7
+OpStore %177 %200
OpReturn
OpFunctionEnd
-%168 = OpFunction %2 None %117
-%167 = OpLabel
-OpBranch %169
-%169 = OpLabel
-%170 = OpFunctionCall %19 %32
-%171 = OpFunctionCall %19 %57
-%172 = OpFunctionCall %8 %73
-%173 = OpVectorShuffle %22 %27 %27 0 1 2
-%174 = OpFunctionCall %22 %84 %173
-%175 = OpFunctionCall %4 %96
-%176 = OpFunctionCall %2 %116
-%177 = OpFunctionCall %2 %129
-%178 = OpFunctionCall %2 %138
-%179 = OpFunctionCall %2 %145
+%202 = OpFunction %2 None %152
+%201 = OpLabel
+OpBranch %203
+%203 = OpLabel
+%204 = OpFunctionCall %23 %45
+%205 = OpFunctionCall %23 %70
+%206 = OpFunctionCall %8 %86
+%207 = OpVectorShuffle %26 %34 %34 0 1 2
+%208 = OpFunctionCall %26 %97 %207
+%209 = OpFunctionCall %4 %128
+%210 = OpFunctionCall %2 %151
+%211 = OpFunctionCall %2 %164
+%212 = OpFunctionCall %2 %173
+%213 = OpFunctionCall %2 %179
OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl
--- a/tests/out/wgsl/operators.wgsl
+++ b/tests/out/wgsl/operators.wgsl
@@ -40,12 +40,26 @@ fn bool_cast(x: vec3<f32>) -> vec3<f32> {
fn constructors() -> f32 {
var foo: Foo;
+ var unnamed: bool = false;
+ var unnamed_1: i32 = 0;
+ var unnamed_2: u32 = 0u;
+ var unnamed_3: f32 = 0.0;
+ var unnamed_4: vec2<u32> = vec2<u32>(0u, 0u);
+ var unnamed_5: mat2x2<f32> = mat2x2<f32>(vec2<f32>(0.0, 0.0), vec2<f32>(0.0, 0.0));
+ var unnamed_6: array<Foo,3> = array<Foo,3>(Foo(vec4<f32>(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4<f32>(0.0, 0.0, 0.0, 0.0), 0), Foo(vec4<f32>(0.0, 0.0, 0.0, 0.0), 0));
+ var unnamed_7: Foo = Foo(vec4<f32>(0.0, 0.0, 0.0, 0.0), 0);
+ var unnamed_8: vec2<u32>;
+ var unnamed_9: mat2x2<f32>;
+ var unnamed_10: array<i32,4u>;
foo = Foo(vec4<f32>(1.0), 1);
let mat2comp = mat2x2<f32>(vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0));
let mat4comp = mat4x4<f32>(vec4<f32>(1.0, 0.0, 0.0, 0.0), vec4<f32>(0.0, 1.0, 0.0, 0.0), vec4<f32>(0.0, 0.0, 1.0, 0.0), vec4<f32>(0.0, 0.0, 0.0, 1.0));
- let _e39 = foo.a.x;
- return _e39;
+ unnamed_8 = vec2<u32>(0u);
+ unnamed_9 = mat2x2<f32>(vec2<f32>(0.0), vec2<f32>(0.0));
+ unnamed_10 = array<i32,4u>(0, 1, 2, 3);
+ let _e70 = foo.a.x;
+ return _e70;
}
fn modulo() {
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -157,10 +157,82 @@ fn bad_type_cast() {
}
"#,
r#"error: cannot cast a vec2<f32> to a i32
- ┌─ wgsl:3:27
+ ┌─ wgsl:3:28
│
3 │ return i32(vec2<f32>(0.0));
- │ ^^^^^^^^^^^^^^^^ cannot cast a vec2<f32> to a i32
+ │ ^^^^^^^^^^^^^^ cannot cast a vec2<f32> to a i32
+
+"#,
+ );
+}
+
+#[test]
+fn type_not_constructible() {
+ check(
+ r#"
+ fn x() {
+ var _ = atomic<i32>(0);
+ }
+ "#,
+ r#"error: type `atomic` is not constructible
+ ┌─ wgsl:3:25
+ │
+3 │ var _ = atomic<i32>(0);
+ │ ^^^^^^ type is not constructible
+
+"#,
+ );
+}
+
+#[test]
+fn type_not_inferrable() {
+ check(
+ r#"
+ fn x() {
+ var _ = vec2();
+ }
+ "#,
+ r#"error: type can't be inferred
+ ┌─ wgsl:3:25
+ │
+3 │ var _ = vec2();
+ │ ^^^^ type can't be inferred
+
+"#,
+ );
+}
+
+#[test]
+fn unexpected_constructor_parameters() {
+ check(
+ r#"
+ fn x() {
+ var _ = i32(0, 1);
+ }
+ "#,
+ r#"error: unexpected components
+ ┌─ wgsl:3:31
+ │
+3 │ var _ = i32(0, 1);
+ │ ^^ unexpected components
+
+"#,
+ );
+}
+
+#[test]
+fn constructor_parameter_type_mismatch() {
+ check(
+ r#"
+ fn x() {
+ var _ = mat2x2<f32>(array(0, 1), vec2(2, 3));
+ }
+ "#,
+ r#"error: invalid type for constructor component at index [0]
+ ┌─ wgsl:3:37
+ │
+3 │ var _ = mat2x2<f32>(array(0, 1), vec2(2, 3));
+ │ ^^^^^^^^^^^ invalid component type
"#,
);
|
WGSL constructor doesn't check length
The following code produces an error message that was unhelpful
```
@stage(vertex)
fn passthrough(@location(0) pos: vec2<f32>) -> @builtin(position) vec4<f32> {
return vec4<f32>(pos);
}
```
The error is:
```
[2022-03-13T21:53:32Z ERROR naga::valid::function] Returning Some(Vector { size: Bi, kind: Float, width: 4 }) where Some(Vector { size: Quad, kind: Float, width: 4 }) is expected
error:
┌─ triangle.wgsl:3:10
│
3 │ return vec4<f32>(pos);
│ ^^^^^^^^^^^^^^^ naga::Expression [2]
Entry point passthrough at Vertex is invalid:
The `return` value Some([2]) does not match the function return value
```
From the log output, it seems like the `4` in the type constructor expression `vec4<f32>(pos)` got ignored, and the expression is typed as a `vec2`, which doesn't match the return type.
|
2022-03-27T00:38:42Z
|
0.8
|
2022-03-30T08:34:25Z
|
ea832a9eec13560560c017072d4318d5d942e5e5
|
[
"convert_wgsl",
"bad_type_cast",
"constructor_parameter_type_mismatch",
"type_not_constructible",
"unexpected_constructor_parameters",
"type_not_inferrable"
] |
[
"arena::tests::append_unique",
"back::msl::test_error_size",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::cast",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::constants::tests::unary_op",
"front::glsl::constants::tests::access",
"back::msl::writer::test_stack_size",
"front::spv::test::parse",
"front::glsl::parser_tests::constants",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_decimal_floats",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_hex_ints",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::tests::parse_parentheses_switch",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_switch",
"front::glsl::parser_tests::expressions",
"front::wgsl::type_inner_tests::to_wgsl",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_struct_instantiation",
"proc::namer::test",
"proc::test_matrix_size",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_hex_floats",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::functions",
"convert_glsl_variations_check",
"convert_glsl_folder",
"convert_spv_all",
"sampler1d",
"cube_array",
"geometry",
"storage1d",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"bad_texture_sample_type",
"function_without_identifier",
"bad_for_initializer",
"inconsistent_binding",
"invalid_float",
"invalid_integer",
"invalid_arrays",
"invalid_texture_sample_type",
"bad_texture",
"dead_code",
"invalid_structs",
"last_case_falltrough",
"invalid_runtime_sized_arrays",
"local_var_missing_type",
"invalid_local_vars",
"missing_default_case",
"let_type_mismatch",
"invalid_access",
"invalid_functions",
"reserved_identifier_prefix",
"struct_member_zero_size",
"struct_member_zero_align",
"missing_bindings",
"pointer_type_equivalence",
"unknown_attribute",
"unknown_access",
"unknown_conservative_depth",
"unknown_built_in",
"postfix_pointers",
"negative_index",
"unknown_scalar_type",
"unknown_ident",
"unknown_local_function",
"reserved_keyword",
"module_scope_identifier_redefinition",
"unknown_shader_stage",
"unknown_identifier",
"unknown_storage_format",
"unknown_storage_class",
"unknown_type",
"var_type_mismatch",
"select",
"wrong_access_mode",
"valid_access",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 142)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,787
|
gfx-rs__naga-1787
|
[
"1721"
] |
05f050fad485763bf7bf6e1ad4206007b52bc345
|
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3743,6 +3743,40 @@ impl Parser {
Some(crate::Statement::Loop { body, continuing })
}
+ "while" => {
+ let _ = lexer.next();
+ let mut body = crate::Block::new();
+
+ let (condition, span) = lexer.capture_span(|lexer| {
+ emitter.start(context.expressions);
+ let condition = self.parse_general_expression(
+ lexer,
+ context.as_expression(&mut body, &mut emitter),
+ )?;
+ lexer.expect(Token::Paren('{'))?;
+ body.extend(emitter.finish(context.expressions));
+ Ok(condition)
+ })?;
+ let mut reject = crate::Block::new();
+ reject.push(crate::Statement::Break, NagaSpan::default());
+ body.push(
+ crate::Statement::If {
+ condition,
+ accept: crate::Block::new(),
+ reject,
+ },
+ NagaSpan::from(span),
+ );
+
+ while !lexer.skip(Token::Paren('}')) {
+ self.parse_statement(lexer, context.reborrow(), &mut body, false)?;
+ }
+
+ Some(crate::Statement::Loop {
+ body,
+ continuing: crate::Block::new(),
+ })
+ }
"for" => {
let _ = lexer.next();
lexer.expect(Token::Paren('('))?;
|
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -262,6 +262,32 @@ fn parse_loop() {
",
)
.unwrap();
+ parse_str(
+ "
+ fn main() {
+ var found: bool = false;
+ var i: i32 = 0;
+ while !found {
+ if i == 10 {
+ found = true;
+ }
+
+ i = i + 1;
+ }
+ }
+ ",
+ )
+ .unwrap();
+ parse_str(
+ "
+ fn main() {
+ while true {
+ break;
+ }
+ }
+ ",
+ )
+ .unwrap();
parse_str(
"
fn main() {
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -418,7 +444,7 @@ fn parse_struct_instantiation() {
a: f32,
b: vec3<f32>,
};
-
+
@stage(fragment)
fn fs_main() {
var foo: Foo = Foo(0.0, vec3<f32>(0.0, 1.0, 42.0));
diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl
--- a/tests/in/collatz.wgsl
+++ b/tests/in/collatz.wgsl
@@ -14,10 +14,7 @@ var<storage,read_write> v_indices: PrimeIndices;
fn collatz_iterations(n_base: u32) -> u32 {
var n = n_base;
var i: u32 = 0u;
- loop {
- if n <= 1u {
- break;
- }
+ while n > 1u {
if n % 2u == 0u {
n = n / 2u;
}
diff --git a/tests/out/hlsl/collatz.hlsl b/tests/out/hlsl/collatz.hlsl
--- a/tests/out/hlsl/collatz.hlsl
+++ b/tests/out/hlsl/collatz.hlsl
@@ -9,7 +9,8 @@ uint collatz_iterations(uint n_base)
n = n_base;
while(true) {
uint _expr5 = n;
- if ((_expr5 <= 1u)) {
+ if ((_expr5 > 1u)) {
+ } else {
break;
}
uint _expr8 = n;
diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron
--- a/tests/out/ir/collatz.ron
+++ b/tests/out/ir/collatz.ron
@@ -125,7 +125,7 @@
),
Constant(2),
Binary(
- op: LessEqual,
+ op: Greater,
left: 6,
right: 7,
),
diff --git a/tests/out/ir/collatz.ron b/tests/out/ir/collatz.ron
--- a/tests/out/ir/collatz.ron
+++ b/tests/out/ir/collatz.ron
@@ -199,10 +199,10 @@
)),
If(
condition: 8,
- accept: [
+ accept: [],
+ reject: [
Break,
],
- reject: [],
),
Emit((
start: 8,
diff --git a/tests/out/msl/collatz.msl b/tests/out/msl/collatz.msl
--- a/tests/out/msl/collatz.msl
+++ b/tests/out/msl/collatz.msl
@@ -21,7 +21,8 @@ uint collatz_iterations(
n = n_base;
while(true) {
uint _e5 = n;
- if (_e5 <= 1u) {
+ if (_e5 > 1u) {
+ } else {
break;
}
uint _e8 = n;
diff --git a/tests/out/spv/collatz.spvasm b/tests/out/spv/collatz.spvasm
--- a/tests/out/spv/collatz.spvasm
+++ b/tests/out/spv/collatz.spvasm
@@ -57,9 +57,9 @@ OpLoopMerge %22 %24 None
OpBranch %23
%23 = OpLabel
%25 = OpLoad %4 %13
-%27 = OpULessThanEqual %26 %25 %5
+%27 = OpUGreaterThan %26 %25 %5
OpSelectionMerge %28 None
-OpBranchConditional %27 %29 %28
+OpBranchConditional %27 %28 %29
%29 = OpLabel
OpBranch %22
%28 = OpLabel
diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl
--- a/tests/out/wgsl/collatz.wgsl
+++ b/tests/out/wgsl/collatz.wgsl
@@ -12,7 +12,8 @@ fn collatz_iterations(n_base: u32) -> u32 {
n = n_base;
loop {
let _e5 = n;
- if (_e5 <= 1u) {
+ if (_e5 > 1u) {
+ } else {
break;
}
let _e8 = n;
|
While loop in WGSL
See https://github.com/gpuweb/gpuweb/pull/2590
|
2022-03-22T18:25:33Z
|
0.8
|
2022-03-23T09:44:47Z
|
ea832a9eec13560560c017072d4318d5d942e5e5
|
[
"front::wgsl::tests::parse_loop",
"convert_wgsl"
] |
[
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"arena::tests::append_non_unique",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_physical_layout_in_words",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"front::spv::test::parse",
"back::msl::writer::test_stack_size",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::lexer::test_tokens",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::tests::parse_decimal_floats",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_hex_floats",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_parentheses_switch",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_statement",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_storage_buffers",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_texture_store",
"proc::namer::test",
"proc::test_matrix_size",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_texture_query",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_types",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_glsl_variations_check",
"convert_spv_all",
"convert_glsl_folder",
"cube_array",
"sampler1d",
"storage1d",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"invalid_float",
"inconsistent_binding",
"bad_texture_sample_type",
"invalid_integer",
"bad_type_cast",
"bad_texture",
"dead_code",
"last_case_falltrough",
"invalid_local_vars",
"invalid_structs",
"invalid_runtime_sized_arrays",
"local_var_missing_type",
"let_type_mismatch",
"invalid_arrays",
"missing_default_case",
"reserved_identifier_prefix",
"invalid_texture_sample_type",
"invalid_access",
"invalid_functions",
"negative_index",
"struct_member_zero_size",
"unknown_attribute",
"unknown_access",
"unknown_built_in",
"unknown_conservative_depth",
"pointer_type_equivalence",
"missing_bindings",
"unknown_ident",
"unknown_scalar_type",
"unknown_local_function",
"unknown_identifier",
"unknown_storage_class",
"unknown_type",
"unknown_storage_format",
"postfix_pointers",
"reserved_keyword",
"module_scope_identifier_redefinition",
"unknown_shader_stage",
"struct_member_zero_align",
"var_type_mismatch",
"wrong_access_mode",
"valid_access",
"select",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 142)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,725
|
gfx-rs__naga-1725
|
[
"1720"
] |
d40522329bd74bf49df05a80dd95d8712ea93b99
|
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -691,9 +691,9 @@ impl<W: Write> Writer<W> {
ref reject,
} => {
write!(self.out, "{}", level)?;
- write!(self.out, "if (")?;
+ write!(self.out, "if ")?;
self.write_expr(module, condition, func_ctx)?;
- writeln!(self.out, ") {{")?;
+ writeln!(self.out, " {{")?;
let l2 = level.next();
for sta in accept {
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -845,9 +845,9 @@ impl<W: Write> Writer<W> {
} => {
// Start the switch
write!(self.out, "{}", level)?;
- write!(self.out, "switch(")?;
+ write!(self.out, "switch ")?;
self.write_expr(module, selector, func_ctx)?;
- writeln!(self.out, ") {{")?;
+ writeln!(self.out, " {{")?;
let type_postfix = match *func_ctx.info[selector].ty.inner_with(&module.types) {
crate::TypeInner::Scalar {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3602,14 +3602,12 @@ impl Parser {
}
"if" => {
let _ = lexer.next();
- lexer.expect(Token::Paren('('))?;
emitter.start(context.expressions);
let condition = self.parse_general_expression(
lexer,
context.as_expression(block, &mut emitter),
)?;
block.extend(emitter.finish(context.expressions));
- lexer.expect(Token::Paren(')'))?;
let accept = self.parse_block(lexer, context.reborrow(), false)?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3628,14 +3626,12 @@ impl Parser {
// ... else if (...) { ... }
let mut sub_emitter = super::Emitter::default();
- lexer.expect(Token::Paren('('))?;
sub_emitter.start(context.expressions);
let other_condition = self.parse_general_expression(
lexer,
context.as_expression(block, &mut sub_emitter),
)?;
let other_emit = sub_emitter.finish(context.expressions);
- lexer.expect(Token::Paren(')'))?;
let other_block = self.parse_block(lexer, context.reborrow(), false)?;
elsif_stack.push((
elseif_span_start,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3671,7 +3667,6 @@ impl Parser {
"switch" => {
let _ = lexer.next();
emitter.start(context.expressions);
- lexer.expect(Token::Paren('('))?;
let selector = self.parse_general_expression(
lexer,
context.as_expression(block, &mut emitter),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3681,7 +3676,6 @@ impl Parser {
.as_expression(block, &mut emitter)
.resolve_type(selector)?
.scalar_kind();
- lexer.expect(Token::Paren(')'))?;
block.extend(emitter.finish(context.expressions));
lexer.expect(Token::Paren('{'))?;
let mut cases = Vec::new();
|
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -206,6 +206,26 @@ fn parse_statement() {
#[test]
fn parse_if() {
+ parse_str(
+ "
+ fn main() {
+ if true {
+ discard;
+ } else {}
+ if 0 != 1 {}
+ if false {
+ return;
+ } else if true {
+ return;
+ } else {}
+ }
+ ",
+ )
+ .unwrap();
+}
+
+#[test]
+fn parse_parentheses_if() {
parse_str(
"
fn main() {
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -231,11 +251,11 @@ fn parse_loop() {
fn main() {
var i: i32 = 0;
loop {
- if (i == 1) { break; }
+ if i == 1 { break; }
continuing { i = 1; }
}
loop {
- if (i == 0) { continue; }
+ if i == 0 { continue; }
break;
}
}
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -283,6 +303,21 @@ fn parse_switch() {
.unwrap();
}
+#[test]
+fn parse_parentheses_switch() {
+ parse_str(
+ "
+ fn main() {
+ var pos: f32;
+ switch pos > 1.0 {
+ default: { pos = 3.0; }
+ }
+ }
+ ",
+ )
+ .unwrap();
+}
+
#[test]
fn parse_texture_load() {
parse_str(
diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl
--- a/tests/in/boids.wgsl
+++ b/tests/in/boids.wgsl
@@ -27,7 +27,7 @@ struct Particles {
@stage(compute) @workgroup_size(64)
fn main(@builtin(global_invocation_id) global_invocation_id : vec3<u32>) {
let index : u32 = global_invocation_id.x;
- if (index >= NUM_PARTICLES) {
+ if index >= NUM_PARTICLES {
return;
}
diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl
--- a/tests/in/boids.wgsl
+++ b/tests/in/boids.wgsl
@@ -44,24 +44,24 @@ fn main(@builtin(global_invocation_id) global_invocation_id : vec3<u32>) {
var vel : vec2<f32>;
var i : u32 = 0u;
loop {
- if (i >= NUM_PARTICLES) {
+ if i >= NUM_PARTICLES {
break;
}
- if (i == index) {
+ if i == index {
continue;
}
pos = particlesSrc.particles[i].pos;
vel = particlesSrc.particles[i].vel;
- if (distance(pos, vPos) < params.rule1Distance) {
+ if distance(pos, vPos) < params.rule1Distance {
cMass = cMass + pos;
cMassCount = cMassCount + 1;
}
- if (distance(pos, vPos) < params.rule2Distance) {
+ if distance(pos, vPos) < params.rule2Distance {
colVel = colVel - (pos - vPos);
}
- if (distance(pos, vPos) < params.rule3Distance) {
+ if distance(pos, vPos) < params.rule3Distance {
cVel = cVel + vel;
cVelCount = cVelCount + 1;
}
diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl
--- a/tests/in/boids.wgsl
+++ b/tests/in/boids.wgsl
@@ -70,10 +70,10 @@ fn main(@builtin(global_invocation_id) global_invocation_id : vec3<u32>) {
i = i + 1u;
}
}
- if (cMassCount > 0) {
+ if cMassCount > 0 {
cMass = cMass / f32(cMassCount) - vPos;
}
- if (cVelCount > 0) {
+ if cVelCount > 0 {
cVel = cVel / f32(cVelCount);
}
diff --git a/tests/in/boids.wgsl b/tests/in/boids.wgsl
--- a/tests/in/boids.wgsl
+++ b/tests/in/boids.wgsl
@@ -88,16 +88,16 @@ fn main(@builtin(global_invocation_id) global_invocation_id : vec3<u32>) {
vPos = vPos + (vVel * params.deltaT);
// Wrap around boundary
- if (vPos.x < -1.0) {
+ if vPos.x < -1.0 {
vPos.x = 1.0;
}
- if (vPos.x > 1.0) {
+ if vPos.x > 1.0 {
vPos.x = -1.0;
}
- if (vPos.y < -1.0) {
+ if vPos.y < -1.0 {
vPos.y = 1.0;
}
- if (vPos.y > 1.0) {
+ if vPos.y > 1.0 {
vPos.y = -1.0;
}
diff --git a/tests/in/collatz.wgsl b/tests/in/collatz.wgsl
--- a/tests/in/collatz.wgsl
+++ b/tests/in/collatz.wgsl
@@ -15,10 +15,10 @@ fn collatz_iterations(n_base: u32) -> u32 {
var n = n_base;
var i: u32 = 0u;
loop {
- if (n <= 1u) {
+ if n <= 1u {
break;
}
- if (n % 2u == 0u) {
+ if n % 2u == 0u {
n = n / 2u;
}
else {
diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl
--- a/tests/in/control-flow.wgsl
+++ b/tests/in/control-flow.wgsl
@@ -6,7 +6,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
var pos: i32;
// switch without cases
- switch (1) {
+ switch 1 {
default: {
pos = 1;
}
diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl
--- a/tests/in/control-flow.wgsl
+++ b/tests/in/control-flow.wgsl
@@ -14,7 +14,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
// non-empty switch *not* in last-statement-in-function position
// (return statements might be inserted into the switch cases otherwise)
- switch (pos) {
+ switch pos {
case 1: {
pos = 0;
break;
diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl
--- a/tests/in/control-flow.wgsl
+++ b/tests/in/control-flow.wgsl
@@ -41,7 +41,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
}
// non-empty switch in last-statement-in-function position
- switch (pos) {
+ switch pos {
case 1: {
pos = 0;
break;
diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl
--- a/tests/in/control-flow.wgsl
+++ b/tests/in/control-flow.wgsl
@@ -61,7 +61,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
}
fn switch_default_break(i: i32) {
- switch (i) {
+ switch i {
default: {
break;
}
diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl
--- a/tests/in/control-flow.wgsl
+++ b/tests/in/control-flow.wgsl
@@ -80,7 +80,7 @@ fn switch_case_break() {
fn loop_switch_continue(x: i32) {
loop {
- switch (x) {
+ switch x {
case 1: {
continue;
}
diff --git a/tests/in/extra.wgsl b/tests/in/extra.wgsl
--- a/tests/in/extra.wgsl
+++ b/tests/in/extra.wgsl
@@ -11,7 +11,7 @@ struct FragmentIn {
@stage(fragment)
fn main(in: FragmentIn) -> @location(0) vec4<f32> {
- if (in.primitive_index % 2u == 0u) {
+ if in.primitive_index % 2u == 0u {
return in.color;
} else {
return vec4<f32>(vec3<f32>(1.0) - in.color.rgb, in.color.a);
diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl
--- a/tests/in/operators.wgsl
+++ b/tests/in/operators.wgsl
@@ -30,7 +30,7 @@ fn splat() -> vec4<f32> {
fn unary() -> i32 {
let a = 1;
- if (!true) { return a; } else { return ~a; };
+ if !true { return a; } else { return ~a; };
}
fn bool_cast(x: vec3<f32>) -> vec3<f32> {
diff --git a/tests/in/quad.wgsl b/tests/in/quad.wgsl
--- a/tests/in/quad.wgsl
+++ b/tests/in/quad.wgsl
@@ -21,7 +21,7 @@ fn vert_main(
@stage(fragment)
fn frag_main(@location(0) uv : vec2<f32>) -> @location(0) vec4<f32> {
let color = textureSample(u_texture, u_sampler, uv);
- if (color.a == 0.0) {
+ if color.a == 0.0 {
discard;
}
// forcing the expression here to be emitted in order to check the
diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl
--- a/tests/in/shadow.wgsl
+++ b/tests/in/shadow.wgsl
@@ -23,7 +23,7 @@ var t_shadow: texture_depth_2d_array;
var sampler_shadow: sampler_comparison;
fn fetch_shadow(light_id: u32, homogeneous_coords: vec4<f32>) -> f32 {
- if (homogeneous_coords.w <= 0.0) {
+ if homogeneous_coords.w <= 0.0 {
return 1.0;
}
let flip_correction = vec2<f32>(0.5, -0.5);
diff --git a/tests/in/shadow.wgsl b/tests/in/shadow.wgsl
--- a/tests/in/shadow.wgsl
+++ b/tests/in/shadow.wgsl
@@ -44,7 +44,7 @@ fn fs_main(
var color = c_ambient;
var i: u32 = 0u;
loop {
- if (i >= min(u_globals.num_lights.x, c_max_lights)) {
+ if i >= min(u_globals.num_lights.x, c_max_lights) {
break;
}
let light = s_lights.data[i];
diff --git a/tests/out/wgsl/246-collatz-comp.wgsl b/tests/out/wgsl/246-collatz-comp.wgsl
--- a/tests/out/wgsl/246-collatz-comp.wgsl
+++ b/tests/out/wgsl/246-collatz-comp.wgsl
@@ -13,12 +13,12 @@ fn collatz_iterations(n: u32) -> u32 {
n_1 = n;
loop {
let _e7 = n_1;
- if (!((_e7 != u32(1)))) {
+ if !((_e7 != u32(1))) {
break;
}
{
let _e14 = n_1;
- if (((f32(_e14) % f32(2)) == f32(0))) {
+ if ((f32(_e14) % f32(2)) == f32(0)) {
{
let _e22 = n_1;
n_1 = (_e22 / u32(2));
diff --git a/tests/out/wgsl/932-for-loop-if-vert.wgsl b/tests/out/wgsl/932-for-loop-if-vert.wgsl
--- a/tests/out/wgsl/932-for-loop-if-vert.wgsl
+++ b/tests/out/wgsl/932-for-loop-if-vert.wgsl
@@ -3,7 +3,7 @@ fn main_1() {
loop {
let _e2 = i;
- if (!((_e2 < 1))) {
+ if !((_e2 < 1)) {
break;
}
{
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -801,7 +801,7 @@ fn main_1() {
let _e224 = i;
let _e225 = global_2.NumLights;
let _e229 = i;
- if (!(((_e224 < i32(_e225.x)) && (_e229 < 10)))) {
+ if !(((_e224 < i32(_e225.x)) && (_e229 < 10))) {
break;
}
{
diff --git a/tests/out/wgsl/bevy-pbr-frag.wgsl b/tests/out/wgsl/bevy-pbr-frag.wgsl
--- a/tests/out/wgsl/bevy-pbr-frag.wgsl
+++ b/tests/out/wgsl/bevy-pbr-frag.wgsl
@@ -828,7 +828,7 @@ fn main_1() {
let _e261 = i_1;
let _e262 = global_2.NumLights;
let _e266 = i_1;
- if (!(((_e261 < i32(_e262.y)) && (_e266 < 1)))) {
+ if !(((_e261 < i32(_e262.y)) && (_e266 < 1))) {
break;
}
{
diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl
--- a/tests/out/wgsl/boids.wgsl
+++ b/tests/out/wgsl/boids.wgsl
@@ -40,7 +40,7 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
var i: u32 = 0u;
let index = global_invocation_id.x;
- if ((index >= NUM_PARTICLES)) {
+ if (index >= NUM_PARTICLES) {
return;
}
let _e10 = particlesSrc.particles[index].pos;
diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl
--- a/tests/out/wgsl/boids.wgsl
+++ b/tests/out/wgsl/boids.wgsl
@@ -52,11 +52,11 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
colVel = vec2<f32>(0.0, 0.0);
loop {
let _e37 = i;
- if ((_e37 >= NUM_PARTICLES)) {
+ if (_e37 >= NUM_PARTICLES) {
break;
}
let _e39 = i;
- if ((_e39 == index)) {
+ if (_e39 == index) {
continue;
}
let _e42 = i;
diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl
--- a/tests/out/wgsl/boids.wgsl
+++ b/tests/out/wgsl/boids.wgsl
@@ -68,7 +68,7 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
let _e51 = pos;
let _e52 = vPos;
let _e55 = params.rule1Distance;
- if ((distance(_e51, _e52) < _e55)) {
+ if (distance(_e51, _e52) < _e55) {
let _e57 = cMass;
let _e58 = pos;
cMass = (_e57 + _e58);
diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl
--- a/tests/out/wgsl/boids.wgsl
+++ b/tests/out/wgsl/boids.wgsl
@@ -78,7 +78,7 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
let _e63 = pos;
let _e64 = vPos;
let _e67 = params.rule2Distance;
- if ((distance(_e63, _e64) < _e67)) {
+ if (distance(_e63, _e64) < _e67) {
let _e69 = colVel;
let _e70 = pos;
let _e71 = vPos;
diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl
--- a/tests/out/wgsl/boids.wgsl
+++ b/tests/out/wgsl/boids.wgsl
@@ -87,7 +87,7 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
let _e74 = pos;
let _e75 = vPos;
let _e78 = params.rule3Distance;
- if ((distance(_e74, _e75) < _e78)) {
+ if (distance(_e74, _e75) < _e78) {
let _e80 = cVel;
let _e81 = vel;
cVel = (_e80 + _e81);
diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl
--- a/tests/out/wgsl/boids.wgsl
+++ b/tests/out/wgsl/boids.wgsl
@@ -100,14 +100,14 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
}
}
let _e89 = cMassCount;
- if ((_e89 > 0)) {
+ if (_e89 > 0) {
let _e92 = cMass;
let _e93 = cMassCount;
let _e97 = vPos;
cMass = ((_e92 / vec2<f32>(f32(_e93))) - _e97);
}
let _e99 = cVelCount;
- if ((_e99 > 0)) {
+ if (_e99 > 0) {
let _e102 = cVel;
let _e103 = cVelCount;
cVel = (_e102 / vec2<f32>(f32(_e103)));
diff --git a/tests/out/wgsl/boids.wgsl b/tests/out/wgsl/boids.wgsl
--- a/tests/out/wgsl/boids.wgsl
+++ b/tests/out/wgsl/boids.wgsl
@@ -128,19 +128,19 @@ fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
let _e134 = params.deltaT;
vPos = (_e131 + (_e132 * _e134));
let _e138 = vPos.x;
- if ((_e138 < -1.0)) {
+ if (_e138 < -1.0) {
vPos.x = 1.0;
}
let _e144 = vPos.x;
- if ((_e144 > 1.0)) {
+ if (_e144 > 1.0) {
vPos.x = -1.0;
}
let _e150 = vPos.y;
- if ((_e150 < -1.0)) {
+ if (_e150 < -1.0) {
vPos.y = 1.0;
}
let _e156 = vPos.y;
- if ((_e156 > 1.0)) {
+ if (_e156 > 1.0) {
vPos.y = -1.0;
}
let _e164 = vPos;
diff --git a/tests/out/wgsl/collatz.wgsl b/tests/out/wgsl/collatz.wgsl
--- a/tests/out/wgsl/collatz.wgsl
+++ b/tests/out/wgsl/collatz.wgsl
@@ -12,11 +12,11 @@ fn collatz_iterations(n_base: u32) -> u32 {
n = n_base;
loop {
let _e5 = n;
- if ((_e5 <= 1u)) {
+ if (_e5 <= 1u) {
break;
}
let _e8 = n;
- if (((_e8 % 2u) == 0u)) {
+ if ((_e8 % 2u) == 0u) {
let _e13 = n;
n = (_e13 / 2u);
} else {
diff --git a/tests/out/wgsl/constant-array-size-vert.wgsl b/tests/out/wgsl/constant-array-size-vert.wgsl
--- a/tests/out/wgsl/constant-array-size-vert.wgsl
+++ b/tests/out/wgsl/constant-array-size-vert.wgsl
@@ -11,7 +11,7 @@ fn function_() -> vec4<f32> {
loop {
let _e9 = i;
- if (!((_e9 < 42))) {
+ if !((_e9 < 42)) {
break;
}
{
diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl
--- a/tests/out/wgsl/control-flow.wgsl
+++ b/tests/out/wgsl/control-flow.wgsl
@@ -1,5 +1,5 @@
fn switch_default_break(i: i32) {
- switch(i) {
+ switch i {
default: {
break;
}
diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl
--- a/tests/out/wgsl/control-flow.wgsl
+++ b/tests/out/wgsl/control-flow.wgsl
@@ -7,7 +7,7 @@ fn switch_default_break(i: i32) {
}
fn switch_case_break() {
- switch(0) {
+ switch 0 {
case 0: {
break;
}
diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl
--- a/tests/out/wgsl/control-flow.wgsl
+++ b/tests/out/wgsl/control-flow.wgsl
@@ -19,7 +19,7 @@ fn switch_case_break() {
fn loop_switch_continue(x: i32) {
loop {
- switch(x) {
+ switch x {
case 1: {
continue;
}
diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl
--- a/tests/out/wgsl/control-flow.wgsl
+++ b/tests/out/wgsl/control-flow.wgsl
@@ -36,13 +36,13 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
storageBarrier();
workgroupBarrier();
- switch(1) {
+ switch 1 {
default: {
pos = 1;
}
}
let _e4 = pos;
- switch(_e4) {
+ switch _e4 {
case 1: {
pos = 0;
break;
diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl
--- a/tests/out/wgsl/control-flow.wgsl
+++ b/tests/out/wgsl/control-flow.wgsl
@@ -60,14 +60,14 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
pos = 3;
}
}
- switch(0u) {
+ switch 0u {
case 0u: {
}
default: {
}
}
let _e10 = pos;
- switch(_e10) {
+ switch _e10 {
case 1: {
pos = 0;
break;
diff --git a/tests/out/wgsl/extra.wgsl b/tests/out/wgsl/extra.wgsl
--- a/tests/out/wgsl/extra.wgsl
+++ b/tests/out/wgsl/extra.wgsl
@@ -12,7 +12,7 @@ var<push_constant> pc: PushConstants;
@stage(fragment)
fn main(in: FragmentIn) -> @location(0) vec4<f32> {
- if (((in.primitive_index % 2u) == 0u)) {
+ if ((in.primitive_index % 2u) == 0u) {
return in.color;
} else {
return vec4<f32>((vec3<f32>(1.0) - in.color.xyz), in.color.w);
diff --git a/tests/out/wgsl/operators.wgsl b/tests/out/wgsl/operators.wgsl
--- a/tests/out/wgsl/operators.wgsl
+++ b/tests/out/wgsl/operators.wgsl
@@ -26,7 +26,7 @@ fn splat() -> vec4<f32> {
}
fn unary() -> i32 {
- if (!(true)) {
+ if !(true) {
return 1;
} else {
return ~(1);
diff --git a/tests/out/wgsl/quad.wgsl b/tests/out/wgsl/quad.wgsl
--- a/tests/out/wgsl/quad.wgsl
+++ b/tests/out/wgsl/quad.wgsl
@@ -18,7 +18,7 @@ fn vert_main(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>) -> VertexO
@stage(fragment)
fn frag_main(@location(0) uv_1: vec2<f32>) -> @location(0) vec4<f32> {
let color = textureSample(u_texture, u_sampler, uv_1);
- if ((color.w == 0.0)) {
+ if (color.w == 0.0) {
discard;
}
let premultiplied = (color.w * color);
diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl
--- a/tests/out/wgsl/shadow.wgsl
+++ b/tests/out/wgsl/shadow.wgsl
@@ -25,7 +25,7 @@ var t_shadow: texture_depth_2d_array;
var sampler_shadow: sampler_comparison;
fn fetch_shadow(light_id: u32, homogeneous_coords: vec4<f32>) -> f32 {
- if ((homogeneous_coords.w <= 0.0)) {
+ if (homogeneous_coords.w <= 0.0) {
return 1.0;
}
let flip_correction = vec2<f32>(0.5, -0.5);
diff --git a/tests/out/wgsl/shadow.wgsl b/tests/out/wgsl/shadow.wgsl
--- a/tests/out/wgsl/shadow.wgsl
+++ b/tests/out/wgsl/shadow.wgsl
@@ -43,7 +43,7 @@ fn fs_main(@location(0) raw_normal: vec3<f32>, @location(1) position: vec4<f32>)
loop {
let _e12 = i;
let _e15 = u_globals.num_lights.x;
- if ((_e12 >= min(_e15, c_max_lights))) {
+ if (_e12 >= min(_e15, c_max_lights)) {
break;
}
let _e19 = i;
|
Remove parenthesis from conditional statements
https://github.com/gpuweb/gpuweb/pull/2585
|
2022-02-15T18:12:11Z
|
0.8
|
2022-02-15T18:05:06Z
|
ea832a9eec13560560c017072d4318d5d942e5e5
|
[
"front::wgsl::tests::parse_parentheses_switch",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_loop",
"convert_wgsl"
] |
[
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"back::msl::writer::test_stack_size",
"front::spv::test::parse",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_decimal_floats",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::lexer::test_tokens",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_hex_floats",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_parentheses_if",
"front::wgsl::tests::parse_struct",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_texture_store",
"proc::typifier::test_error_size",
"proc::test_matrix_size",
"proc::namer::test",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_load",
"valid::analyzer::uniform_control_flow",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_type_cast",
"convert_spv_all",
"convert_glsl_folder",
"sampler1d",
"cube_array",
"storage1d",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"inconsistent_binding",
"bad_texture_sample_type",
"invalid_float",
"invalid_integer",
"bad_type_cast",
"invalid_texture_sample_type",
"invalid_local_vars",
"local_var_missing_type",
"invalid_arrays",
"bad_texture",
"dead_code",
"invalid_structs",
"last_case_falltrough",
"let_type_mismatch",
"invalid_access",
"invalid_runtime_sized_arrays",
"missing_default_case",
"reserved_identifier_prefix",
"invalid_functions",
"unknown_attribute",
"unknown_access",
"struct_member_zero_align",
"unknown_built_in",
"missing_bindings",
"struct_member_zero_size",
"unknown_conservative_depth",
"negative_index",
"unknown_ident",
"unknown_shader_stage",
"postfix_pointers",
"unknown_scalar_type",
"unknown_storage_class",
"unknown_local_function",
"unknown_storage_format",
"pointer_type_equivalence",
"unknown_identifier",
"unknown_type",
"reserved_keyword",
"module_scope_identifier_redefinition",
"var_type_mismatch",
"wrong_access_mode",
"select",
"valid_access",
"src/front/glsl/mod.rs - front::glsl::Options (line 44)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 142)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,675
|
gfx-rs__naga-1675
|
[
"1582"
] |
76814a83a20391b690ecf4e4a455d8a5768ac3be
|
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -356,9 +356,47 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) {
(Token::UnterminatedString, quote_content)
}
}
- '/' if chars.as_str().starts_with('/') => {
- let _ = chars.position(|c| c == '\n' || c == '\r');
- (Token::Trivia, chars.as_str())
+ '/' => {
+ input = chars.as_str();
+ match chars.next() {
+ Some('/') => {
+ let _ = chars.position(|c| c == '\n' || c == '\r');
+ (Token::Trivia, chars.as_str())
+ }
+ Some('*') => {
+ input = chars.as_str();
+
+ let mut depth = 1;
+ let mut prev = '\0';
+
+ for c in &mut chars {
+ match (prev, c) {
+ ('*', '/') => {
+ prev = '\0';
+ depth -= 1;
+ if depth == 0 {
+ break;
+ }
+ }
+ ('/', '*') => {
+ prev = '\0';
+ depth += 1;
+ }
+ _ => {
+ prev = c;
+ }
+ }
+ }
+
+ if depth > 0 {
+ (Token::UnterminatedBlockComment, input)
+ } else {
+ (Token::Trivia, chars.as_str())
+ }
+ }
+ Some('=') => (Token::AssignmentOperation(cur), chars.as_str()),
+ _ => (Token::Operation(cur), input),
+ }
}
'-' => {
let sub_input = chars.as_str();
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -369,7 +407,7 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) {
_ => (Token::Operation(cur), sub_input),
}
}
- '+' | '*' | '/' | '%' | '^' => {
+ '+' | '*' | '%' | '^' => {
input = chars.as_str();
if chars.next() == Some('=') {
(Token::AssignmentOperation(cur), chars.as_str())
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -72,6 +72,7 @@ pub enum Token<'a> {
Arrow,
Unknown(char),
UnterminatedString,
+ UnterminatedBlockComment,
Trivia,
End,
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -204,6 +205,7 @@ impl<'a> Error<'a> {
Token::Arrow => "->".to_string(),
Token::Unknown(c) => format!("unknown ('{}')", c),
Token::UnterminatedString => "unterminated string".to_string(),
+ Token::UnterminatedBlockComment => "unterminated block comment".to_string(),
Token::Trivia => "trivia".to_string(),
Token::End => "end".to_string(),
}
|
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -673,6 +711,14 @@ fn test_tokens() {
sub_test("No好", &[Token::Word("No"), Token::Unknown('好')]);
sub_test("_No", &[Token::Word("_No")]);
sub_test("\"\u{2}ПЀ\u{0}\"", &[Token::String("\u{2}ПЀ\u{0}")]); // https://github.com/gfx-rs/naga/issues/90
+ sub_test(
+ "*/*/***/*//=/*****//",
+ &[
+ Token::Operation('*'),
+ Token::AssignmentOperation('/'),
+ Token::Operation('/'),
+ ],
+ );
}
#[test]
|
error occurs in validating the block comment in WGSL
WGSL allows the block comment, and it works fine in WebGPU apps. Here is an example of using block (or multi-line) comment from the official WGSL site (https://www.w3.org/TR/WGSL/#comments):
EXAMPLE: COMMENTS
let f = 1.5; // This is line-ending comment.
let g = 2.5; /* This is a block comment
that spans lines.
/* Block comments can nest.
*/
But all block comments must terminate.
*/
However, naga gives the following error for this block comment in wgpu apps:
Shader error:
error: expected global item ('struct', 'let', 'var', 'type', ';', 'fn') or the end of the file, found '/'
How to get around this error?
|
We need to implement block comments in WGSL.
|
2022-01-19T22:45:35Z
|
0.8
|
2022-01-19T19:48:05Z
|
ea832a9eec13560560c017072d4318d5d942e5e5
|
[
"front::wgsl::lexer::test_tokens"
] |
[
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::constants::tests::unary_op",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::spv::test::parse",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_decimal_floats",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::expressions",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_hex_floats",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_loop",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::namer::test",
"front::wgsl::tests::parse_storage_buffers",
"proc::typifier::test_error_size",
"proc::test_matrix_size",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_texture_store",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_type_inference",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_spv_all",
"convert_glsl_folder",
"convert_wgsl",
"cube_array",
"sampler1d",
"storage1d",
"geometry",
"sample_rate_shading",
"storage_image_formats",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"bad_texture_sample_type",
"inconsistent_binding",
"bad_type_cast",
"invalid_float",
"invalid_integer",
"invalid_texture_sample_type",
"last_case_falltrough",
"dead_code",
"invalid_local_vars",
"bad_texture",
"invalid_structs",
"invalid_arrays",
"let_type_mismatch",
"invalid_runtime_sized_arrays",
"local_var_missing_type",
"reserved_identifier_prefix",
"invalid_access",
"missing_default_case",
"invalid_functions",
"struct_member_zero_align",
"struct_member_zero_size",
"unknown_attribute",
"unknown_access",
"unknown_built_in",
"negative_index",
"unknown_conservative_depth",
"missing_bindings",
"unknown_shader_stage",
"pointer_type_equivalence",
"unknown_storage_class",
"unknown_local_function",
"unknown_identifier",
"reserved_keyword",
"unknown_scalar_type",
"unknown_ident",
"postfix_pointers",
"unknown_storage_format",
"module_scope_identifier_redefinition",
"unknown_type",
"zero_array_stride",
"var_type_mismatch",
"select",
"valid_access",
"wrong_access_mode",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
gfx-rs/naga
| 1,663
|
gfx-rs__naga-1663
|
[
"1642"
] |
894530e5b4814e08ec38afc674ffd558eeaedde4
|
diff --git a/.gitignore b/.gitignore
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,5 @@ Cargo.lock
/*.frag
/*.comp
/*.wgsl
+/*.hlsl
+/*.txt
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,18 @@
# Change Log
+### v0.8.2 (2022-01-11)
+ - validator:
+ - check structure resource types
+ - MSL-out:
+ - fix data packing functions
+ - fix 1D texture loads
+ - SPV-in:
+ - more operations are sign-agnostic
+ - SPV-out:
+ - fix modulo operator
+ - WGSL-in:
+ - improve type mismatch errors
+
### v0.8.1 (2021-12-29)
- API:
- make `WithSpan` clonable
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "naga"
-version = "0.8.1"
+version = "0.8.2"
authors = ["Naga Developers"]
edition = "2018"
description = "Shader translation infrastructure"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -20,7 +20,7 @@ bitflags = "1"
bit-set = "0.5"
codespan-reporting = { version = "0.11.0", optional = true }
rustc-hash = "1.1.0"
-indexmap = "1.6" # 1.7 has MSRV 1.49
+indexmap = "~1.6" # 1.7 has MSRV 1.49
log = "0.4"
num-traits = "0.2"
spirv = { version = "0.2", optional = true }
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "naga-cli"
-version = "0.4.0"
+version = "0.8.0"
authors = ["Naga Developers"]
edition = "2018"
description = "Shader translation command line tool"
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -14,7 +14,7 @@ name = "naga"
path = "src/main.rs"
[dependencies]
-naga = { path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate"] }
+naga = { path = "../", features = ["validate", "span", "wgsl-in", "wgsl-out", "glsl-in", "glsl-out", "spv-in", "spv-out", "msl-out", "hlsl-out", "dot-out", "glsl-validate"], version = "0.8" }
log = "0.4"
codespan-reporting = "0.11"
env_logger = "0.8"
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -582,7 +582,10 @@ impl<W: Write> Writer<W> {
match dim {
crate::ImageDimension::D1 => {
write!(self.out, "int(")?;
- self.put_image_query(image, "width", level, context)?;
+ // Since 1D textures never have mipmaps, MSL requires that the
+ // `level` argument be a constexpr 0. It's simplest for us just
+ // to omit the level entirely.
+ self.put_image_query(image, "width", None, context)?;
write!(self.out, ")")?;
}
crate::ImageDimension::D2 => {
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -996,8 +999,18 @@ impl<W: Write> Writer<W> {
self.put_expression(expr, context, true)?;
}
if let Some(index) = index {
- write!(self.out, ", ")?;
- self.put_expression(index, context, true)?;
+ // Metal requires that the `level` argument to
+ // `texture1d::read` be a constexpr equal to zero.
+ if let crate::TypeInner::Image {
+ dim: crate::ImageDimension::D1,
+ ..
+ } = *context.resolve_type(image)
+ {
+ // The argument defaults to zero.
+ } else {
+ write!(self.out, ", ")?;
+ self.put_expression(index, context, true)?
+ }
}
write!(self.out, ")")?;
}
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -1188,10 +1201,10 @@ impl<W: Write> Writer<W> {
Mf::ExtractBits => "extract_bits",
Mf::InsertBits => "insert_bits",
// data packing
- Mf::Pack4x8snorm => "pack_float_to_unorm4x8",
- Mf::Pack4x8unorm => "pack_float_to_snorm4x8",
- Mf::Pack2x16snorm => "pack_float_to_unorm2x16",
- Mf::Pack2x16unorm => "pack_float_to_snorm2x16",
+ Mf::Pack4x8snorm => "pack_float_to_snorm4x8",
+ Mf::Pack4x8unorm => "pack_float_to_unorm4x8",
+ Mf::Pack2x16snorm => "pack_float_to_snorm2x16",
+ Mf::Pack2x16unorm => "pack_float_to_unorm2x16",
Mf::Pack2x16float => "",
// data unpacking
Mf::Unpack4x8snorm => "unpack_snorm4x8_to_float",
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -390,7 +390,7 @@ impl<'w> BlockContext<'w> {
crate::BinaryOperator::Modulo => match left_ty_inner.scalar_kind() {
Some(crate::ScalarKind::Sint) => spirv::Op::SMod,
Some(crate::ScalarKind::Uint) => spirv::Op::UMod,
- Some(crate::ScalarKind::Float) => spirv::Op::FMod,
+ Some(crate::ScalarKind::Float) => spirv::Op::FRem,
_ => unimplemented!(),
},
crate::BinaryOperator::Equal => match left_ty_inner.scalar_kind() {
diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs
--- a/src/front/spv/convert.rs
+++ b/src/front/spv/convert.rs
@@ -13,6 +13,7 @@ pub(super) fn map_binary_operator(word: spirv::Op) -> Result<crate::BinaryOperat
Op::IMul | Op::FMul => Ok(BinaryOperator::Multiply),
Op::UDiv | Op::SDiv | Op::FDiv => Ok(BinaryOperator::Divide),
Op::UMod | Op::SMod | Op::FMod => Ok(BinaryOperator::Modulo),
+ Op::SRem => Ok(BinaryOperator::Modulo),
// Relational and Logical Instructions
Op::IEqual | Op::FOrdEqual | Op::FUnordEqual | Op::LogicalEqual => {
Ok(BinaryOperator::Equal)
diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs
--- a/src/front/spv/convert.rs
+++ b/src/front/spv/convert.rs
@@ -34,6 +35,9 @@ pub(super) fn map_binary_operator(word: spirv::Op) -> Result<crate::BinaryOperat
| Op::SGreaterThanEqual
| Op::FOrdGreaterThanEqual
| Op::FUnordGreaterThanEqual => Ok(BinaryOperator::GreaterEqual),
+ Op::BitwiseOr => Ok(BinaryOperator::InclusiveOr),
+ Op::BitwiseXor => Ok(BinaryOperator::ExclusiveOr),
+ Op::BitwiseAnd => Ok(BinaryOperator::And),
_ => Err(Error::UnknownBinaryOperator(word)),
}
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -854,6 +854,59 @@ impl<I: Iterator<Item = u32>> Parser<I> {
Ok(())
}
+ /// A more complicated version of the unary op,
+ /// where we force the operand to have the same type as the result.
+ fn parse_expr_unary_op_sign_adjusted(
+ &mut self,
+ ctx: &mut BlockContext,
+ emitter: &mut super::Emitter,
+ block: &mut crate::Block,
+ block_id: spirv::Word,
+ body_idx: usize,
+ op: crate::UnaryOperator,
+ ) -> Result<(), Error> {
+ let start = self.data_offset;
+ let result_type_id = self.next()?;
+ let result_id = self.next()?;
+ let p1_id = self.next()?;
+ let span = self.span_from_with_op(start);
+
+ let p1_lexp = self.lookup_expression.lookup(p1_id)?;
+ let left = self.get_expr_handle(p1_id, p1_lexp, ctx, emitter, block, body_idx);
+
+ let result_lookup_ty = self.lookup_type.lookup(result_type_id)?;
+ let kind = ctx.type_arena[result_lookup_ty.handle]
+ .inner
+ .scalar_kind()
+ .unwrap();
+
+ let expr = crate::Expression::Unary {
+ op,
+ expr: if p1_lexp.type_id == result_type_id {
+ left
+ } else {
+ ctx.expressions.append(
+ crate::Expression::As {
+ expr: left,
+ kind,
+ convert: None,
+ },
+ span,
+ )
+ },
+ };
+
+ self.lookup_expression.insert(
+ result_id,
+ LookupExpression {
+ handle: ctx.expressions.append(expr, span),
+ type_id: result_type_id,
+ block_id,
+ },
+ );
+ Ok(())
+ }
+
/// A more complicated version of the binary op,
/// where we force the operand to have the same type as the result.
/// This is mostly needed for "i++" and "i--" coming from GLSL.
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1634,7 +1687,24 @@ impl<I: Iterator<Item = u32>> Parser<I> {
let root_handle = get_expr_handle!(composite_id, root_lexp);
let root_type_lookup = self.lookup_type.lookup(root_lexp.type_id)?;
let index_lexp = self.lookup_expression.lookup(index_id)?;
- let index_handle = get_expr_handle!(index_id, index_lexp);
+ let mut index_handle = get_expr_handle!(index_id, index_lexp);
+ let index_type = self.lookup_type.lookup(index_lexp.type_id)?.handle;
+
+ // SPIR-V allows signed and unsigned indices but naga's is strict about
+ // types and since the `index_constants` are all signed integers, we need
+ // to cast the index to a signed integer if it's unsigned.
+ if let Some(crate::ScalarKind::Uint) =
+ ctx.type_arena[index_type].inner.scalar_kind()
+ {
+ index_handle = ctx.expressions.append(
+ crate::Expression::As {
+ expr: index_handle,
+ kind: crate::ScalarKind::Sint,
+ convert: None,
+ },
+ span,
+ )
+ }
let num_components = match ctx.type_arena[root_type_lookup.handle].inner {
crate::TypeInner::Vector { size, .. } => size as usize,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1872,9 +1942,24 @@ impl<I: Iterator<Item = u32>> Parser<I> {
// Arithmetic Instructions +, -, *, /, %
Op::SNegate | Op::FNegate => {
inst.expect(4)?;
- parse_expr_op!(crate::UnaryOperator::Negate, UNARY)?;
+ self.parse_expr_unary_op_sign_adjusted(
+ ctx,
+ &mut emitter,
+ &mut block,
+ block_id,
+ body_idx,
+ crate::UnaryOperator::Negate,
+ )?;
}
- Op::IAdd | Op::ISub | Op::IMul => {
+ Op::IAdd
+ | Op::ISub
+ | Op::IMul
+ | Op::BitwiseOr
+ | Op::BitwiseXor
+ | Op::BitwiseAnd
+ | Op::SDiv
+ | Op::SMod
+ | Op::SRem => {
inst.expect(5)?;
let operator = map_binary_operator(inst.op)?;
self.parse_expr_binary_op_sign_adjusted(
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1912,11 +1997,11 @@ impl<I: Iterator<Item = u32>> Parser<I> {
inst.expect(5)?;
parse_expr_op!(crate::BinaryOperator::Multiply, BINARY)?;
}
- Op::SDiv | Op::UDiv | Op::FDiv => {
+ Op::UDiv | Op::FDiv => {
inst.expect(5)?;
parse_expr_op!(crate::BinaryOperator::Divide, BINARY)?;
}
- Op::SMod | Op::UMod | Op::FMod | Op::SRem | Op::FRem => {
+ Op::UMod | Op::FMod | Op::FRem => {
inst.expect(5)?;
parse_expr_op!(crate::BinaryOperator::Modulo, BINARY)?;
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2151,19 +2236,14 @@ impl<I: Iterator<Item = u32>> Parser<I> {
// Bitwise instructions
Op::Not => {
inst.expect(4)?;
- parse_expr_op!(crate::UnaryOperator::Not, UNARY)?;
- }
- Op::BitwiseOr => {
- inst.expect(5)?;
- parse_expr_op!(crate::BinaryOperator::InclusiveOr, BINARY)?;
- }
- Op::BitwiseXor => {
- inst.expect(5)?;
- parse_expr_op!(crate::BinaryOperator::ExclusiveOr, BINARY)?;
- }
- Op::BitwiseAnd => {
- inst.expect(5)?;
- parse_expr_op!(crate::BinaryOperator::And, BINARY)?;
+ self.parse_expr_unary_op_sign_adjusted(
+ ctx,
+ &mut emitter,
+ &mut block,
+ block_id,
+ body_idx,
+ crate::UnaryOperator::Not,
+ )?;
}
Op::ShiftRightLogical => {
inst.expect(5)?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -164,7 +164,7 @@ pub enum Error<'a> {
ZeroSizeOrAlign(Span),
InconsistentBinding(Span),
UnknownLocalFunction(Span),
- InitializationTypeMismatch(Span, Handle<crate::Type>),
+ InitializationTypeMismatch(Span, String),
MissingType(Span),
InvalidAtomicPointer(Span),
InvalidAtomicOperandType(Span),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -414,7 +414,7 @@ impl<'a> Error<'a> {
notes: vec![],
},
Error::InitializationTypeMismatch(ref name_span, ref expected_ty) => ParseError {
- message: format!("the type of `{}` is expected to be {:?}", &source[name_span.clone()], expected_ty),
+ message: format!("the type of `{}` is expected to be `{}`", &source[name_span.clone()], expected_ty),
labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())],
notes: vec![],
},
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3448,7 +3448,10 @@ impl Parser {
given_inner,
expr_inner
);
- return Err(Error::InitializationTypeMismatch(name_span, ty));
+ return Err(Error::InitializationTypeMismatch(
+ name_span,
+ expr_inner.to_wgsl(context.types, context.constants),
+ ));
}
}
block.extend(emitter.finish(context.expressions));
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3513,7 +3516,8 @@ impl Parser {
expr_inner
);
return Err(Error::InitializationTypeMismatch(
- name_span, ty,
+ name_span,
+ expr_inner.to_wgsl(context.types, context.constants),
));
}
ty
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4288,7 +4292,22 @@ impl Parser {
crate::ConstantInner::Composite { ty, components: _ } => ty == explicit_ty,
};
if !type_match {
- return Err(Error::InitializationTypeMismatch(name_span, explicit_ty));
+ let exptected_inner_str = match con.inner {
+ crate::ConstantInner::Scalar { width, value } => {
+ crate::TypeInner::Scalar {
+ kind: value.scalar_kind(),
+ width,
+ }
+ .to_wgsl(&module.types, &module.constants)
+ }
+ crate::ConstantInner::Composite { .. } => module.types[explicit_ty]
+ .inner
+ .to_wgsl(&module.types, &module.constants),
+ };
+ return Err(Error::InitializationTypeMismatch(
+ name_span,
+ exptected_inner_str,
+ ));
}
}
diff --git a/src/valid/interface.rs b/src/valid/interface.rs
--- a/src/valid/interface.rs
+++ b/src/valid/interface.rs
@@ -355,13 +355,7 @@ impl super::Validator {
true,
)
}
- crate::StorageClass::Handle => {
- match types[var.ty].inner {
- crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => {}
- _ => return Err(GlobalVariableError::InvalidType),
- };
- (TypeFlags::empty(), true)
- }
+ crate::StorageClass::Handle => (TypeFlags::empty(), true),
crate::StorageClass::Private | crate::StorageClass::WorkGroup => {
(TypeFlags::DATA | TypeFlags::SIZED, false)
}
diff --git a/src/valid/interface.rs b/src/valid/interface.rs
--- a/src/valid/interface.rs
+++ b/src/valid/interface.rs
@@ -378,6 +372,16 @@ impl super::Validator {
}
};
+ let is_handle = var.class == crate::StorageClass::Handle;
+ let good_type = match types[var.ty].inner {
+ crate::TypeInner::Struct { .. } => !is_handle,
+ crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => is_handle,
+ _ => false,
+ };
+ if is_resource && !good_type {
+ return Err(GlobalVariableError::InvalidType);
+ }
+
if !type_info.flags.contains(required_type_flags) {
return Err(GlobalVariableError::MissingTypeFlags {
seen: type_info.flags,
|
diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl
--- a/tests/in/image.wgsl
+++ b/tests/in/image.wgsl
@@ -10,6 +10,8 @@ var image_storage_src: texture_storage_2d<rgba8uint, read>;
var image_array_src: texture_2d_array<u32>;
[[group(0), binding(6)]]
var image_dup_src: texture_storage_1d<r32uint,read>; // for #1307
+[[group(0), binding(7)]]
+var image_1d_src: texture_1d<u32>;
[[group(0), binding(2)]]
var image_dst: texture_storage_1d<r32uint,write>;
diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl
--- a/tests/in/image.wgsl
+++ b/tests/in/image.wgsl
@@ -25,7 +27,8 @@ fn main(
let value2 = textureLoad(image_multisampled_src, itc, i32(local_id.z));
let value4 = textureLoad(image_storage_src, itc);
let value5 = textureLoad(image_array_src, itc, i32(local_id.z), i32(local_id.z) + 1);
- textureStore(image_dst, itc.x, value1 + value2 + value4 + value5);
+ let value6 = textureLoad(image_1d_src, i32(local_id.x), i32(local_id.z));
+ textureStore(image_dst, itc.x, value1 + value2 + value4 + value5 + value6);
}
[[stage(compute), workgroup_size(16, 1, 1)]]
diff --git a/tests/in/image.wgsl b/tests/in/image.wgsl
--- a/tests/in/image.wgsl
+++ b/tests/in/image.wgsl
@@ -55,6 +58,7 @@ var image_aa: texture_multisampled_2d<f32>;
[[stage(vertex)]]
fn queries() -> [[builtin(position)]] vec4<f32> {
let dim_1d = textureDimensions(image_1d);
+ let dim_1d_lod = textureDimensions(image_1d, i32(dim_1d));
let dim_2d = textureDimensions(image_2d);
let dim_2d_lod = textureDimensions(image_2d, 1);
let dim_2d_array = textureDimensions(image_2d_array);
diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl
--- a/tests/out/glsl/image.main.Compute.glsl
+++ b/tests/out/glsl/image.main.Compute.glsl
@@ -14,6 +14,8 @@ layout(rgba8ui) readonly uniform highp uimage2D _group_0_binding_1_cs;
uniform highp usampler2DArray _group_0_binding_5_cs;
+uniform highp usampler2D _group_0_binding_7_cs;
+
layout(r32ui) writeonly uniform highp uimage2D _group_0_binding_2_cs;
diff --git a/tests/out/glsl/image.main.Compute.glsl b/tests/out/glsl/image.main.Compute.glsl
--- a/tests/out/glsl/image.main.Compute.glsl
+++ b/tests/out/glsl/image.main.Compute.glsl
@@ -25,7 +27,8 @@ void main() {
uvec4 value2_ = texelFetch(_group_0_binding_3_cs, itc, int(local_id.z));
uvec4 value4_ = imageLoad(_group_0_binding_1_cs, itc);
uvec4 value5_ = texelFetch(_group_0_binding_5_cs, ivec3(itc, int(local_id.z)), (int(local_id.z) + 1));
- imageStore(_group_0_binding_2_cs, ivec2(itc.x, 0.0), (((value1_ + value2_) + value4_) + value5_));
+ uvec4 value6_ = texelFetch(_group_0_binding_7_cs, ivec2(int(local_id.x), 0.0), int(local_id.z));
+ imageStore(_group_0_binding_2_cs, ivec2(itc.x, 0.0), ((((value1_ + value2_) + value4_) + value5_) + value6_));
return;
}
diff --git a/tests/out/glsl/image.queries.Vertex.glsl b/tests/out/glsl/image.queries.Vertex.glsl
--- a/tests/out/glsl/image.queries.Vertex.glsl
+++ b/tests/out/glsl/image.queries.Vertex.glsl
@@ -19,6 +19,7 @@ uniform highp sampler3D _group_0_binding_5_vs;
void main() {
int dim_1d = textureSize(_group_0_binding_0_vs, 0).x;
+ int dim_1d_lod = textureSize(_group_0_binding_0_vs, int(dim_1d)).x;
ivec2 dim_2d = textureSize(_group_0_binding_1_vs, 0).xy;
ivec2 dim_2d_lod = textureSize(_group_0_binding_1_vs, 1).xy;
ivec2 dim_2d_array = textureSize(_group_0_binding_2_vs, 0).xy;
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -5,6 +5,7 @@ Texture2DMS<float> image_depth_multisampled_src : register(t4);
RWTexture2D<uint4> image_storage_src : register(u1);
Texture2DArray<uint4> image_array_src : register(t5);
RWTexture1D<uint4> image_dup_src : register(u6);
+Texture1D<uint4> image_1d_src : register(t7);
RWTexture1D<uint4> image_dst : register(u2);
Texture1D<float4> image_1d : register(t0);
Texture2D<float4> image_2d : register(t1);
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -33,7 +34,8 @@ void main(uint3 local_id : SV_GroupThreadID)
uint4 value2_ = image_multisampled_src.Load(itc, int(local_id.z));
uint4 value4_ = image_storage_src.Load(itc);
uint4 value5_ = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1)));
- image_dst[itc.x] = (((value1_ + value2_) + value4_) + value5_);
+ uint4 value6_ = image_1d_src.Load(int2(int(local_id.x), int(local_id.z)));
+ image_dst[itc.x] = ((((value1_ + value2_) + value4_) + value5_) + value6_);
return;
}
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -54,6 +56,13 @@ int NagaDimensions1D(Texture1D<float4> tex)
return ret.x;
}
+int NagaMipDimensions1D(Texture1D<float4> tex, uint mip_level)
+{
+ uint4 ret;
+ tex.GetDimensions(mip_level, ret.x, ret.y);
+ return ret.x;
+}
+
int2 NagaDimensions2D(Texture2D<float4> tex)
{
uint4 ret;
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -127,6 +136,7 @@ int3 NagaMipDimensions3D(Texture3D<float4> tex, uint mip_level)
float4 queries() : SV_Position
{
int dim_1d = NagaDimensions1D(image_1d);
+ int dim_1d_lod = NagaMipDimensions1D(image_1d, int(dim_1d));
int2 dim_2d = NagaDimensions2D(image_2d);
int2 dim_2d_lod = NagaMipDimensions2D(image_2d, 1);
int2 dim_2d_array = NagaDimensions2DArray(image_2d_array);
diff --git a/tests/out/msl/bits.msl b/tests/out/msl/bits.msl
--- a/tests/out/msl/bits.msl
+++ b/tests/out/msl/bits.msl
@@ -24,13 +24,13 @@ kernel void main_(
f2_ = metal::float2(0.0);
f4_ = metal::float4(0.0);
metal::float4 _e28 = f4_;
- u = metal::pack_float_to_unorm4x8(_e28);
+ u = metal::pack_float_to_snorm4x8(_e28);
metal::float4 _e30 = f4_;
- u = metal::pack_float_to_snorm4x8(_e30);
+ u = metal::pack_float_to_unorm4x8(_e30);
metal::float2 _e32 = f2_;
- u = metal::pack_float_to_unorm2x16(_e32);
+ u = metal::pack_float_to_snorm2x16(_e32);
metal::float2 _e34 = f2_;
- u = metal::pack_float_to_snorm2x16(_e34);
+ u = metal::pack_float_to_unorm2x16(_e34);
metal::float2 _e36 = f2_;
u = as_type<uint>(half2(_e36));
metal::uint _e38 = u;
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -2,7 +2,7 @@
#include <metal_stdlib>
#include <simd/simd.h>
-constant metal::int2 const_type_8_ = {3, 1};
+constant metal::int2 const_type_9_ = {3, 1};
struct main_Input {
};
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -12,6 +12,7 @@ kernel void main_(
, metal::texture2d_ms<uint, metal::access::read> image_multisampled_src [[user(fake0)]]
, metal::texture2d<uint, metal::access::read> image_storage_src [[user(fake0)]]
, metal::texture2d_array<uint, metal::access::sample> image_array_src [[user(fake0)]]
+, metal::texture1d<uint, metal::access::sample> image_1d_src [[user(fake0)]]
, metal::texture1d<uint, metal::access::write> image_dst [[user(fake0)]]
) {
metal::int2 dim = int2(image_storage_src.get_width(), image_storage_src.get_height());
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -20,7 +21,8 @@ kernel void main_(
metal::uint4 value2_ = image_multisampled_src.read(metal::uint2(itc), static_cast<int>(local_id.z));
metal::uint4 value4_ = image_storage_src.read(metal::uint2(itc));
metal::uint4 value5_ = image_array_src.read(metal::uint2(itc), static_cast<int>(local_id.z), static_cast<int>(local_id.z) + 1);
- image_dst.write(((value1_ + value2_) + value4_) + value5_, metal::uint(itc.x));
+ metal::uint4 value6_ = image_1d_src.read(metal::uint(static_cast<int>(local_id.x)));
+ image_dst.write((((value1_ + value2_) + value4_) + value5_) + value6_, metal::uint(itc.x));
return;
}
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -53,6 +55,7 @@ vertex queriesOutput queries(
, metal::texture3d<float, metal::access::sample> image_3d [[user(fake0)]]
) {
int dim_1d = int(image_1d.get_width());
+ int dim_1d_lod = int(image_1d.get_width());
metal::int2 dim_2d = int2(image_2d.get_width(), image_2d.get_height());
metal::int2 dim_2d_lod = int2(image_2d.get_width(1), image_2d.get_height(1));
metal::int2 dim_2d_array = int2(image_2d_array.get_width(), image_2d_array.get_height());
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -103,9 +106,9 @@ fragment sampleOutput sample(
metal::float2 tc = metal::float2(0.5);
metal::float4 s1d = image_1d.sample(sampler_reg, tc.x);
metal::float4 s2d = image_2d.sample(sampler_reg, tc);
- metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type_8_);
+ metal::float4 s2d_offset = image_2d.sample(sampler_reg, tc, const_type_9_);
metal::float4 s2d_level = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284));
- metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_8_);
+ metal::float4 s2d_level_offset = image_2d.sample(sampler_reg, tc, metal::level(2.299999952316284), const_type_9_);
return sampleOutput { (((s1d + s2d) + s2d_offset) + s2d_level) + s2d_level_offset };
}
diff --git a/tests/out/msl/image.msl b/tests/out/msl/image.msl
--- a/tests/out/msl/image.msl
+++ b/tests/out/msl/image.msl
@@ -135,9 +138,9 @@ fragment gatherOutput gather(
) {
metal::float2 tc_2 = metal::float2(0.5);
metal::float4 s2d_1 = image_2d.gather(sampler_reg, tc_2, int2(0), metal::component::y);
- metal::float4 s2d_offset_1 = image_2d.gather(sampler_reg, tc_2, const_type_8_, metal::component::w);
+ metal::float4 s2d_offset_1 = image_2d.gather(sampler_reg, tc_2, const_type_9_, metal::component::w);
metal::float4 s2d_depth_1 = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5);
- metal::float4 s2d_depth_offset = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5, const_type_8_);
+ metal::float4 s2d_depth_offset = image_2d_depth.gather_compare(sampler_cmp, tc_2, 0.5, const_type_9_);
return gatherOutput { ((s2d_1 + s2d_offset_1) + s2d_depth_1) + s2d_depth_offset };
}
diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm
--- a/tests/out/spv/image.spvasm
+++ b/tests/out/spv/image.spvasm
@@ -1,7 +1,7 @@
; SPIR-V
; Version: 1.1
; Generator: rspirv
-; Bound: 280
+; Bound: 292
OpCapability SampledCubeArray
OpCapability ImageQuery
OpCapability Image1D
diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm
--- a/tests/out/spv/image.spvasm
+++ b/tests/out/spv/image.spvasm
@@ -9,93 +9,96 @@ OpCapability Shader
OpCapability Sampled1D
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
-OpEntryPoint GLCompute %69 "main" %66
-OpEntryPoint GLCompute %107 "depth_load" %105
-OpEntryPoint Vertex %128 "queries" %126
-OpEntryPoint Vertex %176 "levels_queries" %175
-OpEntryPoint Fragment %205 "sample" %204
-OpEntryPoint Fragment %232 "sample_comparison" %230
-OpEntryPoint Fragment %246 "gather" %245
-OpEntryPoint Fragment %268 "depth_no_comparison" %267
-OpExecutionMode %69 LocalSize 16 1 1
-OpExecutionMode %107 LocalSize 16 1 1
-OpExecutionMode %205 OriginUpperLeft
-OpExecutionMode %232 OriginUpperLeft
-OpExecutionMode %246 OriginUpperLeft
-OpExecutionMode %268 OriginUpperLeft
+OpEntryPoint GLCompute %72 "main" %69
+OpEntryPoint GLCompute %117 "depth_load" %115
+OpEntryPoint Vertex %138 "queries" %136
+OpEntryPoint Vertex %188 "levels_queries" %187
+OpEntryPoint Fragment %217 "sample" %216
+OpEntryPoint Fragment %244 "sample_comparison" %242
+OpEntryPoint Fragment %258 "gather" %257
+OpEntryPoint Fragment %280 "depth_no_comparison" %279
+OpExecutionMode %72 LocalSize 16 1 1
+OpExecutionMode %117 LocalSize 16 1 1
+OpExecutionMode %217 OriginUpperLeft
+OpExecutionMode %244 OriginUpperLeft
+OpExecutionMode %258 OriginUpperLeft
+OpExecutionMode %280 OriginUpperLeft
OpSource GLSL 450
-OpName %31 "image_mipmapped_src"
-OpName %33 "image_multisampled_src"
-OpName %35 "image_depth_multisampled_src"
-OpName %37 "image_storage_src"
-OpName %39 "image_array_src"
-OpName %41 "image_dup_src"
-OpName %43 "image_dst"
-OpName %45 "image_1d"
-OpName %47 "image_2d"
-OpName %49 "image_2d_array"
-OpName %51 "image_cube"
-OpName %53 "image_cube_array"
-OpName %55 "image_3d"
-OpName %57 "image_aa"
-OpName %59 "sampler_reg"
-OpName %61 "sampler_cmp"
-OpName %63 "image_2d_depth"
-OpName %66 "local_id"
-OpName %69 "main"
-OpName %105 "local_id"
-OpName %107 "depth_load"
-OpName %128 "queries"
-OpName %176 "levels_queries"
-OpName %205 "sample"
-OpName %232 "sample_comparison"
-OpName %246 "gather"
-OpName %268 "depth_no_comparison"
-OpDecorate %31 DescriptorSet 0
-OpDecorate %31 Binding 0
-OpDecorate %33 DescriptorSet 0
-OpDecorate %33 Binding 3
-OpDecorate %35 DescriptorSet 0
-OpDecorate %35 Binding 4
-OpDecorate %37 NonWritable
-OpDecorate %37 DescriptorSet 0
-OpDecorate %37 Binding 1
-OpDecorate %39 DescriptorSet 0
-OpDecorate %39 Binding 5
-OpDecorate %41 NonWritable
-OpDecorate %41 DescriptorSet 0
-OpDecorate %41 Binding 6
-OpDecorate %43 NonReadable
-OpDecorate %43 DescriptorSet 0
-OpDecorate %43 Binding 2
-OpDecorate %45 DescriptorSet 0
-OpDecorate %45 Binding 0
-OpDecorate %47 DescriptorSet 0
-OpDecorate %47 Binding 1
-OpDecorate %49 DescriptorSet 0
-OpDecorate %49 Binding 2
-OpDecorate %51 DescriptorSet 0
-OpDecorate %51 Binding 3
-OpDecorate %53 DescriptorSet 0
-OpDecorate %53 Binding 4
-OpDecorate %55 DescriptorSet 0
-OpDecorate %55 Binding 5
-OpDecorate %57 DescriptorSet 0
-OpDecorate %57 Binding 6
-OpDecorate %59 DescriptorSet 1
-OpDecorate %59 Binding 0
-OpDecorate %61 DescriptorSet 1
-OpDecorate %61 Binding 1
-OpDecorate %63 DescriptorSet 1
-OpDecorate %63 Binding 2
-OpDecorate %66 BuiltIn LocalInvocationId
-OpDecorate %105 BuiltIn LocalInvocationId
-OpDecorate %126 BuiltIn Position
-OpDecorate %175 BuiltIn Position
-OpDecorate %204 Location 0
-OpDecorate %230 Location 0
-OpDecorate %245 Location 0
-OpDecorate %267 Location 0
+OpName %32 "image_mipmapped_src"
+OpName %34 "image_multisampled_src"
+OpName %36 "image_depth_multisampled_src"
+OpName %38 "image_storage_src"
+OpName %40 "image_array_src"
+OpName %42 "image_dup_src"
+OpName %44 "image_1d_src"
+OpName %46 "image_dst"
+OpName %48 "image_1d"
+OpName %50 "image_2d"
+OpName %52 "image_2d_array"
+OpName %54 "image_cube"
+OpName %56 "image_cube_array"
+OpName %58 "image_3d"
+OpName %60 "image_aa"
+OpName %62 "sampler_reg"
+OpName %64 "sampler_cmp"
+OpName %66 "image_2d_depth"
+OpName %69 "local_id"
+OpName %72 "main"
+OpName %115 "local_id"
+OpName %117 "depth_load"
+OpName %138 "queries"
+OpName %188 "levels_queries"
+OpName %217 "sample"
+OpName %244 "sample_comparison"
+OpName %258 "gather"
+OpName %280 "depth_no_comparison"
+OpDecorate %32 DescriptorSet 0
+OpDecorate %32 Binding 0
+OpDecorate %34 DescriptorSet 0
+OpDecorate %34 Binding 3
+OpDecorate %36 DescriptorSet 0
+OpDecorate %36 Binding 4
+OpDecorate %38 NonWritable
+OpDecorate %38 DescriptorSet 0
+OpDecorate %38 Binding 1
+OpDecorate %40 DescriptorSet 0
+OpDecorate %40 Binding 5
+OpDecorate %42 NonWritable
+OpDecorate %42 DescriptorSet 0
+OpDecorate %42 Binding 6
+OpDecorate %44 DescriptorSet 0
+OpDecorate %44 Binding 7
+OpDecorate %46 NonReadable
+OpDecorate %46 DescriptorSet 0
+OpDecorate %46 Binding 2
+OpDecorate %48 DescriptorSet 0
+OpDecorate %48 Binding 0
+OpDecorate %50 DescriptorSet 0
+OpDecorate %50 Binding 1
+OpDecorate %52 DescriptorSet 0
+OpDecorate %52 Binding 2
+OpDecorate %54 DescriptorSet 0
+OpDecorate %54 Binding 3
+OpDecorate %56 DescriptorSet 0
+OpDecorate %56 Binding 4
+OpDecorate %58 DescriptorSet 0
+OpDecorate %58 Binding 5
+OpDecorate %60 DescriptorSet 0
+OpDecorate %60 Binding 6
+OpDecorate %62 DescriptorSet 1
+OpDecorate %62 Binding 0
+OpDecorate %64 DescriptorSet 1
+OpDecorate %64 Binding 1
+OpDecorate %66 DescriptorSet 1
+OpDecorate %66 Binding 2
+OpDecorate %69 BuiltIn LocalInvocationId
+OpDecorate %115 BuiltIn LocalInvocationId
+OpDecorate %136 BuiltIn Position
+OpDecorate %187 BuiltIn Position
+OpDecorate %216 Location 0
+OpDecorate %242 Location 0
+OpDecorate %257 Location 0
+OpDecorate %279 Location 0
%2 = OpTypeVoid
%4 = OpTypeInt 32 1
%3 = OpConstant %4 10
diff --git a/tests/out/spv/image.spvasm b/tests/out/spv/image.spvasm
--- a/tests/out/spv/image.spvasm
+++ b/tests/out/spv/image.spvasm
@@ -112,297 +115,309 @@ OpDecorate %267 Location 0
%15 = OpTypeImage %12 2D 0 0 0 2 Rgba8ui
%16 = OpTypeImage %12 2D 0 1 0 1 Unknown
%17 = OpTypeImage %12 1D 0 0 0 2 R32ui
-%18 = OpTypeVector %12 3
-%19 = OpTypeVector %4 2
-%20 = OpTypeImage %8 1D 0 0 0 1 Unknown
-%21 = OpTypeImage %8 2D 0 0 0 1 Unknown
-%22 = OpTypeImage %8 2D 0 1 0 1 Unknown
-%23 = OpTypeImage %8 Cube 0 0 0 1 Unknown
-%24 = OpTypeImage %8 Cube 0 1 0 1 Unknown
-%25 = OpTypeImage %8 3D 0 0 0 1 Unknown
-%26 = OpTypeImage %8 2D 0 0 1 1 Unknown
-%27 = OpTypeVector %8 4
-%28 = OpTypeSampler
-%29 = OpTypeImage %8 2D 1 0 0 1 Unknown
-%30 = OpConstantComposite %19 %10 %6
-%32 = OpTypePointer UniformConstant %11
-%31 = OpVariable %32 UniformConstant
-%34 = OpTypePointer UniformConstant %13
-%33 = OpVariable %34 UniformConstant
-%36 = OpTypePointer UniformConstant %14
-%35 = OpVariable %36 UniformConstant
-%38 = OpTypePointer UniformConstant %15
-%37 = OpVariable %38 UniformConstant
-%40 = OpTypePointer UniformConstant %16
-%39 = OpVariable %40 UniformConstant
-%42 = OpTypePointer UniformConstant %17
-%41 = OpVariable %42 UniformConstant
-%44 = OpTypePointer UniformConstant %17
-%43 = OpVariable %44 UniformConstant
-%46 = OpTypePointer UniformConstant %20
-%45 = OpVariable %46 UniformConstant
-%48 = OpTypePointer UniformConstant %21
-%47 = OpVariable %48 UniformConstant
-%50 = OpTypePointer UniformConstant %22
-%49 = OpVariable %50 UniformConstant
-%52 = OpTypePointer UniformConstant %23
-%51 = OpVariable %52 UniformConstant
-%54 = OpTypePointer UniformConstant %24
-%53 = OpVariable %54 UniformConstant
-%56 = OpTypePointer UniformConstant %25
-%55 = OpVariable %56 UniformConstant
-%58 = OpTypePointer UniformConstant %26
-%57 = OpVariable %58 UniformConstant
-%60 = OpTypePointer UniformConstant %28
-%59 = OpVariable %60 UniformConstant
-%62 = OpTypePointer UniformConstant %28
-%61 = OpVariable %62 UniformConstant
-%64 = OpTypePointer UniformConstant %29
-%63 = OpVariable %64 UniformConstant
-%67 = OpTypePointer Input %18
-%66 = OpVariable %67 Input
-%70 = OpTypeFunction %2
-%78 = OpTypeVector %12 2
-%86 = OpTypeVector %12 4
-%97 = OpTypeVector %4 3
-%105 = OpVariable %67 Input
-%127 = OpTypePointer Output %27
-%126 = OpVariable %127 Output
-%136 = OpConstant %12 0
-%175 = OpVariable %127 Output
-%204 = OpVariable %127 Output
-%210 = OpTypeVector %8 2
-%213 = OpTypeSampledImage %20
-%216 = OpTypeSampledImage %21
-%231 = OpTypePointer Output %8
-%230 = OpVariable %231 Output
-%237 = OpTypeSampledImage %29
-%242 = OpConstant %8 0.0
-%245 = OpVariable %127 Output
-%255 = OpConstant %12 1
-%258 = OpConstant %12 3
-%267 = OpVariable %127 Output
-%69 = OpFunction %2 None %70
-%65 = OpLabel
-%68 = OpLoad %18 %66
-%71 = OpLoad %11 %31
-%72 = OpLoad %13 %33
-%73 = OpLoad %15 %37
-%74 = OpLoad %16 %39
-%75 = OpLoad %17 %43
-OpBranch %76
-%76 = OpLabel
-%77 = OpImageQuerySize %19 %73
-%79 = OpVectorShuffle %78 %68 %68 0 1
-%80 = OpBitcast %19 %79
-%81 = OpIMul %19 %77 %80
-%82 = OpCompositeConstruct %19 %3 %5
-%83 = OpSMod %19 %81 %82
-%84 = OpCompositeExtract %12 %68 2
-%85 = OpBitcast %4 %84
-%87 = OpImageFetch %86 %71 %83 Lod %85
-%88 = OpCompositeExtract %12 %68 2
+%18 = OpTypeImage %12 1D 0 0 0 1 Unknown
+%19 = OpTypeVector %12 3
+%20 = OpTypeVector %4 2
+%21 = OpTypeImage %8 1D 0 0 0 1 Unknown
+%22 = OpTypeImage %8 2D 0 0 0 1 Unknown
+%23 = OpTypeImage %8 2D 0 1 0 1 Unknown
+%24 = OpTypeImage %8 Cube 0 0 0 1 Unknown
+%25 = OpTypeImage %8 Cube 0 1 0 1 Unknown
+%26 = OpTypeImage %8 3D 0 0 0 1 Unknown
+%27 = OpTypeImage %8 2D 0 0 1 1 Unknown
+%28 = OpTypeVector %8 4
+%29 = OpTypeSampler
+%30 = OpTypeImage %8 2D 1 0 0 1 Unknown
+%31 = OpConstantComposite %20 %10 %6
+%33 = OpTypePointer UniformConstant %11
+%32 = OpVariable %33 UniformConstant
+%35 = OpTypePointer UniformConstant %13
+%34 = OpVariable %35 UniformConstant
+%37 = OpTypePointer UniformConstant %14
+%36 = OpVariable %37 UniformConstant
+%39 = OpTypePointer UniformConstant %15
+%38 = OpVariable %39 UniformConstant
+%41 = OpTypePointer UniformConstant %16
+%40 = OpVariable %41 UniformConstant
+%43 = OpTypePointer UniformConstant %17
+%42 = OpVariable %43 UniformConstant
+%45 = OpTypePointer UniformConstant %18
+%44 = OpVariable %45 UniformConstant
+%47 = OpTypePointer UniformConstant %17
+%46 = OpVariable %47 UniformConstant
+%49 = OpTypePointer UniformConstant %21
+%48 = OpVariable %49 UniformConstant
+%51 = OpTypePointer UniformConstant %22
+%50 = OpVariable %51 UniformConstant
+%53 = OpTypePointer UniformConstant %23
+%52 = OpVariable %53 UniformConstant
+%55 = OpTypePointer UniformConstant %24
+%54 = OpVariable %55 UniformConstant
+%57 = OpTypePointer UniformConstant %25
+%56 = OpVariable %57 UniformConstant
+%59 = OpTypePointer UniformConstant %26
+%58 = OpVariable %59 UniformConstant
+%61 = OpTypePointer UniformConstant %27
+%60 = OpVariable %61 UniformConstant
+%63 = OpTypePointer UniformConstant %29
+%62 = OpVariable %63 UniformConstant
+%65 = OpTypePointer UniformConstant %29
+%64 = OpVariable %65 UniformConstant
+%67 = OpTypePointer UniformConstant %30
+%66 = OpVariable %67 UniformConstant
+%70 = OpTypePointer Input %19
+%69 = OpVariable %70 Input
+%73 = OpTypeFunction %2
+%82 = OpTypeVector %12 2
+%90 = OpTypeVector %12 4
+%101 = OpTypeVector %4 3
+%115 = OpVariable %70 Input
+%137 = OpTypePointer Output %28
+%136 = OpVariable %137 Output
+%146 = OpConstant %12 0
+%187 = OpVariable %137 Output
+%216 = OpVariable %137 Output
+%222 = OpTypeVector %8 2
+%225 = OpTypeSampledImage %21
+%228 = OpTypeSampledImage %22
+%243 = OpTypePointer Output %8
+%242 = OpVariable %243 Output
+%249 = OpTypeSampledImage %30
+%254 = OpConstant %8 0.0
+%257 = OpVariable %137 Output
+%267 = OpConstant %12 1
+%270 = OpConstant %12 3
+%279 = OpVariable %137 Output
+%72 = OpFunction %2 None %73
+%68 = OpLabel
+%71 = OpLoad %19 %69
+%74 = OpLoad %11 %32
+%75 = OpLoad %13 %34
+%76 = OpLoad %15 %38
+%77 = OpLoad %16 %40
+%78 = OpLoad %18 %44
+%79 = OpLoad %17 %46
+OpBranch %80
+%80 = OpLabel
+%81 = OpImageQuerySize %20 %76
+%83 = OpVectorShuffle %82 %71 %71 0 1
+%84 = OpBitcast %20 %83
+%85 = OpIMul %20 %81 %84
+%86 = OpCompositeConstruct %20 %3 %5
+%87 = OpSMod %20 %85 %86
+%88 = OpCompositeExtract %12 %71 2
%89 = OpBitcast %4 %88
-%90 = OpImageFetch %86 %72 %83 Sample %89
-%91 = OpImageRead %86 %73 %83
-%92 = OpCompositeExtract %12 %68 2
+%91 = OpImageFetch %90 %74 %87 Lod %89
+%92 = OpCompositeExtract %12 %71 2
%93 = OpBitcast %4 %92
-%94 = OpCompositeExtract %12 %68 2
-%95 = OpBitcast %4 %94
-%96 = OpIAdd %4 %95 %6
-%98 = OpCompositeConstruct %97 %83 %93
-%99 = OpImageFetch %86 %74 %98 Lod %96
-%100 = OpCompositeExtract %4 %83 0
-%101 = OpIAdd %86 %87 %90
-%102 = OpIAdd %86 %101 %91
-%103 = OpIAdd %86 %102 %99
-OpImageWrite %75 %100 %103
+%94 = OpImageFetch %90 %75 %87 Sample %93
+%95 = OpImageRead %90 %76 %87
+%96 = OpCompositeExtract %12 %71 2
+%97 = OpBitcast %4 %96
+%98 = OpCompositeExtract %12 %71 2
+%99 = OpBitcast %4 %98
+%100 = OpIAdd %4 %99 %6
+%102 = OpCompositeConstruct %101 %87 %97
+%103 = OpImageFetch %90 %77 %102 Lod %100
+%104 = OpCompositeExtract %12 %71 0
+%105 = OpBitcast %4 %104
+%106 = OpCompositeExtract %12 %71 2
+%107 = OpBitcast %4 %106
+%108 = OpImageFetch %90 %78 %105 Lod %107
+%109 = OpCompositeExtract %4 %87 0
+%110 = OpIAdd %90 %91 %94
+%111 = OpIAdd %90 %110 %95
+%112 = OpIAdd %90 %111 %103
+%113 = OpIAdd %90 %112 %108
+OpImageWrite %79 %109 %113
OpReturn
OpFunctionEnd
-%107 = OpFunction %2 None %70
-%104 = OpLabel
-%106 = OpLoad %18 %105
-%108 = OpLoad %14 %35
-%109 = OpLoad %15 %37
-%110 = OpLoad %17 %43
-OpBranch %111
-%111 = OpLabel
-%112 = OpImageQuerySize %19 %109
-%113 = OpVectorShuffle %78 %106 %106 0 1
-%114 = OpBitcast %19 %113
-%115 = OpIMul %19 %112 %114
-%116 = OpCompositeConstruct %19 %3 %5
-%117 = OpSMod %19 %115 %116
-%118 = OpCompositeExtract %12 %106 2
-%119 = OpBitcast %4 %118
-%120 = OpImageFetch %27 %108 %117 Sample %119
-%121 = OpCompositeExtract %8 %120 0
-%122 = OpCompositeExtract %4 %117 0
-%123 = OpConvertFToU %12 %121
-%124 = OpCompositeConstruct %86 %123 %123 %123 %123
-OpImageWrite %110 %122 %124
+%117 = OpFunction %2 None %73
+%114 = OpLabel
+%116 = OpLoad %19 %115
+%118 = OpLoad %14 %36
+%119 = OpLoad %15 %38
+%120 = OpLoad %17 %46
+OpBranch %121
+%121 = OpLabel
+%122 = OpImageQuerySize %20 %119
+%123 = OpVectorShuffle %82 %116 %116 0 1
+%124 = OpBitcast %20 %123
+%125 = OpIMul %20 %122 %124
+%126 = OpCompositeConstruct %20 %3 %5
+%127 = OpSMod %20 %125 %126
+%128 = OpCompositeExtract %12 %116 2
+%129 = OpBitcast %4 %128
+%130 = OpImageFetch %28 %118 %127 Sample %129
+%131 = OpCompositeExtract %8 %130 0
+%132 = OpCompositeExtract %4 %127 0
+%133 = OpConvertFToU %12 %131
+%134 = OpCompositeConstruct %90 %133 %133 %133 %133
+OpImageWrite %120 %132 %134
OpReturn
OpFunctionEnd
-%128 = OpFunction %2 None %70
-%125 = OpLabel
-%129 = OpLoad %20 %45
-%130 = OpLoad %21 %47
-%131 = OpLoad %22 %49
-%132 = OpLoad %23 %51
-%133 = OpLoad %24 %53
-%134 = OpLoad %25 %55
-OpBranch %135
+%138 = OpFunction %2 None %73
%135 = OpLabel
-%137 = OpImageQuerySizeLod %4 %129 %136
-%138 = OpImageQuerySizeLod %19 %130 %136
-%139 = OpImageQuerySizeLod %19 %130 %6
-%140 = OpImageQuerySizeLod %97 %131 %136
-%141 = OpVectorShuffle %19 %140 %140 0 1
-%142 = OpImageQuerySizeLod %97 %131 %6
-%143 = OpVectorShuffle %19 %142 %142 0 1
-%144 = OpImageQuerySizeLod %19 %132 %136
-%145 = OpImageQuerySizeLod %19 %132 %6
-%146 = OpImageQuerySizeLod %97 %133 %136
-%147 = OpVectorShuffle %19 %146 %146 0 0
-%148 = OpImageQuerySizeLod %97 %133 %6
-%149 = OpVectorShuffle %19 %148 %148 0 0
-%150 = OpImageQuerySizeLod %97 %134 %136
-%151 = OpImageQuerySizeLod %97 %134 %6
-%152 = OpCompositeExtract %4 %138 1
-%153 = OpIAdd %4 %137 %152
-%154 = OpCompositeExtract %4 %139 1
-%155 = OpIAdd %4 %153 %154
-%156 = OpCompositeExtract %4 %141 1
-%157 = OpIAdd %4 %155 %156
-%158 = OpCompositeExtract %4 %143 1
-%159 = OpIAdd %4 %157 %158
-%160 = OpCompositeExtract %4 %144 1
-%161 = OpIAdd %4 %159 %160
-%162 = OpCompositeExtract %4 %145 1
-%163 = OpIAdd %4 %161 %162
-%164 = OpCompositeExtract %4 %147 1
-%165 = OpIAdd %4 %163 %164
-%166 = OpCompositeExtract %4 %149 1
+%139 = OpLoad %21 %48
+%140 = OpLoad %22 %50
+%141 = OpLoad %23 %52
+%142 = OpLoad %24 %54
+%143 = OpLoad %25 %56
+%144 = OpLoad %26 %58
+OpBranch %145
+%145 = OpLabel
+%147 = OpImageQuerySizeLod %4 %139 %146
+%148 = OpBitcast %4 %147
+%149 = OpImageQuerySizeLod %4 %139 %148
+%150 = OpImageQuerySizeLod %20 %140 %146
+%151 = OpImageQuerySizeLod %20 %140 %6
+%152 = OpImageQuerySizeLod %101 %141 %146
+%153 = OpVectorShuffle %20 %152 %152 0 1
+%154 = OpImageQuerySizeLod %101 %141 %6
+%155 = OpVectorShuffle %20 %154 %154 0 1
+%156 = OpImageQuerySizeLod %20 %142 %146
+%157 = OpImageQuerySizeLod %20 %142 %6
+%158 = OpImageQuerySizeLod %101 %143 %146
+%159 = OpVectorShuffle %20 %158 %158 0 0
+%160 = OpImageQuerySizeLod %101 %143 %6
+%161 = OpVectorShuffle %20 %160 %160 0 0
+%162 = OpImageQuerySizeLod %101 %144 %146
+%163 = OpImageQuerySizeLod %101 %144 %6
+%164 = OpCompositeExtract %4 %150 1
+%165 = OpIAdd %4 %147 %164
+%166 = OpCompositeExtract %4 %151 1
%167 = OpIAdd %4 %165 %166
-%168 = OpCompositeExtract %4 %150 2
+%168 = OpCompositeExtract %4 %153 1
%169 = OpIAdd %4 %167 %168
-%170 = OpCompositeExtract %4 %151 2
+%170 = OpCompositeExtract %4 %155 1
%171 = OpIAdd %4 %169 %170
-%172 = OpConvertSToF %8 %171
-%173 = OpCompositeConstruct %27 %172 %172 %172 %172
-OpStore %126 %173
+%172 = OpCompositeExtract %4 %156 1
+%173 = OpIAdd %4 %171 %172
+%174 = OpCompositeExtract %4 %157 1
+%175 = OpIAdd %4 %173 %174
+%176 = OpCompositeExtract %4 %159 1
+%177 = OpIAdd %4 %175 %176
+%178 = OpCompositeExtract %4 %161 1
+%179 = OpIAdd %4 %177 %178
+%180 = OpCompositeExtract %4 %162 2
+%181 = OpIAdd %4 %179 %180
+%182 = OpCompositeExtract %4 %163 2
+%183 = OpIAdd %4 %181 %182
+%184 = OpConvertSToF %8 %183
+%185 = OpCompositeConstruct %28 %184 %184 %184 %184
+OpStore %136 %185
OpReturn
OpFunctionEnd
-%176 = OpFunction %2 None %70
-%174 = OpLabel
-%177 = OpLoad %21 %47
-%178 = OpLoad %22 %49
-%179 = OpLoad %23 %51
-%180 = OpLoad %24 %53
-%181 = OpLoad %25 %55
-%182 = OpLoad %26 %57
-OpBranch %183
-%183 = OpLabel
-%184 = OpImageQueryLevels %4 %177
-%185 = OpImageQueryLevels %4 %178
-%186 = OpImageQuerySizeLod %97 %178 %136
-%187 = OpCompositeExtract %4 %186 2
-%188 = OpImageQueryLevels %4 %179
-%189 = OpImageQueryLevels %4 %180
-%190 = OpImageQuerySizeLod %97 %180 %136
-%191 = OpCompositeExtract %4 %190 2
-%192 = OpImageQueryLevels %4 %181
-%193 = OpImageQuerySamples %4 %182
-%194 = OpIAdd %4 %187 %191
-%195 = OpIAdd %4 %194 %193
-%196 = OpIAdd %4 %195 %184
-%197 = OpIAdd %4 %196 %185
-%198 = OpIAdd %4 %197 %192
-%199 = OpIAdd %4 %198 %188
-%200 = OpIAdd %4 %199 %189
-%201 = OpConvertSToF %8 %200
-%202 = OpCompositeConstruct %27 %201 %201 %201 %201
-OpStore %175 %202
+%188 = OpFunction %2 None %73
+%186 = OpLabel
+%189 = OpLoad %22 %50
+%190 = OpLoad %23 %52
+%191 = OpLoad %24 %54
+%192 = OpLoad %25 %56
+%193 = OpLoad %26 %58
+%194 = OpLoad %27 %60
+OpBranch %195
+%195 = OpLabel
+%196 = OpImageQueryLevels %4 %189
+%197 = OpImageQueryLevels %4 %190
+%198 = OpImageQuerySizeLod %101 %190 %146
+%199 = OpCompositeExtract %4 %198 2
+%200 = OpImageQueryLevels %4 %191
+%201 = OpImageQueryLevels %4 %192
+%202 = OpImageQuerySizeLod %101 %192 %146
+%203 = OpCompositeExtract %4 %202 2
+%204 = OpImageQueryLevels %4 %193
+%205 = OpImageQuerySamples %4 %194
+%206 = OpIAdd %4 %199 %203
+%207 = OpIAdd %4 %206 %205
+%208 = OpIAdd %4 %207 %196
+%209 = OpIAdd %4 %208 %197
+%210 = OpIAdd %4 %209 %204
+%211 = OpIAdd %4 %210 %200
+%212 = OpIAdd %4 %211 %201
+%213 = OpConvertSToF %8 %212
+%214 = OpCompositeConstruct %28 %213 %213 %213 %213
+OpStore %187 %214
OpReturn
OpFunctionEnd
-%205 = OpFunction %2 None %70
-%203 = OpLabel
-%206 = OpLoad %20 %45
-%207 = OpLoad %21 %47
-%208 = OpLoad %28 %59
-OpBranch %209
-%209 = OpLabel
-%211 = OpCompositeConstruct %210 %7 %7
-%212 = OpCompositeExtract %8 %211 0
-%214 = OpSampledImage %213 %206 %208
-%215 = OpImageSampleImplicitLod %27 %214 %212
-%217 = OpSampledImage %216 %207 %208
-%218 = OpImageSampleImplicitLod %27 %217 %211
-%219 = OpSampledImage %216 %207 %208
-%220 = OpImageSampleImplicitLod %27 %219 %211 ConstOffset %30
-%221 = OpSampledImage %216 %207 %208
-%222 = OpImageSampleExplicitLod %27 %221 %211 Lod %9
-%223 = OpSampledImage %216 %207 %208
-%224 = OpImageSampleExplicitLod %27 %223 %211 Lod|ConstOffset %9 %30
-%225 = OpFAdd %27 %215 %218
-%226 = OpFAdd %27 %225 %220
-%227 = OpFAdd %27 %226 %222
-%228 = OpFAdd %27 %227 %224
-OpStore %204 %228
+%217 = OpFunction %2 None %73
+%215 = OpLabel
+%218 = OpLoad %21 %48
+%219 = OpLoad %22 %50
+%220 = OpLoad %29 %62
+OpBranch %221
+%221 = OpLabel
+%223 = OpCompositeConstruct %222 %7 %7
+%224 = OpCompositeExtract %8 %223 0
+%226 = OpSampledImage %225 %218 %220
+%227 = OpImageSampleImplicitLod %28 %226 %224
+%229 = OpSampledImage %228 %219 %220
+%230 = OpImageSampleImplicitLod %28 %229 %223
+%231 = OpSampledImage %228 %219 %220
+%232 = OpImageSampleImplicitLod %28 %231 %223 ConstOffset %31
+%233 = OpSampledImage %228 %219 %220
+%234 = OpImageSampleExplicitLod %28 %233 %223 Lod %9
+%235 = OpSampledImage %228 %219 %220
+%236 = OpImageSampleExplicitLod %28 %235 %223 Lod|ConstOffset %9 %31
+%237 = OpFAdd %28 %227 %230
+%238 = OpFAdd %28 %237 %232
+%239 = OpFAdd %28 %238 %234
+%240 = OpFAdd %28 %239 %236
+OpStore %216 %240
OpReturn
OpFunctionEnd
-%232 = OpFunction %2 None %70
-%229 = OpLabel
-%233 = OpLoad %28 %61
-%234 = OpLoad %29 %63
-OpBranch %235
-%235 = OpLabel
-%236 = OpCompositeConstruct %210 %7 %7
-%238 = OpSampledImage %237 %234 %233
-%239 = OpImageSampleDrefImplicitLod %8 %238 %236 %7
-%240 = OpSampledImage %237 %234 %233
-%241 = OpImageSampleDrefExplicitLod %8 %240 %236 %7 Lod %242
-%243 = OpFAdd %8 %239 %241
-OpStore %230 %243
+%244 = OpFunction %2 None %73
+%241 = OpLabel
+%245 = OpLoad %29 %64
+%246 = OpLoad %30 %66
+OpBranch %247
+%247 = OpLabel
+%248 = OpCompositeConstruct %222 %7 %7
+%250 = OpSampledImage %249 %246 %245
+%251 = OpImageSampleDrefImplicitLod %8 %250 %248 %7
+%252 = OpSampledImage %249 %246 %245
+%253 = OpImageSampleDrefExplicitLod %8 %252 %248 %7 Lod %254
+%255 = OpFAdd %8 %251 %253
+OpStore %242 %255
OpReturn
OpFunctionEnd
-%246 = OpFunction %2 None %70
-%244 = OpLabel
-%247 = OpLoad %21 %47
-%248 = OpLoad %28 %59
-%249 = OpLoad %28 %61
-%250 = OpLoad %29 %63
-OpBranch %251
-%251 = OpLabel
-%252 = OpCompositeConstruct %210 %7 %7
-%253 = OpSampledImage %216 %247 %248
-%254 = OpImageGather %27 %253 %252 %255
-%256 = OpSampledImage %216 %247 %248
-%257 = OpImageGather %27 %256 %252 %258 ConstOffset %30
-%259 = OpSampledImage %237 %250 %249
-%260 = OpImageDrefGather %27 %259 %252 %7
-%261 = OpSampledImage %237 %250 %249
-%262 = OpImageDrefGather %27 %261 %252 %7 ConstOffset %30
-%263 = OpFAdd %27 %254 %257
-%264 = OpFAdd %27 %263 %260
-%265 = OpFAdd %27 %264 %262
-OpStore %245 %265
+%258 = OpFunction %2 None %73
+%256 = OpLabel
+%259 = OpLoad %22 %50
+%260 = OpLoad %29 %62
+%261 = OpLoad %29 %64
+%262 = OpLoad %30 %66
+OpBranch %263
+%263 = OpLabel
+%264 = OpCompositeConstruct %222 %7 %7
+%265 = OpSampledImage %228 %259 %260
+%266 = OpImageGather %28 %265 %264 %267
+%268 = OpSampledImage %228 %259 %260
+%269 = OpImageGather %28 %268 %264 %270 ConstOffset %31
+%271 = OpSampledImage %249 %262 %261
+%272 = OpImageDrefGather %28 %271 %264 %7
+%273 = OpSampledImage %249 %262 %261
+%274 = OpImageDrefGather %28 %273 %264 %7 ConstOffset %31
+%275 = OpFAdd %28 %266 %269
+%276 = OpFAdd %28 %275 %272
+%277 = OpFAdd %28 %276 %274
+OpStore %257 %277
OpReturn
OpFunctionEnd
-%268 = OpFunction %2 None %70
-%266 = OpLabel
-%269 = OpLoad %28 %59
-%270 = OpLoad %29 %63
-OpBranch %271
-%271 = OpLabel
-%272 = OpCompositeConstruct %210 %7 %7
-%273 = OpSampledImage %237 %270 %269
-%274 = OpImageSampleImplicitLod %27 %273 %272
-%275 = OpCompositeExtract %8 %274 0
-%276 = OpSampledImage %237 %270 %269
-%277 = OpImageGather %27 %276 %272 %136
-%278 = OpCompositeConstruct %27 %275 %275 %275 %275
-%279 = OpFAdd %27 %278 %277
-OpStore %267 %279
+%280 = OpFunction %2 None %73
+%278 = OpLabel
+%281 = OpLoad %29 %62
+%282 = OpLoad %30 %66
+OpBranch %283
+%283 = OpLabel
+%284 = OpCompositeConstruct %222 %7 %7
+%285 = OpSampledImage %249 %282 %281
+%286 = OpImageSampleImplicitLod %28 %285 %284
+%287 = OpCompositeExtract %8 %286 0
+%288 = OpSampledImage %249 %282 %281
+%289 = OpImageGather %28 %288 %284 %146
+%290 = OpCompositeConstruct %28 %287 %287 %287 %287
+%291 = OpFAdd %28 %290 %289
+OpStore %279 %291
OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/spv/operators.spvasm b/tests/out/spv/operators.spvasm
--- a/tests/out/spv/operators.spvasm
+++ b/tests/out/spv/operators.spvasm
@@ -149,13 +149,13 @@ OpFunctionEnd
OpBranch %118
%118 = OpLabel
%119 = OpSMod %8 %7 %7
-%120 = OpFMod %4 %3 %3
+%120 = OpFRem %4 %3 %3
%122 = OpCompositeConstruct %121 %7 %7 %7
%123 = OpCompositeConstruct %121 %7 %7 %7
%124 = OpSMod %121 %122 %123
%125 = OpCompositeConstruct %22 %3 %3 %3
%126 = OpCompositeConstruct %22 %3 %3 %3
-%127 = OpFMod %22 %125 %126
+%127 = OpFRem %22 %125 %126
OpReturn
OpFunctionEnd
%129 = OpFunction %2 None %117
diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl
--- a/tests/out/wgsl/image.wgsl
+++ b/tests/out/wgsl/image.wgsl
@@ -10,6 +10,8 @@ var image_storage_src: texture_storage_2d<rgba8uint,read>;
var image_array_src: texture_2d_array<u32>;
[[group(0), binding(6)]]
var image_dup_src: texture_storage_1d<r32uint,read>;
+[[group(0), binding(7)]]
+var image_1d_src: texture_1d<u32>;
[[group(0), binding(2)]]
var image_dst: texture_storage_1d<r32uint,write>;
[[group(0), binding(0)]]
diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl
--- a/tests/out/wgsl/image.wgsl
+++ b/tests/out/wgsl/image.wgsl
@@ -41,7 +43,8 @@ fn main([[builtin(local_invocation_id)]] local_id: vec3<u32>) {
let value2_ = textureLoad(image_multisampled_src, itc, i32(local_id.z));
let value4_ = textureLoad(image_storage_src, itc);
let value5_ = textureLoad(image_array_src, itc, i32(local_id.z), (i32(local_id.z) + 1));
- textureStore(image_dst, itc.x, (((value1_ + value2_) + value4_) + value5_));
+ let value6_ = textureLoad(image_1d_src, i32(local_id.x), i32(local_id.z));
+ textureStore(image_dst, itc.x, ((((value1_ + value2_) + value4_) + value5_) + value6_));
return;
}
diff --git a/tests/out/wgsl/image.wgsl b/tests/out/wgsl/image.wgsl
--- a/tests/out/wgsl/image.wgsl
+++ b/tests/out/wgsl/image.wgsl
@@ -57,6 +60,7 @@ fn depth_load([[builtin(local_invocation_id)]] local_id_1: vec3<u32>) {
[[stage(vertex)]]
fn queries() -> [[builtin(position)]] vec4<f32> {
let dim_1d = textureDimensions(image_1d);
+ let dim_1d_lod = textureDimensions(image_1d, i32(dim_1d));
let dim_2d = textureDimensions(image_2d);
let dim_2d_lod = textureDimensions(image_2d, 1);
let dim_2d_array = textureDimensions(image_2d_array);
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -461,28 +461,56 @@ fn let_type_mismatch() {
r#"
let x: i32 = 1.0;
"#,
- r#"error: the type of `x` is expected to be [1]
+ r#"error: the type of `x` is expected to be `f32`
┌─ wgsl:2:17
│
2 │ let x: i32 = 1.0;
│ ^ definition of `x`
+"#,
+ );
+
+ check(
+ r#"
+ fn foo() {
+ let x: f32 = true;
+ }
+ "#,
+ r#"error: the type of `x` is expected to be `bool`
+ ┌─ wgsl:3:21
+ │
+3 │ let x: f32 = true;
+ │ ^ definition of `x`
+
"#,
);
}
#[test]
-fn local_var_type_mismatch() {
+fn var_type_mismatch() {
+ check(
+ r#"
+ let x: f32 = 1;
+ "#,
+ r#"error: the type of `x` is expected to be `i32`
+ ┌─ wgsl:2:17
+ │
+2 │ let x: f32 = 1;
+ │ ^ definition of `x`
+
+"#,
+ );
+
check(
r#"
fn foo() {
- var x: f32 = 1;
+ var x: f32 = 1u32;
}
"#,
- r#"error: the type of `x` is expected to be [1]
+ r#"error: the type of `x` is expected to be `u32`
┌─ wgsl:3:21
│
-3 │ var x: f32 = 1;
+3 │ var x: f32 = 1u32;
│ ^ definition of `x`
"#,
|
Naga generates bad MSL for `textureLoad` access on 1d textures
Naga compiles the following WGSL input to Metal Shading Language that does not validate:
```
// Load a texel from a 1d texture.
[[group(0), binding(0)]]
var tex: texture_1d<u32>;
[[stage(compute), workgroup_size(16)]]
fn main(
[[builtin(local_invocation_id)]] local_id: vec3<u32>,
) {
var x = textureLoad(tex, i32(local_id.x), i32(local_id.y));
}
```
The generated MSL is:
```
// language: metal1.1
#include <metal_stdlib>
#include <simd/simd.h>
struct main_Input {
};
kernel void main_(
metal::uint3 local_id [[thread_position_in_threadgroup]]
, metal::texture1d<uint, metal::access::sample> tex [[user(fake0)]]
) {
metal::uint4 x;
metal::uint4 _e6 = tex.read(metal::uint(static_cast<int>(local_id.x)), static_cast<int>(local_id.y));
x = _e6;
return;
}
```
The error messages are a bunch of complaints explaining why each overload of `read` doesn't apply, but the gist of it is, we would like this overload:
```
METAL_FUNC vec<T, 4> read(uint coord, uint lod = 0) const thread METAL_CONST_ARG(lod) METAL_ZERO_ARG(lod)
```
but we don't get it because the level-of-detail argument is not a compile-time constant.
1D textures can't have mipmaps. At the WGSL level, this means that `textureNumLevels` always returns `1` on 1D textures, and any value of the `textureLoad`'s `level` argument other than zero is out of bounds. But at the MSL level, the `level` argument to `texture1d::read` must be a constexpr equal to zero. So when Naga emits the expression `static_cast<int>(local_id.y)` for that argument, Metal validation fails.
|
The same problem arises with WGSL's `textureDimensions`: it accepts a `level` argument, but MSL requires that it be a constexpr equal to zero.
|
2022-01-12T11:46:14Z
|
0.8
|
2022-01-12T03:52:06Z
|
ea832a9eec13560560c017072d4318d5d942e5e5
|
[
"let_type_mismatch",
"var_type_mismatch"
] |
[
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"back::msl::writer::test_stack_size",
"front::wgsl::lexer::test_tokens",
"front::spv::test::parse",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_comment",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::expressions",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_decimal_floats",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_pointers",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_hex_floats",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::namer::test",
"front::wgsl::tests::parse_struct",
"proc::test_matrix_size",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::declarations",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_types",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_spv_all",
"convert_glsl_folder",
"convert_wgsl",
"cube_array",
"sampler1d",
"geometry",
"storage1d",
"sample_rate_shading",
"storage_image_formats",
"image_queries",
"bad_for_initializer",
"function_without_identifier",
"bad_texture_sample_type",
"inconsistent_binding",
"invalid_float",
"invalid_integer",
"bad_type_cast",
"invalid_structs",
"bad_texture",
"dead_code",
"last_case_falltrough",
"invalid_local_vars",
"invalid_runtime_sized_arrays",
"local_var_missing_type",
"invalid_texture_sample_type",
"invalid_arrays",
"missing_default_case",
"invalid_access",
"invalid_functions",
"reserved_identifier_prefix",
"negative_index",
"unknown_attribute",
"unknown_access",
"struct_member_zero_size",
"unknown_built_in",
"struct_member_zero_align",
"unknown_conservative_depth",
"missing_bindings",
"pointer_type_equivalence",
"unknown_scalar_type",
"unknown_ident",
"unknown_storage_class",
"unknown_local_function",
"module_scope_identifier_redefinition",
"postfix_pointers",
"unknown_shader_stage",
"reserved_keyword",
"unknown_type",
"unknown_storage_format",
"unknown_identifier",
"zero_array_stride",
"wrong_access_mode",
"select",
"valid_access",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
gfx-rs/naga
| 1,658
|
gfx-rs__naga-1658
|
[
"1655"
] |
70b5ddaaad46b68ffb4e298b1d10d920544d3ca0
|
diff --git a/.gitignore b/.gitignore
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,5 @@ Cargo.lock
/*.frag
/*.comp
/*.wgsl
+/*.hlsl
+/*.txt
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -164,7 +164,7 @@ pub enum Error<'a> {
ZeroSizeOrAlign(Span),
InconsistentBinding(Span),
UnknownLocalFunction(Span),
- InitializationTypeMismatch(Span, Handle<crate::Type>),
+ InitializationTypeMismatch(Span, String),
MissingType(Span),
InvalidAtomicPointer(Span),
InvalidAtomicOperandType(Span),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -414,7 +414,7 @@ impl<'a> Error<'a> {
notes: vec![],
},
Error::InitializationTypeMismatch(ref name_span, ref expected_ty) => ParseError {
- message: format!("the type of `{}` is expected to be {:?}", &source[name_span.clone()], expected_ty),
+ message: format!("the type of `{}` is expected to be `{}`", &source[name_span.clone()], expected_ty),
labels: vec![(name_span.clone(), format!("definition of `{}`", &source[name_span.clone()]).into())],
notes: vec![],
},
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3453,7 +3453,10 @@ impl Parser {
given_inner,
expr_inner
);
- return Err(Error::InitializationTypeMismatch(name_span, ty));
+ return Err(Error::InitializationTypeMismatch(
+ name_span,
+ expr_inner.to_wgsl(context.types, context.constants),
+ ));
}
}
block.extend(emitter.finish(context.expressions));
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3518,7 +3521,8 @@ impl Parser {
expr_inner
);
return Err(Error::InitializationTypeMismatch(
- name_span, ty,
+ name_span,
+ expr_inner.to_wgsl(context.types, context.constants),
));
}
ty
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -4293,7 +4297,22 @@ impl Parser {
crate::ConstantInner::Composite { ty, components: _ } => ty == explicit_ty,
};
if !type_match {
- return Err(Error::InitializationTypeMismatch(name_span, explicit_ty));
+ let exptected_inner_str = match con.inner {
+ crate::ConstantInner::Scalar { width, value } => {
+ crate::TypeInner::Scalar {
+ kind: value.scalar_kind(),
+ width,
+ }
+ .to_wgsl(&module.types, &module.constants)
+ }
+ crate::ConstantInner::Composite { .. } => module.types[explicit_ty]
+ .inner
+ .to_wgsl(&module.types, &module.constants),
+ };
+ return Err(Error::InitializationTypeMismatch(
+ name_span,
+ exptected_inner_str,
+ ));
}
}
|
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -461,28 +461,56 @@ fn let_type_mismatch() {
r#"
let x: i32 = 1.0;
"#,
- r#"error: the type of `x` is expected to be [1]
+ r#"error: the type of `x` is expected to be `f32`
┌─ wgsl:2:17
│
2 │ let x: i32 = 1.0;
│ ^ definition of `x`
+"#,
+ );
+
+ check(
+ r#"
+ fn foo() {
+ let x: f32 = true;
+ }
+ "#,
+ r#"error: the type of `x` is expected to be `bool`
+ ┌─ wgsl:3:21
+ │
+3 │ let x: f32 = true;
+ │ ^ definition of `x`
+
"#,
);
}
#[test]
-fn local_var_type_mismatch() {
+fn var_type_mismatch() {
+ check(
+ r#"
+ let x: f32 = 1;
+ "#,
+ r#"error: the type of `x` is expected to be `i32`
+ ┌─ wgsl:2:17
+ │
+2 │ let x: f32 = 1;
+ │ ^ definition of `x`
+
+"#,
+ );
+
check(
r#"
fn foo() {
- var x: f32 = 1;
+ var x: f32 = 1u32;
}
"#,
- r#"error: the type of `x` is expected to be [1]
+ r#"error: the type of `x` is expected to be `u32`
┌─ wgsl:3:21
│
-3 │ var x: f32 = 1;
+3 │ var x: f32 = 1u32;
│ ^ definition of `x`
"#,
|
Confusing error messages on type mismatch
Consider the following wgsl code:
```
[[stage(compute), workgroup_size(1)]]
fn main() {
var x: u32 = 0;
}
```
Attempting to evaluate it leads to a naga output of:
```
ERROR naga::front::wgsl] Given type Scalar { kind: Uint, width: 4 } doesn't match expected Scalar { kind: Sint, width: 4 }
error: the type of `x` is expected to be [1]
┌─ wgsl:3:9
│
3 │ var x: u32 = 0;
│ ^ definition of `x`
Could not parse WGSL
```
While the initial error message can clue an experienced user into what the problem is, the rest of the error message is, in my opinion, rather mystifying. What exactly does "[1]" refer to here, and how is it useful to someone reading the error? For this example, it may be worth adding a note explaining to the user that perhaps they may want to declare the right-hand side as unsigned.
|
2022-01-10T21:10:57Z
|
0.8
|
2022-01-12T03:53:58Z
|
ea832a9eec13560560c017072d4318d5d942e5e5
|
[
"let_type_mismatch",
"var_type_mismatch"
] |
[
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::append_non_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::glsl::parser_tests::version",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::textures",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_decimal_floats",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_hex_floats",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_decimal_ints",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_type_inference",
"proc::namer::test",
"proc::typifier::test_error_size",
"front::wgsl::type_inner_tests::to_wgsl",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_struct_instantiation",
"proc::test_matrix_size",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"front::spv::test::parse",
"front::glsl::parser_tests::function_overloading",
"convert_spv_all",
"convert_glsl_folder",
"convert_wgsl",
"cube_array",
"geometry",
"sample_rate_shading",
"storage1d",
"sampler1d",
"storage_image_formats",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"bad_texture_sample_type",
"bad_type_cast",
"inconsistent_binding",
"invalid_arrays",
"invalid_local_vars",
"invalid_float",
"invalid_texture_sample_type",
"invalid_integer",
"invalid_runtime_sized_arrays",
"last_case_falltrough",
"invalid_functions",
"dead_code",
"local_var_missing_type",
"invalid_structs",
"missing_default_case",
"invalid_access",
"negative_index",
"pointer_type_equivalence",
"bad_texture",
"reserved_identifier_prefix",
"unknown_access",
"struct_member_zero_size",
"struct_member_zero_align",
"missing_bindings",
"unknown_local_function",
"module_scope_identifier_redefinition",
"reserved_keyword",
"unknown_identifier",
"unknown_storage_class",
"postfix_pointers",
"unknown_storage_format",
"unknown_shader_stage",
"unknown_scalar_type",
"unknown_type",
"select",
"unknown_built_in",
"unknown_attribute",
"zero_array_stride",
"unknown_conservative_depth",
"unknown_ident",
"valid_access",
"wrong_access_mode",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,402
|
gfx-rs__naga-1402
|
[
"1019"
] |
dc8a41de04068b4766c1e74f9d77f765e815172a
|
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -135,6 +135,11 @@ bitflags::bitflags! {
}
}
+struct BlockInfo {
+ stages: ShaderStages,
+ finished: bool,
+}
+
struct BlockContext<'a> {
abilities: ControlFlowAbility,
info: &'a FunctionInfo,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -326,7 +331,7 @@ impl super::Validator {
&mut self,
statements: &[crate::Statement],
context: &BlockContext,
- ) -> Result<ShaderStages, FunctionError> {
+ ) -> Result<BlockInfo, FunctionError> {
use crate::{Statement as S, TypeInner as Ti};
let mut finished = false;
let mut stages = ShaderStages::all();
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -345,7 +350,9 @@ impl super::Validator {
}
}
S::Block(ref block) => {
- stages &= self.validate_block(block, context)?;
+ let info = self.validate_block(block, context)?;
+ stages &= info.stages;
+ finished = info.finished;
}
S::If {
condition,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -359,8 +366,8 @@ impl super::Validator {
} => {}
_ => return Err(FunctionError::InvalidIfType(condition)),
}
- stages &= self.validate_block(accept, context)?;
- stages &= self.validate_block(reject, context)?;
+ stages &= self.validate_block(accept, context)?.stages;
+ stages &= self.validate_block(reject, context)?.stages;
}
S::Switch {
selector,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -385,9 +392,9 @@ impl super::Validator {
let sub_context =
context.with_abilities(pass_through_abilities | ControlFlowAbility::BREAK);
for case in cases {
- stages &= self.validate_block(&case.body, &sub_context)?;
+ stages &= self.validate_block(&case.body, &sub_context)?.stages;
}
- stages &= self.validate_block(default, &sub_context)?;
+ stages &= self.validate_block(default, &sub_context)?.stages;
}
S::Loop {
ref body,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -397,18 +404,22 @@ impl super::Validator {
// because the continuing{} block inherits the scope
let base_expression_count = self.valid_expression_list.len();
let pass_through_abilities = context.abilities & ControlFlowAbility::RETURN;
- stages &= self.validate_block_impl(
- body,
- &context.with_abilities(
- pass_through_abilities
- | ControlFlowAbility::BREAK
- | ControlFlowAbility::CONTINUE,
- ),
- )?;
- stages &= self.validate_block_impl(
- continuing,
- &context.with_abilities(ControlFlowAbility::empty()),
- )?;
+ stages &= self
+ .validate_block_impl(
+ body,
+ &context.with_abilities(
+ pass_through_abilities
+ | ControlFlowAbility::BREAK
+ | ControlFlowAbility::CONTINUE,
+ ),
+ )?
+ .stages;
+ stages &= self
+ .validate_block_impl(
+ continuing,
+ &context.with_abilities(ControlFlowAbility::empty()),
+ )?
+ .stages;
for handle in self.valid_expression_list.drain(base_expression_count..) {
self.valid_expression_set.remove(handle.index());
}
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -593,20 +604,20 @@ impl super::Validator {
}
}
}
- Ok(stages)
+ Ok(BlockInfo { stages, finished })
}
fn validate_block(
&mut self,
statements: &[crate::Statement],
context: &BlockContext,
- ) -> Result<ShaderStages, FunctionError> {
+ ) -> Result<BlockInfo, FunctionError> {
let base_expression_count = self.valid_expression_list.len();
- let stages = self.validate_block_impl(statements, context)?;
+ let info = self.validate_block_impl(statements, context)?;
for handle in self.valid_expression_list.drain(base_expression_count..) {
self.valid_expression_set.remove(handle.index());
}
- Ok(stages)
+ Ok(info)
}
fn validate_local_var(
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -694,10 +705,12 @@ impl super::Validator {
}
if self.flags.contains(ValidationFlags::BLOCKS) {
- let stages = self.validate_block(
- &fun.body,
- &BlockContext::new(fun, module, &info, &mod_info.functions),
- )?;
+ let stages = self
+ .validate_block(
+ &fun.body,
+ &BlockContext::new(fun, module, &info, &mod_info.functions),
+ )?
+ .stages;
info.available_stages &= stages;
}
Ok(info)
|
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -848,3 +848,34 @@ fn invalid_local_vars() {
if local_var_name == "not_okay"
}
}
+
+#[test]
+fn dead_code() {
+ check_validation_error! {
+ "
+ fn dead_code_after_if(condition: bool) -> i32 {
+ if (condition) {
+ return 1;
+ } else {
+ return 2;
+ }
+ return 3;
+ }
+ ":
+ Ok(_)
+ }
+ check_validation_error! {
+ "
+ fn dead_code_after_block() -> i32 {
+ {
+ return 1;
+ }
+ return 2;
+ }
+ ":
+ Err(naga::valid::ValidationError::Function {
+ error: naga::valid::FunctionError::InstructionsAfterReturn,
+ ..
+ })
+ }
+}
|
Naga doesn't detect unreachable code
The following test, if added to `wgsl-errors.rs`, should fail, but it passes:
```
check_validation_error! {
"
fn dead_code_after_if(condition: bool) -> i32 {
if (condition) {
return 1;
} else {
return 2;
}
return 3;
}
",
"
fn dead_code_after_block() -> i32 {
{
return 1;
}
return 2;
}
":
Ok(_)
}
```
|
2021-09-20T23:46:59Z
|
0.6
|
2021-09-24T14:11:33Z
|
2e7d629aefe6857ade4f96fe2c3dc1a09f0fa4db
|
[
"dead_code"
] |
[
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::spv::test::parse",
"front::glsl::parser_tests::implicit_conversions",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_decimal_floats",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::declarations",
"front::glsl::parser_tests::control_flow",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_hex_floats",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_decimal_ints",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_types",
"proc::test_matrix_size",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"convert_spv_pointer_access",
"convert_spv_inverse_hyperbolic_trig_functions",
"convert_spv_shadow",
"convert_spv_quad_vert",
"convert_glsl_folder",
"convert_wgsl",
"sampler1d",
"cube_array",
"storage1d",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"inconsistent_binding",
"bad_texture_sample_type",
"bad_type_cast",
"invalid_functions",
"invalid_float",
"invalid_texture_sample_type",
"let_type_mismatch",
"local_var_missing_type",
"invalid_access",
"invalid_structs",
"invalid_integer",
"bad_texture",
"local_var_type_mismatch",
"struct_member_zero_align",
"struct_member_zero_size",
"missing_bindings",
"unknown_conservative_depth",
"unknown_access",
"unknown_attribute",
"unknown_built_in",
"invalid_arrays",
"unknown_shader_stage",
"invalid_local_vars",
"unknown_type",
"unknown_storage_class",
"unknown_local_function",
"unknown_storage_format",
"unknown_identifier",
"negative_index",
"unknown_scalar_type",
"unknown_ident",
"zero_array_stride",
"postfix_pointers",
"valid_access",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 17)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 26)",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,390
|
gfx-rs__naga-1390
|
[
"1386"
] |
d7ca7d43b987c17f553db2823d833646ff1d48e0
|
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -336,7 +336,7 @@ fn consume_token(mut input: &str, generic: bool) -> (Token<'_>, &str) {
}
}
'0'..='9' => consume_number(input),
- 'a'..='z' | 'A'..='Z' | '_' => {
+ 'a'..='z' | 'A'..='Z' => {
let (word, rest) = consume_any(input, |c| c.is_ascii_alphanumeric() || c == '_');
(Token::Word(word), rest)
}
|
diff --git a/src/front/wgsl/lexer.rs b/src/front/wgsl/lexer.rs
--- a/src/front/wgsl/lexer.rs
+++ b/src/front/wgsl/lexer.rs
@@ -655,6 +655,7 @@ fn test_tokens() {
);
sub_test("No¾", &[Token::Word("No"), Token::Unknown('¾')]);
sub_test("No好", &[Token::Word("No"), Token::Unknown('好')]);
+ sub_test("_No", &[Token::Unknown('_'), Token::Word("No")]);
sub_test("\"\u{2}ПЀ\u{0}\"", &[Token::String("\u{2}ПЀ\u{0}")]); // https://github.com/gfx-rs/naga/issues/90
}
|
naga should reject identifiers beginning with underscore
This should fail compilation. But Naga allows it.
```
let _123 = 123;
```
|
2021-09-18T04:35:00Z
|
0.6
|
2021-09-24T14:12:35Z
|
2e7d629aefe6857ade4f96fe2c3dc1a09f0fa4db
|
[
"front::wgsl::lexer::test_tokens"
] |
[
"back::msl::test_error_size",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::constants",
"front::glsl::parser_tests::version",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_comment",
"front::spv::test::parse",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_hex_floats",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_decimal_floats",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_pointers",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::test_matrix_size",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_struct_instantiation",
"valid::analyzer::uniform_control_flow",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_store",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_type_cast",
"convert_spv_pointer_access",
"convert_spv_inverse_hyperbolic_trig_functions",
"convert_spv_shadow",
"convert_spv_quad_vert",
"convert_glsl_folder",
"convert_wgsl",
"cube_array",
"sampler1d",
"storage1d",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"inconsistent_binding",
"invalid_float",
"bad_texture_sample_type",
"invalid_texture_sample_type",
"bad_type_cast",
"invalid_functions",
"invalid_arrays",
"invalid_integer",
"let_type_mismatch",
"invalid_structs",
"local_var_missing_type",
"invalid_access",
"bad_texture",
"struct_member_zero_align",
"unknown_access",
"struct_member_zero_size",
"local_var_type_mismatch",
"invalid_local_vars",
"unknown_built_in",
"unknown_attribute",
"unknown_conservative_depth",
"unknown_shader_stage",
"unknown_storage_class",
"negative_index",
"unknown_scalar_type",
"unknown_type",
"unknown_ident",
"postfix_pointers",
"missing_bindings",
"unknown_local_function",
"unknown_storage_format",
"zero_array_stride",
"unknown_identifier",
"valid_access",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 26)",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 17)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,384
|
gfx-rs__naga-1384
|
[
"1382"
] |
73f9d072079246ccf119c4e27de2b624afa6e466
|
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -51,56 +51,6 @@ enum Indirection {
Reference,
}
-/// Return the sort of indirection that `expr`'s plain form evaluates to.
-///
-/// An expression's 'plain form' is the most general rendition of that
-/// expression into WGSL, lacking `&` or `*` operators:
-///
-/// - The plain form of `LocalVariable(x)` is simply `x`, which is a reference
-/// to the local variable's storage.
-///
-/// - The plain form of `GlobalVariable(g)` is simply `g`, which is usually a
-/// reference to the global variable's storage. However, globals in the
-/// `Handle` storage class are immutable, and `GlobalVariable` expressions for
-/// those produce the value directly, not a pointer to it. Such
-/// `GlobalVariable` expressions are `Ordinary`.
-///
-/// - `Access` and `AccessIndex` are `Reference` when their `base` operand is a
-/// pointer. If they are applied directly to a composite value, they are
-/// `Ordinary`.
-///
-/// Note that `FunctionArgument` expressions are never `Reference`, even when
-/// the argument's type is `Pointer`. `FunctionArgument` always evaluates to the
-/// argument's value directly, so any pointer it produces is merely the value
-/// passed by the caller.
-fn plain_form_indirection(
- expr: Handle<crate::Expression>,
- module: &Module,
- func_ctx: &back::FunctionCtx<'_>,
-) -> Indirection {
- use crate::Expression as Ex;
- match func_ctx.expressions[expr] {
- Ex::LocalVariable(_) => Indirection::Reference,
- Ex::GlobalVariable(handle) => {
- let global = &module.global_variables[handle];
- match global.class {
- crate::StorageClass::Handle => Indirection::Ordinary,
- _ => Indirection::Reference,
- }
- }
- Ex::Access { base, .. } | Ex::AccessIndex { base, .. } => {
- let base_ty = func_ctx.info[base].ty.inner_with(&module.types);
- match *base_ty {
- crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => {
- Indirection::Reference
- }
- _ => Indirection::Ordinary,
- }
- }
- _ => Indirection::Ordinary,
- }
-}
-
pub struct Writer<W> {
out: W,
names: crate::FastHashMap<NameKey, String>,
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -630,15 +580,64 @@ impl<W: Write> Writer<W> {
}
TypeInner::Pointer { base, class } => {
let (storage, maybe_access) = storage_class_str(class);
+ // Everything but `StorageClass::Handle` gives us a `storage` name, but
+ // Naga IR never produces pointers to handles, so it doesn't matter much
+ // how we write such a type. Just write it as the base type alone.
if let Some(class) = storage {
write!(self.out, "ptr<{}, ", class)?;
+ }
+ self.write_type(module, base)?;
+ if storage.is_some() {
if let Some(access) = maybe_access {
write!(self.out, ", {}", access)?;
}
+ write!(self.out, ">")?;
}
- self.write_type(module, base)?;
- if storage.is_some() {
+ }
+ TypeInner::ValuePointer {
+ size: None,
+ kind,
+ width: _,
+ class,
+ } => {
+ let (storage, maybe_access) = storage_class_str(class);
+ if let Some(class) = storage {
+ write!(self.out, "ptr<{}, {}", class, scalar_kind_str(kind))?;
+ if let Some(access) = maybe_access {
+ write!(self.out, ", {}", access)?;
+ }
+ write!(self.out, ">")?;
+ } else {
+ return Err(Error::Unimplemented(format!(
+ "ValuePointer to StorageClass::Handle {:?}",
+ inner
+ )));
+ }
+ }
+ TypeInner::ValuePointer {
+ size: Some(size),
+ kind,
+ width: _,
+ class,
+ } => {
+ let (storage, maybe_access) = storage_class_str(class);
+ if let Some(class) = storage {
+ write!(
+ self.out,
+ "ptr<{}, vec{}<{}>",
+ class,
+ back::vector_size_str(size),
+ scalar_kind_str(kind)
+ )?;
+ if let Some(access) = maybe_access {
+ write!(self.out, ", {}", access)?;
+ }
write!(self.out, ">")?;
+ } else {
+ return Err(Error::Unimplemented(format!(
+ "ValuePointer to StorageClass::Handle {:?}",
+ inner
+ )));
}
}
_ => {
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -976,6 +975,65 @@ impl<W: Write> Writer<W> {
Ok(())
}
+ /// Return the sort of indirection that `expr`'s plain form evaluates to.
+ ///
+ /// An expression's 'plain form' is the most general rendition of that
+ /// expression into WGSL, lacking `&` or `*` operators:
+ ///
+ /// - The plain form of `LocalVariable(x)` is simply `x`, which is a reference
+ /// to the local variable's storage.
+ ///
+ /// - The plain form of `GlobalVariable(g)` is simply `g`, which is usually a
+ /// reference to the global variable's storage. However, globals in the
+ /// `Handle` storage class are immutable, and `GlobalVariable` expressions for
+ /// those produce the value directly, not a pointer to it. Such
+ /// `GlobalVariable` expressions are `Ordinary`.
+ ///
+ /// - `Access` and `AccessIndex` are `Reference` when their `base` operand is a
+ /// pointer. If they are applied directly to a composite value, they are
+ /// `Ordinary`.
+ ///
+ /// Note that `FunctionArgument` expressions are never `Reference`, even when
+ /// the argument's type is `Pointer`. `FunctionArgument` always evaluates to the
+ /// argument's value directly, so any pointer it produces is merely the value
+ /// passed by the caller.
+ fn plain_form_indirection(
+ &self,
+ expr: Handle<crate::Expression>,
+ module: &Module,
+ func_ctx: &back::FunctionCtx<'_>,
+ ) -> Indirection {
+ use crate::Expression as Ex;
+
+ // Named expressions are `let` expressions, which apply the Load Rule,
+ // so if their type is a Naga pointer, then that must be a WGSL pointer
+ // as well.
+ if self.named_expressions.contains_key(&expr) {
+ return Indirection::Ordinary;
+ }
+
+ match func_ctx.expressions[expr] {
+ Ex::LocalVariable(_) => Indirection::Reference,
+ Ex::GlobalVariable(handle) => {
+ let global = &module.global_variables[handle];
+ match global.class {
+ crate::StorageClass::Handle => Indirection::Ordinary,
+ _ => Indirection::Reference,
+ }
+ }
+ Ex::Access { base, .. } | Ex::AccessIndex { base, .. } => {
+ let base_ty = func_ctx.info[base].ty.inner_with(&module.types);
+ match *base_ty {
+ crate::TypeInner::Pointer { .. } | crate::TypeInner::ValuePointer { .. } => {
+ Indirection::Reference
+ }
+ _ => Indirection::Ordinary,
+ }
+ }
+ _ => Indirection::Ordinary,
+ }
+ }
+
fn start_named_expr(
&mut self,
module: &Module,
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -1031,27 +1089,46 @@ impl<W: Write> Writer<W> {
func_ctx: &back::FunctionCtx<'_>,
requested: Indirection,
) -> BackendResult {
- use crate::Expression;
-
- if let Some(name) = self.named_expressions.get(&expr) {
- write!(self.out, "{}", name)?;
- return Ok(());
- }
-
// If the plain form of the expression is not what we need, emit the
// operator necessary to correct that.
- let plain = plain_form_indirection(expr, module, func_ctx);
- let opened_paren = match (requested, plain) {
+ let plain = self.plain_form_indirection(expr, module, func_ctx);
+ match (requested, plain) {
(Indirection::Ordinary, Indirection::Reference) => {
write!(self.out, "(&")?;
- true
+ self.write_expr_plain_form(module, expr, func_ctx, plain)?;
+ write!(self.out, ")")?;
}
(Indirection::Reference, Indirection::Ordinary) => {
write!(self.out, "(*")?;
- true
+ self.write_expr_plain_form(module, expr, func_ctx, plain)?;
+ write!(self.out, ")")?;
}
- (_, _) => false,
- };
+ (_, _) => self.write_expr_plain_form(module, expr, func_ctx, plain)?,
+ }
+
+ Ok(())
+ }
+
+ /// Write the 'plain form' of `expr`.
+ ///
+ /// An expression's 'plain form' is the most general rendition of that
+ /// expression into WGSL, lacking `&` or `*` operators. The plain forms of
+ /// `LocalVariable(x)` and `GlobalVariable(g)` are simply `x` and `g`. Such
+ /// Naga expressions represent both WGSL pointers and references; it's the
+ /// caller's responsibility to distinguish those cases appropriately.
+ fn write_expr_plain_form(
+ &mut self,
+ module: &Module,
+ expr: Handle<crate::Expression>,
+ func_ctx: &back::FunctionCtx<'_>,
+ indirection: Indirection,
+ ) -> BackendResult {
+ use crate::Expression;
+
+ if let Some(name) = self.named_expressions.get(&expr) {
+ write!(self.out, "{}", name)?;
+ return Ok(());
+ }
let expression = &func_ctx.expressions[expr];
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -1124,7 +1201,7 @@ impl<W: Write> Writer<W> {
}
// TODO: copy-paste from glsl-out
Expression::Access { base, index } => {
- self.write_expr_with_indirection(module, base, func_ctx, plain)?;
+ self.write_expr_with_indirection(module, base, func_ctx, indirection)?;
write!(self.out, "[")?;
self.write_expr(module, index, func_ctx)?;
write!(self.out, "]")?
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -1134,7 +1211,7 @@ impl<W: Write> Writer<W> {
let base_ty_res = &func_ctx.info[base].ty;
let mut resolved = base_ty_res.inner_with(&module.types);
- self.write_expr_with_indirection(module, base, func_ctx, plain)?;
+ self.write_expr_with_indirection(module, base, func_ctx, indirection)?;
let base_ty_handle = match *resolved {
TypeInner::Pointer { base, class: _ } => {
diff --git a/src/back/wgsl/writer.rs b/src/back/wgsl/writer.rs
--- a/src/back/wgsl/writer.rs
+++ b/src/back/wgsl/writer.rs
@@ -1561,10 +1638,6 @@ impl<W: Write> Writer<W> {
Expression::CallResult(_) | Expression::AtomicResult { .. } => {}
}
- if opened_paren {
- write!(self.out, ")")?
- };
-
Ok(())
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3223,7 +3223,7 @@ impl Parser {
.resolve_type(expr_id)?;
let expr_inner = context.typifier.get(expr_id, context.types);
let given_inner = &context.types[ty].inner;
- if given_inner != expr_inner {
+ if !given_inner.equivalent(expr_inner, context.types) {
log::error!(
"Given type {:?} doesn't match expected {:?}",
given_inner,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3284,7 +3284,7 @@ impl Parser {
Some(ty) => {
let expr_inner = context.typifier.get(value, context.types);
let given_inner = &context.types[ty].inner;
- if given_inner != expr_inner {
+ if !given_inner.equivalent(expr_inner, context.types) {
log::error!(
"Given type {:?} doesn't match expected {:?}",
given_inner,
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -7,6 +7,8 @@ mod namer;
mod terminator;
mod typifier;
+use std::cmp::PartialEq;
+
pub use index::IndexableLength;
pub use layouter::{Alignment, InvalidBaseType, Layouter, TypeLayout};
pub use namer::{EntryPointIndex, NameKey, Namer};
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -130,6 +132,50 @@ impl super::TypeInner {
Self::Image { .. } | Self::Sampler { .. } => 0,
}
}
+
+ /// Return the canoncal form of `self`, or `None` if it's already in
+ /// canonical form.
+ ///
+ /// Certain types have multiple representations in `TypeInner`. This
+ /// function converts all forms of equivalent types to a single
+ /// representative of their class, so that simply applying `Eq` to the
+ /// result indicates whether the types are equivalent, as far as Naga IR is
+ /// concerned.
+ pub fn canonical_form(&self, types: &crate::Arena<crate::Type>) -> Option<crate::TypeInner> {
+ use crate::TypeInner as Ti;
+ match *self {
+ Ti::Pointer { base, class } => match types[base].inner {
+ Ti::Scalar { kind, width } => Some(Ti::ValuePointer {
+ size: None,
+ kind,
+ width,
+ class,
+ }),
+ Ti::Vector { size, kind, width } => Some(Ti::ValuePointer {
+ size: Some(size),
+ kind,
+ width,
+ class,
+ }),
+ _ => None,
+ },
+ _ => None,
+ }
+ }
+
+ /// Compare `self` and `rhs` as types.
+ ///
+ /// This is mostly the same as `<TypeInner as Eq>::eq`, but it treats
+ /// `ValuePointer` and `Pointer` types as equivalent.
+ ///
+ /// When you know that one side of the comparison is never a pointer, it's
+ /// fine to not bother with canonicalization, and just compare `TypeInner`
+ /// values with `==`.
+ pub fn equivalent(&self, rhs: &crate::TypeInner, types: &crate::Arena<crate::Type>) -> bool {
+ let left = self.canonical_form(types);
+ let right = rhs.canonical_form(types);
+ left.as_ref().unwrap_or(self) == right.as_ref().unwrap_or(rhs)
+ }
}
impl super::MathFunction {
diff --git a/src/valid/compose.rs b/src/valid/compose.rs
--- a/src/valid/compose.rs
+++ b/src/valid/compose.rs
@@ -96,7 +96,11 @@ pub fn validate_compose(
});
}
for (index, comp_res) in component_resolutions.enumerate() {
- if comp_res.inner_with(type_arena) != &type_arena[base].inner {
+ let base_inner = &type_arena[base].inner;
+ let comp_res_inner = comp_res.inner_with(type_arena);
+ // We don't support arrays of pointers, but it seems best not to
+ // embed that assumption here, so use `TypeInner::equivalent`.
+ if !base_inner.equivalent(comp_res_inner, type_arena) {
log::error!("Array component[{}] type {:?}", index, comp_res);
return Err(ComposeError::ComponentType {
index: index as u32,
diff --git a/src/valid/compose.rs b/src/valid/compose.rs
--- a/src/valid/compose.rs
+++ b/src/valid/compose.rs
@@ -113,7 +117,11 @@ pub fn validate_compose(
}
for (index, (member, comp_res)) in members.iter().zip(component_resolutions).enumerate()
{
- if comp_res.inner_with(type_arena) != &type_arena[member.ty].inner {
+ let member_inner = &type_arena[member.ty].inner;
+ let comp_res_inner = comp_res.inner_with(type_arena);
+ // We don't support pointers in structs, but it seems best not to embed
+ // that assumption here, so use `TypeInner::equivalent`.
+ if !comp_res_inner.equivalent(member_inner, type_arena) {
log::error!("Struct component[{}] type {:?}", index, comp_res);
return Err(ComposeError::ComponentType {
index: index as u32,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -243,7 +243,8 @@ impl super::Validator {
let ty = context
.resolve_type_impl(expr, &self.valid_expression_set)
.map_err(|error| CallError::Argument { index, error })?;
- if ty != &context.types[arg.ty].inner {
+ let arg_inner = &context.types[arg.ty].inner;
+ if !ty.equivalent(arg_inner, context.types) {
return Err(CallError::ArgumentType {
index,
required: arg.ty,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -448,7 +449,17 @@ impl super::Validator {
.map(|expr| context.resolve_type(expr, &self.valid_expression_set))
.transpose()?;
let expected_ty = context.return_type.map(|ty| &context.types[ty].inner);
- if value_ty != expected_ty {
+ // We can't return pointers, but it seems best not to embed that
+ // assumption here, so use `TypeInner::equivalent` for comparison.
+ let okay = match (value_ty, expected_ty) {
+ (None, None) => true,
+ (Some(value_inner), Some(expected_inner)) => {
+ value_inner.equivalent(expected_inner, context.types)
+ }
+ (_, _) => false,
+ };
+
+ if !okay {
log::error!(
"Returning {:?} where {:?} is expected",
value_ty,
|
diff --git /dev/null b/tests/in/pointers.param.ron
new file mode 100644
--- /dev/null
+++ b/tests/in/pointers.param.ron
@@ -0,0 +1,7 @@
+(
+ spv: (
+ version: (1, 2),
+ debug: true,
+ adjust_coordinate_space: false,
+ ),
+)
diff --git /dev/null b/tests/in/pointers.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/in/pointers.wgsl
@@ -0,0 +1,5 @@
+fn f() {
+ var v: vec2<i32>;
+ let px = &v.x;
+ *px = 10;
+}
diff --git /dev/null b/tests/out/spv/pointers.spvasm
new file mode 100644
--- /dev/null
+++ b/tests/out/spv/pointers.spvasm
@@ -0,0 +1,29 @@
+; SPIR-V
+; Version: 1.2
+; Generator: rspirv
+; Bound: 16
+OpCapability Shader
+OpCapability Linkage
+%1 = OpExtInstImport "GLSL.std.450"
+OpMemoryModel Logical GLSL450
+OpSource GLSL 450
+OpName %6 "v"
+OpName %9 "f"
+%2 = OpTypeVoid
+%4 = OpTypeInt 32 1
+%3 = OpConstant %4 10
+%5 = OpTypeVector %4 2
+%7 = OpTypePointer Function %5
+%10 = OpTypeFunction %2
+%12 = OpTypePointer Function %4
+%14 = OpTypeInt 32 0
+%13 = OpConstant %14 0
+%9 = OpFunction %2 None %10
+%8 = OpLabel
+%6 = OpVariable %7 Function
+OpBranch %11
+%11 = OpLabel
+%15 = OpAccessChain %12 %6 %13
+OpStore %15 %3
+OpReturn
+OpFunctionEnd
\ No newline at end of file
diff --git /dev/null b/tests/out/wgsl/pointers.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/out/wgsl/pointers.wgsl
@@ -0,0 +1,8 @@
+fn f() {
+ var v: vec2<i32>;
+
+ let px: ptr<function, i32> = (&v.x);
+ (*px) = 10;
+ return;
+}
+
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -480,6 +480,7 @@ fn convert_wgsl() {
"access",
Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL,
),
+ ("pointers", Targets::SPIRV | Targets::WGSL),
(
"control-flow",
Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL,
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -687,6 +687,24 @@ fn invalid_functions() {
}
}
+#[test]
+fn pointer_type_equivalence() {
+ check_validation_error! {
+ r#"
+ fn f(pv: ptr<function, vec2<f32>>, pf: ptr<function, f32>) { }
+
+ fn g() {
+ var m: mat2x2<f32>;
+ let pv: ptr<function, vec2<f32>> = &m.x;
+ let pf: ptr<function, f32> = &m.x.x;
+
+ f(pv, pf);
+ }
+ "#:
+ Ok(_)
+ }
+}
+
#[test]
fn missing_bindings() {
check_validation_error! {
|
Naga produces incorrect WGSL for let-bound pointers
The following WGSL input generates incorrect WGSL output:
```
fn f() {
var v: vec2<i32>;
let px = &v.x;
*px = 10;
}
```
The output omits the `*`:
```
fn f() {
var v: vec2<i32>;
let px: ptr<function, i32> = (&v.x);
px = 10;
return;
}
```
This is because the fix for #1332 does not properly address named expressions.
|
2021-09-17T09:50:57Z
|
0.6
|
2021-09-28T17:03:01Z
|
2e7d629aefe6857ade4f96fe2c3dc1a09f0fa4db
|
[
"convert_wgsl",
"pointer_type_equivalence"
] |
[
"arena::tests::fetch_or_append_unique",
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"back::msl::test_error_size",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::access",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::version",
"front::wgsl::lexer::test_tokens",
"front::spv::test::parse",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::expressions",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_decimal_floats",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_hex_floats",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_hex_ints",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_type_inference",
"proc::test_matrix_size",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::functions",
"convert_spv_pointer_access",
"convert_spv_inverse_hyperbolic_trig_functions",
"convert_spv_quad_vert",
"convert_spv_shadow",
"convert_glsl_folder",
"sampler1d",
"cube_array",
"storage1d",
"geometry",
"storage_image_formats",
"sample_rate_shading",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"bad_texture_sample_type",
"inconsistent_binding",
"invalid_float",
"invalid_texture_sample_type",
"bad_type_cast",
"invalid_integer",
"invalid_structs",
"local_var_missing_type",
"invalid_local_vars",
"bad_texture",
"dead_code",
"invalid_functions",
"local_var_type_mismatch",
"let_type_mismatch",
"struct_member_zero_align",
"unknown_attribute",
"unknown_access",
"invalid_access",
"struct_member_zero_size",
"invalid_arrays",
"unknown_built_in",
"unknown_conservative_depth",
"unknown_scalar_type",
"unknown_shader_stage",
"negative_index",
"unknown_ident",
"unknown_storage_class",
"unknown_local_function",
"unknown_type",
"postfix_pointers",
"unknown_storage_format",
"zero_array_stride",
"unknown_identifier",
"missing_bindings",
"valid_access",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,367
|
gfx-rs__naga-1367
|
[
"1356"
] |
933ecc4a443cb882bce0283fe77897bba6007080
|
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -165,9 +165,9 @@ pub enum Error<'a> {
MissingType(Span),
InvalidAtomicPointer(Span),
InvalidAtomicOperandType(Span),
+ Pointer(&'static str, Span),
NotPointer(Span),
- AddressOfNotReference(Span),
- AssignmentNotReference(Span),
+ NotReference(&'static str, Span),
Other,
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -419,14 +419,14 @@ impl<'a> Error<'a> {
labels: vec![(span.clone(), "expression is not a pointer".into())],
notes: vec![],
},
- Error::AddressOfNotReference(ref span) => ParseError {
- message: "the operand of the `&` operator must be a reference".to_string(),
+ Error::NotReference(what, ref span) => ParseError {
+ message: format!("{} must be a reference", what),
labels: vec![(span.clone(), "expression is not a reference".into())],
notes: vec![],
},
- Error::AssignmentNotReference(ref span) => ParseError {
- message: "the left-hand side of an assignment be a reference".to_string(),
- labels: vec![(span.clone(), "expression is not a reference".into())],
+ Error::Pointer(what, ref span) => ParseError {
+ message: format!("{} must not be a pointer", what),
+ labels: vec![(span.clone(), "expression is a pointer".into())],
notes: vec![],
},
Error::Other => ParseError {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -692,15 +692,15 @@ trait StringValueLookup<'a> {
type Value;
fn lookup(&self, key: &'a str, span: Span) -> Result<Self::Value, Error<'a>>;
}
-impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, Handle<crate::Expression>> {
- type Value = Handle<crate::Expression>;
+impl<'a> StringValueLookup<'a> for FastHashMap<&'a str, TypedExpression> {
+ type Value = TypedExpression;
fn lookup(&self, key: &'a str, span: Span) -> Result<Self::Value, Error<'a>> {
self.get(key).cloned().ok_or(Error::UnknownIdent(span, key))
}
}
struct StatementContext<'input, 'temp, 'out> {
- lookup_ident: &'temp mut FastHashMap<&'input str, Handle<crate::Expression>>,
+ lookup_ident: &'temp mut FastHashMap<&'input str, TypedExpression>,
typifier: &'temp mut super::Typifier,
variables: &'out mut Arena<crate::LocalVariable>,
expressions: &'out mut Arena<crate::Expression>,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -758,7 +758,7 @@ struct SamplingContext {
}
struct ExpressionContext<'input, 'temp, 'out> {
- lookup_ident: &'temp FastHashMap<&'input str, Handle<crate::Expression>>,
+ lookup_ident: &'temp FastHashMap<&'input str, TypedExpression>,
typifier: &'temp mut super::Typifier,
expressions: &'out mut Arena<crate::Expression>,
types: &'out mut Arena<crate::Type>,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -811,7 +811,7 @@ impl<'a> ExpressionContext<'a, '_, '_> {
image_name: &'a str,
span: Span,
) -> Result<SamplingContext, Error<'a>> {
- let image = self.lookup_ident.lookup(image_name, span.clone())?;
+ let image = self.lookup_ident.lookup(image_name, span.clone())?.handle;
Ok(SamplingContext {
image,
arrayed: match *self.resolve_type(image)? {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1567,7 +1567,7 @@ impl Parser {
lexer.close_arguments()?;
crate::Expression::ImageSample {
image: sc.image,
- sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?,
+ sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle,
coordinate,
array_index,
offset,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1600,7 +1600,7 @@ impl Parser {
lexer.close_arguments()?;
crate::Expression::ImageSample {
image: sc.image,
- sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?,
+ sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle,
coordinate,
array_index,
offset,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1633,7 +1633,7 @@ impl Parser {
lexer.close_arguments()?;
crate::Expression::ImageSample {
image: sc.image,
- sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?,
+ sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle,
coordinate,
array_index,
offset,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1668,7 +1668,7 @@ impl Parser {
lexer.close_arguments()?;
crate::Expression::ImageSample {
image: sc.image,
- sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?,
+ sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle,
coordinate,
array_index,
offset,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1701,7 +1701,7 @@ impl Parser {
lexer.close_arguments()?;
crate::Expression::ImageSample {
image: sc.image,
- sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?,
+ sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle,
coordinate,
array_index,
offset,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1734,7 +1734,7 @@ impl Parser {
lexer.close_arguments()?;
crate::Expression::ImageSample {
image: sc.image,
- sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?,
+ sampler: ctx.lookup_ident.lookup(sampler_name, sampler_span)?.handle,
coordinate,
array_index,
offset,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1746,7 +1746,10 @@ impl Parser {
let _ = lexer.next();
lexer.open_arguments()?;
let (image_name, image_span) = lexer.next_ident_with_span()?;
- let image = ctx.lookup_ident.lookup(image_name, image_span.clone())?;
+ let image = ctx
+ .lookup_ident
+ .lookup(image_name, image_span.clone())?
+ .handle;
lexer.expect(Token::Separator(','))?;
let coordinate = self.parse_general_expression(lexer, ctx.reborrow())?;
let (class, arrayed) = match *ctx.resolve_type(image)? {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1779,7 +1782,7 @@ impl Parser {
let _ = lexer.next();
lexer.open_arguments()?;
let (image_name, image_span) = lexer.next_ident_with_span()?;
- let image = ctx.lookup_ident.lookup(image_name, image_span)?;
+ let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle;
let level = if lexer.skip(Token::Separator(',')) {
let expr = self.parse_general_expression(lexer, ctx.reborrow())?;
Some(expr)
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1796,7 +1799,7 @@ impl Parser {
let _ = lexer.next();
lexer.open_arguments()?;
let (image_name, image_span) = lexer.next_ident_with_span()?;
- let image = ctx.lookup_ident.lookup(image_name, image_span)?;
+ let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle;
lexer.close_arguments()?;
crate::Expression::ImageQuery {
image,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1807,7 +1810,7 @@ impl Parser {
let _ = lexer.next();
lexer.open_arguments()?;
let (image_name, image_span) = lexer.next_ident_with_span()?;
- let image = ctx.lookup_ident.lookup(image_name, image_span)?;
+ let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle;
lexer.close_arguments()?;
crate::Expression::ImageQuery {
image,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1818,7 +1821,7 @@ impl Parser {
let _ = lexer.next();
lexer.open_arguments()?;
let (image_name, image_span) = lexer.next_ident_with_span()?;
- let image = ctx.lookup_ident.lookup(image_name, image_span)?;
+ let image = ctx.lookup_ident.lookup(image_name, image_span)?.handle;
lexer.close_arguments()?;
crate::Expression::ImageQuery {
image,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2074,18 +2077,15 @@ impl Parser {
)
}
(Token::Word(word), span) => {
- if let Some(&handle) = ctx.lookup_ident.get(word) {
+ if let Some(definition) = ctx.lookup_ident.get(word) {
let _ = lexer.next();
self.pop_scope(lexer);
// Not all identifiers constitute references in WGSL.
- let is_reference = match ctx.expressions[handle] {
- // `let`-bound identifiers don't evaluate to references. But that
- // means `let` declarations apply the Load Rule to their values,
- // so we will never see a `LocalVariable` in `lookup_ident` for a
- // `let` binding. Thus, a Naga `LocalVariable` always means a WGSL
- // `var` binding.
- crate::Expression::LocalVariable(_) => true,
+ let is_reference = match ctx.expressions[definition.handle] {
+ // `let`-bound identifiers don't evaluate to references: `let`
+ // declarations apply the Load Rule to their values.
+ crate::Expression::LocalVariable(_) => definition.is_reference,
// Global variables in the `Handle` storage class do not evaluate
// to references.
crate::Expression::GlobalVariable(global) => {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2095,7 +2095,7 @@ impl Parser {
};
TypedExpression {
- handle,
+ handle: definition.handle,
is_reference,
}
} else if let Some(expr) =
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2135,43 +2135,56 @@ impl Parser {
mut handle,
mut is_reference,
} = expr;
+ let mut prefix_span = lexer.span_from(span_start);
loop {
+ // Step lightly around `resolve_type`'s mutable borrow.
+ ctx.resolve_type(handle)?;
+
+ // Find the type of the composite whose elements, components or members we're
+ // accessing, skipping through references: except for swizzles, the `Access`
+ // or `AccessIndex` expressions we'd generate are the same either way.
+ //
+ // Pointers, however, are not permitted. For error checks below, note whether
+ // the base expression is a WGSL pointer.
+ let temp_inner;
+ let (composite, wgsl_pointer) = match *ctx.typifier.get(handle, ctx.types) {
+ crate::TypeInner::Pointer { base, .. } => (&ctx.types[base].inner, !is_reference),
+ crate::TypeInner::ValuePointer {
+ size: None,
+ kind,
+ width,
+ ..
+ } => {
+ temp_inner = crate::TypeInner::Scalar { kind, width };
+ (&temp_inner, !is_reference)
+ }
+ crate::TypeInner::ValuePointer {
+ size: Some(size),
+ kind,
+ width,
+ ..
+ } => {
+ temp_inner = crate::TypeInner::Vector { size, kind, width };
+ (&temp_inner, !is_reference)
+ }
+ ref other => (other, false),
+ };
+
let expression = match lexer.peek().0 {
Token::Separator('.') => {
let _ = lexer.next();
let (name, name_span) = lexer.next_ident_with_span()?;
- // Step lightly around `resolve_type`'s mutable borrow.
- ctx.resolve_type(handle)?;
-
- // Find the type of the composite whose components or members we're
- // accessing, skipping through pointers: except for swizzles, the
- // `Access` or `AccessIndex` expressions we'd generate are the same
- // either way.
- let temp_inner;
- let composite = match *ctx.typifier.get(handle, ctx.types) {
- crate::TypeInner::Pointer { base, .. } => &ctx.types[base].inner,
- crate::TypeInner::ValuePointer {
- size: None,
- kind,
- width,
- ..
- } => {
- temp_inner = crate::TypeInner::Scalar { kind, width };
- &temp_inner
- }
- crate::TypeInner::ValuePointer {
- size: Some(size),
- kind,
- width,
- ..
- } => {
- temp_inner = crate::TypeInner::Vector { size, kind, width };
- &temp_inner
- }
- ref other => other,
- };
+ // WGSL doesn't allow accessing members on pointers, or swizzling
+ // them. But Naga IR doesn't distinguish pointers and references, so
+ // we must check here.
+ if wgsl_pointer {
+ return Err(Error::Pointer(
+ "the value accessed by a `.member` expression",
+ prefix_span,
+ ));
+ }
let access = match *composite {
crate::TypeInner::Struct { ref members, .. } => {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2219,6 +2232,15 @@ impl Parser {
let index = self.parse_general_expression(lexer, ctx.reborrow())?;
let close_brace_span = lexer.expect_span(Token::Paren(']'))?;
+ // WGSL doesn't allow pointers to be subscripted. But Naga IR doesn't
+ // distinguish pointers and references, so we must check here.
+ if wgsl_pointer {
+ return Err(Error::Pointer(
+ "the value indexed by a `[]` subscripting expression",
+ prefix_span,
+ ));
+ }
+
if let crate::Expression::Constant(constant) = ctx.expressions[index] {
let expr_span = open_brace_span.end..close_brace_span.start;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2248,9 +2270,10 @@ impl Parser {
_ => break,
};
+ prefix_span = lexer.span_from(span_start);
handle = ctx
.expressions
- .append(expression, NagaSpan::from(lexer.span_from(span_start)));
+ .append(expression, NagaSpan::from(prefix_span.clone()));
}
Ok(TypedExpression {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2327,7 +2350,7 @@ impl Parser {
.get_span(operand.handle)
.to_range()
.unwrap_or_else(|| self.peek_scope(lexer));
- return Err(Error::AddressOfNotReference(span));
+ return Err(Error::NotReference("the operand of the `&` operator", span));
}
// No code is generated. We just declare the pointer a reference now.
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3065,7 +3088,10 @@ impl Parser {
// The left hand side of an assignment must be a reference.
if !reference.is_reference {
let span = span_start..lexer.current_byte_offset();
- return Err(Error::AssignmentNotReference(span));
+ return Err(Error::NotReference(
+ "the left-hand side of an assignment",
+ span,
+ ));
}
lexer.expect(Token::Operation('='))?;
let value = self.parse_general_expression(lexer, context.reborrow())?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3183,7 +3209,13 @@ impl Parser {
}
}
block.extend(emitter.finish(context.expressions));
- context.lookup_ident.insert(name, expr_id);
+ context.lookup_ident.insert(
+ name,
+ TypedExpression {
+ handle: expr_id,
+ is_reference: false,
+ },
+ );
context
.named_expressions
.insert(expr_id, String::from(name));
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3291,7 +3323,13 @@ impl Parser {
let expr_id = context
.expressions
.append(crate::Expression::LocalVariable(var_id), Default::default());
- context.lookup_ident.insert(name, expr_id);
+ context.lookup_ident.insert(
+ name,
+ TypedExpression {
+ handle: expr_id,
+ is_reference: true,
+ },
+ );
if let Init::Variable(value) = init {
Some(crate::Statement::Store {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3597,7 +3635,8 @@ impl Parser {
let (image_name, image_span) = lexer.next_ident_with_span()?;
let image = context
.lookup_ident
- .lookup(image_name, image_span.clone())?;
+ .lookup(image_name, image_span.clone())?
+ .handle;
lexer.expect(Token::Separator(','))?;
let mut expr_context = context.as_expression(block, &mut emitter);
let arrayed = match *expr_context.resolve_type(image)? {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3722,15 +3761,22 @@ impl Parser {
// populate initial expressions
let mut expressions = Arena::new();
for (&name, expression) in lookup_global_expression.iter() {
- let span = match *expression {
- crate::Expression::GlobalVariable(handle) => {
- module.global_variables.get_span(handle)
- }
- crate::Expression::Constant(handle) => module.constants.get_span(handle),
+ let (span, is_reference) = match *expression {
+ crate::Expression::GlobalVariable(handle) => (
+ module.global_variables.get_span(handle),
+ module.global_variables[handle].class != crate::StorageClass::Handle,
+ ),
+ crate::Expression::Constant(handle) => (module.constants.get_span(handle), false),
_ => unreachable!(),
};
- let expr_handle = expressions.append(expression.clone(), span);
- lookup_ident.insert(name, expr_handle);
+ let expression = expressions.append(expression.clone(), span);
+ lookup_ident.insert(
+ name,
+ TypedExpression {
+ handle: expression,
+ is_reference,
+ },
+ );
}
// read parameter list
let mut arguments = Vec::new();
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -3747,11 +3793,17 @@ impl Parser {
let (param_name, param_name_span, param_type, _access) =
self.parse_variable_ident_decl(lexer, &mut module.types, &mut module.constants)?;
let param_index = arguments.len() as u32;
- let expression_token = expressions.append(
+ let expression = expressions.append(
crate::Expression::FunctionArgument(param_index),
NagaSpan::from(param_name_span),
);
- lookup_ident.insert(param_name, expression_token);
+ lookup_ident.insert(
+ param_name,
+ TypedExpression {
+ handle: expression,
+ is_reference: false,
+ },
+ );
arguments.push(crate::FunctionArgument {
name: Some(param_name.to_string()),
ty: param_type,
|
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -493,6 +493,44 @@ fn local_var_missing_type() {
);
}
+#[test]
+fn postfix_pointers() {
+ check(
+ r#"
+ fn main() {
+ var v: vec4<f32> = vec4<f32>(1.0, 1.0, 1.0, 1.0);
+ let pv = &v;
+ let a = *pv[3]; // Problematic line
+ }
+ "#,
+ r#"error: the value indexed by a `[]` subscripting expression must not be a pointer
+ ┌─ wgsl:5:26
+ │
+5 │ let a = *pv[3]; // Problematic line
+ │ ^^ expression is a pointer
+
+"#,
+ );
+
+ check(
+ r#"
+ struct S { m: i32; };
+ fn main() {
+ var s: S = S(42);
+ let ps = &s;
+ let a = *ps.m; // Problematic line
+ }
+ "#,
+ r#"error: the value accessed by a `.member` expression must not be a pointer
+ ┌─ wgsl:6:26
+ │
+6 │ let a = *ps.m; // Problematic line
+ │ ^^ expression is a pointer
+
+"#,
+ );
+}
+
macro_rules! check_validation_error {
// We want to support an optional guard expression after the pattern, so
// that we can check values we can't match against, like strings.
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -778,6 +816,13 @@ fn valid_access() {
// `Access` to a `ValuePointer`.
return temp[i][j];
}
+ ",
+ "
+ fn main() {
+ var v: vec4<f32> = vec4<f32>(1.0, 1.0, 1.0, 1.0);
+ let pv = &v;
+ let a = (*pv)[3];
+ }
":
Ok(_)
}
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -789,7 +834,7 @@ fn invalid_local_vars() {
"
struct Unsized { data: array<f32>; };
fn local_ptr_dynamic_array(okay: ptr<storage, Unsized>) {
- var not_okay: ptr<storage, array<f32>> = okay.data;
+ var not_okay: ptr<storage, array<f32>> = &(*okay).data;
}
":
Err(naga::valid::ValidationError::Function {
|
[wgsl-in] Missing parentheses around dereference
https://github.com/gfx-rs/naga/pull/1348 fixed this for wgsl-out, but the following still incorrectly validates:
```
[[stage(vertex)]]
fn main() -> [[builtin(position)]] vec4<f32> {
var v: vec4<f32> = vec4<f32>(1.0, 1.0, 1.0, 1.0);
let pv = &v;
let a = *pv[3]; // Problematic line
return v;
}
```
```
cargo run -- test.wgsl
```
[According to the WGSL grammar](https://www.w3.org/TR/WGSL/#expression-grammar), [] should bind more tightly than *, so `*pv[3]` should not pass validation. The correct code would be `(*pv)[3]`.
naga @ https://github.com/gfx-rs/naga/commit/0e66930aff1340d5c636df616d573cc326702158
|
I've reproduced this. Indeed, `*pv[3]` parenthesizes as `*(pv[3])`, which is ill-typed.
Naga's WGSL front end doesn't follow the grammar in the spec very closely, so I think there are a number of problems along these lines. See also #1352.
This was not fixed by #1360. The [approach](https://github.com/gfx-rs/naga/blob/933ecc4a443cb882bce0283fe77897bba6007080/src/front/wgsl/mod.rs#L2083-L2087) I took to handling `let` bindings is incorrect.
|
2021-09-15T11:04:10Z
|
0.6
|
2021-09-15T22:52:26Z
|
2e7d629aefe6857ade4f96fe2c3dc1a09f0fa4db
|
[
"postfix_pointers",
"valid_access"
] |
[
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"back::msl::writer::test_stack_size",
"front::wgsl::lexer::test_tokens",
"front::spv::test::parse",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_decimal_floats",
"front::glsl::parser_tests::structs",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::expressions",
"front::wgsl::tests::parse_hex_ints",
"front::wgsl::tests::parse_hex_floats",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_statement",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_storage_buffers",
"front::glsl::parser_tests::control_flow",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_switch",
"proc::test_matrix_size",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_types",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_spv_pointer_access",
"convert_spv_inverse_hyperbolic_trig_functions",
"convert_spv_quad_vert",
"convert_spv_shadow",
"convert_glsl_folder",
"convert_wgsl",
"sampler1d",
"cube_array",
"geometry",
"storage1d",
"sample_rate_shading",
"storage_image_formats",
"image_queries",
"function_without_identifier",
"bad_for_initializer",
"bad_texture_sample_type",
"invalid_float",
"inconsistent_binding",
"invalid_integer",
"bad_type_cast",
"invalid_texture_sample_type",
"local_var_missing_type",
"let_type_mismatch",
"invalid_structs",
"invalid_arrays",
"invalid_access",
"local_var_type_mismatch",
"struct_member_zero_size",
"bad_texture",
"struct_member_zero_align",
"invalid_functions",
"negative_index",
"unknown_conservative_depth",
"unknown_access",
"unknown_attribute",
"invalid_local_vars",
"unknown_built_in",
"missing_bindings",
"unknown_shader_stage",
"unknown_storage_class",
"unknown_storage_format",
"unknown_ident",
"unknown_local_function",
"unknown_scalar_type",
"unknown_identifier",
"zero_array_stride",
"unknown_type",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 17)",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 26)",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
gfx-rs/naga
| 1,304
|
gfx-rs__naga-1304
|
[
"1017"
] |
28547e3d3b61a7872cdba66638f0bae17154f031
|
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1013,6 +1013,11 @@ impl<'w> BlockContext<'w> {
Instruction::switch(selector_id, default_id, &raw_cases),
);
+ let inner_context = LoopContext {
+ break_id: Some(merge_id),
+ ..loop_context
+ };
+
for (i, (case, raw_case)) in cases.iter().zip(raw_cases.iter()).enumerate() {
let case_finish_id = if case.fall_through {
match raw_cases.get(i + 1) {
diff --git a/src/back/spv/block.rs b/src/back/spv/block.rs
--- a/src/back/spv/block.rs
+++ b/src/back/spv/block.rs
@@ -1026,11 +1031,11 @@ impl<'w> BlockContext<'w> {
raw_case.label_id,
&case.body,
Some(case_finish_id),
- LoopContext::default(),
+ inner_context,
)?;
}
- self.write_block(default_id, default, Some(merge_id), LoopContext::default())?;
+ self.write_block(default_id, default, Some(merge_id), inner_context)?;
block = Block::new(merge_id);
}
|
diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl
--- a/tests/in/control-flow.wgsl
+++ b/tests/in/control-flow.wgsl
@@ -30,3 +30,30 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3<u32>) {
}
}
}
+
+fn switch_default_break(i: i32) {
+ switch (i) {
+ default: {
+ break;
+ }
+ }
+}
+
+fn switch_case_break() {
+ switch(0) {
+ case 0: {
+ break;
+ }
+ }
+ return;
+}
+
+fn loop_switch_continue(x: i32) {
+ loop {
+ switch (x) {
+ case 1: {
+ continue;
+ }
+ }
+ }
+}
diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl
--- a/tests/out/glsl/control-flow.main.Compute.glsl
+++ b/tests/out/glsl/control-flow.main.Compute.glsl
@@ -6,6 +6,31 @@ precision highp int;
layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
+void switch_default_break(int i) {
+ switch(i) {
+ default:
+ break;
+ }
+}
+
+void switch_case_break() {
+ switch(0) {
+ case 0:
+ break;
+ }
+ return;
+}
+
+void loop_switch_continue(int x) {
+ while(true) {
+ switch(x) {
+ case 1:
+ continue;
+ }
+ }
+ return;
+}
+
void main() {
uvec3 global_id = gl_GlobalInvocationID;
int pos = 0;
diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl
--- a/tests/out/hlsl/control-flow.hlsl
+++ b/tests/out/hlsl/control-flow.hlsl
@@ -1,4 +1,37 @@
+void switch_default_break(int i)
+{
+ switch(i) {
+ default: {
+ break;
+ }
+ }
+}
+
+void switch_case_break()
+{
+ switch(0) {
+ case 0: {
+ break;
+ break;
+ }
+ }
+ return;
+}
+
+void loop_switch_continue(int x)
+{
+ while(true) {
+ switch(x) {
+ case 1: {
+ continue;
+ break;
+ }
+ }
+ }
+ return;
+}
+
[numthreads(1, 1, 1)]
void main(uint3 global_id : SV_DispatchThreadID)
{
diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl
--- a/tests/out/msl/control-flow.msl
+++ b/tests/out/msl/control-flow.msl
@@ -3,6 +3,45 @@
#include <simd/simd.h>
+void switch_default_break(
+ int i
+) {
+ switch(i) {
+ default: {
+ break;
+ }
+ }
+}
+
+void switch_case_break(
+) {
+ switch(0) {
+ case 0: {
+ break;
+ break;
+ }
+ default: {
+ }
+ }
+ return;
+}
+
+void loop_switch_continue(
+ int x
+) {
+ while(true) {
+ switch(x) {
+ case 1: {
+ continue;
+ break;
+ }
+ default: {
+ }
+ }
+ }
+ return;
+}
+
struct main1Input {
};
kernel void main1(
diff --git a/tests/out/spv/control-flow.spvasm b/tests/out/spv/control-flow.spvasm
--- a/tests/out/spv/control-flow.spvasm
+++ b/tests/out/spv/control-flow.spvasm
@@ -1,29 +1,109 @@
; SPIR-V
; Version: 1.1
; Generator: rspirv
-; Bound: 16
+; Bound: 56
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
-OpEntryPoint GLCompute %9 "main" %6
-OpExecutionMode %9 LocalSize 1 1 1
-OpDecorate %6 BuiltIn GlobalInvocationId
+OpEntryPoint GLCompute %41 "main" %38
+OpExecutionMode %41 LocalSize 1 1 1
+OpDecorate %38 BuiltIn GlobalInvocationId
%2 = OpTypeVoid
-%4 = OpTypeInt 32 0
-%3 = OpTypeVector %4 3
-%7 = OpTypePointer Input %3
-%6 = OpVariable %7 Input
-%10 = OpTypeFunction %2
-%12 = OpConstant %4 2
-%13 = OpConstant %4 1
-%14 = OpConstant %4 72
-%15 = OpConstant %4 264
-%9 = OpFunction %2 None %10
-%5 = OpLabel
-%8 = OpLoad %3 %6
-OpBranch %11
-%11 = OpLabel
-OpControlBarrier %12 %13 %14
-OpControlBarrier %12 %12 %15
+%4 = OpTypeInt 32 1
+%3 = OpConstant %4 1
+%5 = OpConstant %4 0
+%6 = OpConstant %4 2
+%7 = OpConstant %4 3
+%9 = OpTypeInt 32 0
+%8 = OpTypeVector %9 3
+%13 = OpTypeFunction %2 %4
+%19 = OpTypeFunction %2
+%36 = OpTypePointer Function %4
+%39 = OpTypePointer Input %8
+%38 = OpVariable %39 Input
+%43 = OpConstant %9 2
+%44 = OpConstant %9 1
+%45 = OpConstant %9 72
+%46 = OpConstant %9 264
+%12 = OpFunction %2 None %13
+%11 = OpFunctionParameter %4
+%10 = OpLabel
+OpBranch %14
+%14 = OpLabel
+OpSelectionMerge %15 None
+OpSwitch %11 %16
+%16 = OpLabel
+OpBranch %15
+%15 = OpLabel
+OpReturn
+OpFunctionEnd
+%18 = OpFunction %2 None %19
+%17 = OpLabel
+OpBranch %20
+%20 = OpLabel
+OpSelectionMerge %21 None
+OpSwitch %5 %22 0 %23
+%23 = OpLabel
+OpBranch %21
+%22 = OpLabel
+OpBranch %21
+%21 = OpLabel
+OpReturn
+OpFunctionEnd
+%26 = OpFunction %2 None %13
+%25 = OpFunctionParameter %4
+%24 = OpLabel
+OpBranch %27
+%27 = OpLabel
+OpBranch %28
+%28 = OpLabel
+OpLoopMerge %29 %31 None
+OpBranch %30
+%30 = OpLabel
+OpSelectionMerge %32 None
+OpSwitch %25 %33 1 %34
+%34 = OpLabel
+OpBranch %31
+%33 = OpLabel
+OpBranch %32
+%32 = OpLabel
+OpBranch %31
+%31 = OpLabel
+OpBranch %28
+%29 = OpLabel
+OpReturn
+OpFunctionEnd
+%41 = OpFunction %2 None %19
+%37 = OpLabel
+%35 = OpVariable %36 Function
+%40 = OpLoad %8 %38
+OpBranch %42
+%42 = OpLabel
+OpControlBarrier %43 %44 %45
+OpControlBarrier %43 %43 %46
+OpSelectionMerge %47 None
+OpSwitch %3 %48
+%48 = OpLabel
+OpStore %35 %3
+OpBranch %47
+%47 = OpLabel
+%49 = OpLoad %4 %35
+OpSelectionMerge %50 None
+OpSwitch %49 %51 1 %52 2 %53 3 %54 4 %55
+%52 = OpLabel
+OpStore %35 %5
+OpBranch %50
+%53 = OpLabel
+OpStore %35 %3
+OpReturn
+%54 = OpLabel
+OpStore %35 %6
+OpBranch %55
+%55 = OpLabel
+OpReturn
+%51 = OpLabel
+OpStore %35 %7
+OpReturn
+%50 = OpLabel
OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl
--- a/tests/out/wgsl/control-flow.wgsl
+++ b/tests/out/wgsl/control-flow.wgsl
@@ -1,3 +1,31 @@
+fn switch_default_break(i: i32) {
+ switch(i) {
+ default: {
+ break;
+ }
+ }
+}
+
+fn switch_case_break() {
+ switch(0) {
+ case 0: {
+ break;
+ }
+ }
+ return;
+}
+
+fn loop_switch_continue(x: i32) {
+ loop {
+ switch(x) {
+ case 1: {
+ continue;
+ }
+ }
+ }
+ return;
+}
+
[[stage(compute), workgroup_size(1, 1, 1)]]
fn main([[builtin(global_invocation_id)]] global_id: vec3<u32>) {
var pos: i32;
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -448,9 +448,7 @@ fn convert_wgsl() {
),
(
"control-flow",
- // TODO: SPIRV https://github.com/gfx-rs/naga/issues/1017
- //Targets::SPIRV |
- Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL,
+ Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL,
),
(
"standard",
|
Naga panics translating valid WGSL to SPIR-V
This may be a duplicate, but filing it just in case: The following WGSL program passes validation, but panics in `back/spv/writer.rs`:
```
fn loop_switch_continue(x: i32) {
loop {
switch (x) {
case 1: {
continue;
}
}
}
}
```
The failing code is the `unwrap` [here](https://github.com/gfx-rs/naga/blob/64b9e4501576bf5fecdb60c6375b191becbaa992/src/back/spv/writer.rs#L2583):
```
crate::Statement::Continue => {
block.termination =
Some(Instruction::branch(loop_context.continuing_id.unwrap()));
}
```
|
I think it'll be a challenge to generate SPIR-V for this. SPIR-V §2.11, "Structured Control Flow", includes this rule:
> each header block must strictly dominate its merge block, unless the merge block is unreachable in the CFG
Control flow in shaders is required to be structured, which means that the WGSL `switch` statement gets translated into a SPIR-V `OpSelectionMerge` followed by an `OpSwitch`. The rule quoted above implies that the `continue` cannot simply be translated into an `OpBranch` to the `loop`'s continue target.
I'll see what `glslangValidate` does with similar GLSL code.
Okay, I was misunderstanding the rule:
Although the header block must strictly dominate the merge block, that does not imply that all paths much reach the merge block, as I had incorrectly inferred. There is no requirement that the merge block post-dominate the header block.
Given this GLSL:
```
#version 450
int f(int q) { return q + 1; }
void main() {
int i;
for (i = 0; i < 10; i++) {
switch (i & 3) {
case 1: {
continue;
}
}
i = f(i);
}
}
```
edit: glslangValidator produces the following SPIR-V for the body of `main`:
```
%19 = OpLabel
OpLoopMerge %21 %22 None
OpBranch %23
%23 = OpLabel
%24 = OpLoad %int %i
%27 = OpSLessThan %bool %24 %int_10
OpBranchConditional %27 %20 %21
%20 = OpLabel
%28 = OpLoad %int %i
%30 = OpBitwiseAnd %int %28 %int_3
OpSelectionMerge %32 None
OpSwitch %30 %32 1 %31
%31 = OpLabel
OpBranch %22
%32 = OpLabel
%36 = OpLoad %int %i
OpStore %param %36
%37 = OpFunctionCall %int %f_i1_ %param
OpStore %i %37
OpBranch %22
%22 = OpLabel
%38 = OpLoad %int %i
%39 = OpIAdd %int %38 %int_1
OpStore %i %39
OpBranch %19
%21 = OpLabel
OpReturn
OpFunctionEnd
```
And this validates just fine.
I think this wgsl also connected with this issue:
```wgsl
[[stage(compute), workgroup_size(1)]]
fn main() {
var pos: i32 = 0;
switch (pos) {
case 1: {
break;
}
}
}
```
panic here: https://github.com/gfx-rs/naga/blob/64b9e4501576bf5fecdb60c6375b191becbaa992/src/back/spv/writer.rs#L2579
```log
[2021-08-21T17:06:41Z DEBUG naga::front] Resolving [1] = Constant([1]) : Value(Scalar { kind: Sint, width: 4 })
[2021-08-21T17:06:41Z DEBUG naga::front] Resolving [2] = LocalVariable([1]) : Value(Pointer { base: [1], class: Function })
[2021-08-21T17:06:41Z DEBUG naga::valid::function] var LocalVariable { name: Some("pos"), ty: [1], init: Some([1]) }
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src/back/spv/block.rs:1552:83
stack backtrace:
0: rust_begin_unwind
at /rustc/a178d0322ce20e33eac124758e837cbd80a6f633/library/std/src/panicking.rs:515:5
1: core::panicking::panic_fmt
at /rustc/a178d0322ce20e33eac124758e837cbd80a6f633/library/core/src/panicking.rs:92:14
2: core::panicking::panic
at /rustc/a178d0322ce20e33eac124758e837cbd80a6f633/library/core/src/panicking.rs:50:5
3: core::option::Option<T>::unwrap
at /rustc/a178d0322ce20e33eac124758e837cbd80a6f633/library/core/src/option.rs:388:21
4: naga::back::spv::block::<impl naga::back::spv::BlockContext>::write_block
at ./src/back/spv/block.rs:1552:61
5: naga::back::spv::block::<impl naga::back::spv::BlockContext>::write_block
at ./src/back/spv/block.rs:1494:25
6: naga::back::spv::writer::<impl naga::back::spv::Writer>::write_function
at ./src/back/spv/writer.rs:453:9
7: naga::back::spv::writer::<impl naga::back::spv::Writer>::write_entry_point
at ./src/back/spv/writer.rs:488:27
8: naga::back::spv::writer::<impl naga::back::spv::Writer>::write_logical_layout
at ./src/back/spv/writer.rs:1225:34
9: naga::back::spv::writer::<impl naga::back::spv::Writer>::write
at ./src/back/spv/writer.rs:1267:9
10: naga::back::spv::write_vec
at ./src/back/spv/mod.rs:458:5
11: naga::run
at ./cli/src/main.rs:311:27
12: naga::main
at ./cli/src/main.rs:154:21
13: core::ops::function::FnOnce::call_once
at /rustc/a178d0322ce20e33eac124758e837cbd80a6f633/library/core/src/ops/function.rs:227:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
```
|
2021-08-28T06:46:03Z
|
0.6
|
2021-09-01T21:55:46Z
|
2e7d629aefe6857ade4f96fe2c3dc1a09f0fa4db
|
[
"convert_wgsl"
] |
[
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_unique",
"front::glsl::parser_tests::constants",
"front::glsl::constants::tests::cast",
"front::glsl::parser_tests::control_flow",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"front::glsl::parser_tests::declarations",
"front::glsl::parser_tests::function_overloading",
"back::spv::layout::test_physical_layout_in_words",
"back::msl::test_error_size",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::access",
"back::spv::writer::test_write_physical_layout",
"back::msl::writer::test_stack_size",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::constants::tests::unary_op",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_comment",
"front::spv::test::parse",
"front::glsl::parser_tests::structs",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::expressions",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_hex_floats",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_hex_ints",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_decimal_ints",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_decimal_floats",
"front::glsl::parser_tests::swizzles",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::type_inner_tests::to_wgsl",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_texture_load",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_type_inference",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_switch",
"proc::test_matrix_size",
"front::wgsl::tests::parse_type_cast",
"convert_spv_inverse_hyperbolic_trig_functions",
"convert_spv_pointer_access",
"convert_spv_shadow",
"convert_spv_quad_vert",
"convert_glsl_folder",
"sampler1d",
"cube_array",
"sample_rate_shading",
"geometry",
"storage1d",
"image_queries",
"bad_texture",
"invalid_integer",
"invalid_structs",
"invalid_texture_sample_type",
"bad_texture_sample_type",
"function_without_identifier",
"let_type_mismatch",
"invalid_functions",
"bad_for_initializer",
"missing_bindings",
"negative_index",
"invalid_access",
"bad_type_cast",
"local_var_missing_type",
"invalid_arrays",
"struct_member_zero_size",
"unknown_attribute",
"unknown_built_in",
"unknown_access",
"unknown_conservative_depth",
"inconsistent_binding",
"unknown_local_function",
"unknown_shader_stage",
"struct_member_zero_align",
"local_var_type_mismatch",
"invalid_local_vars",
"unknown_scalar_type",
"invalid_float",
"unknown_ident",
"unknown_storage_class",
"unknown_identifier",
"unknown_storage_format",
"unknown_type",
"zero_array_stride",
"valid_access",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 17)",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 26)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
gfx-rs/naga
| 1,292
|
gfx-rs__naga-1292
|
[
"1266"
] |
7a45d73465d90a11fbfdb6892f5a15c050c6d3bb
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,20 @@
# Change Log
+## v0.6.1 (2021-08-24)
+ - HLSL-out fixes:
+ - array arguments
+ - pointers to array arguments
+ - switch statement
+ - rewritten interface matching
+ - SPV-in fixes:
+ - array storage texture stores
+ - tracking sampling across function parameters
+ - updated petgraph dependencies
+ - MSL-out:
+ - gradient sampling
+ - GLSL-out:
+ - modulo operator on floats
+
## v0.6 (2021-08-18)
- development release for wgpu-0.10
- API:
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "naga"
-version = "0.6.0"
+version = "0.6.1"
authors = ["Naga Developers"]
edition = "2018"
description = "Shader translation infrastructure"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -15,8 +15,8 @@ resolver = "2"
all-features = true
[dependencies]
-# bitflags 1.3 requires Rust-1.46
-bitflags = "~1.2"
+# MSRV warning: bitflags 1.3 requires Rust-1.46
+bitflags = "1"
bit-set = "0.5"
codespan-reporting = { version = "0.11.0", optional = true }
fxhash = "0.2"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -25,8 +25,8 @@ num-traits = "0.2"
spirv = { version = "0.2", optional = true }
thiserror = "1.0.21"
serde = { version = "1.0", features = ["derive"], optional = true }
-petgraph = { version ="0.5", optional = true }
-rose_tree = { version ="0.2", optional = true }
+petgraph = { version ="0.6", optional = true }
+rose_tree = { version ="0.3", optional = true }
pp-rs = { version = "0.2.1", optional = true }
[features]
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -66,3 +66,15 @@ make validate-dot # for dot files, requires GraphViz installed
make validate-wgsl # for WGSL shaders
make validate-hlsl # for HLSL shaders. Note: this Make target makes use of the "sh" shell. This is not the default shell in Windows.
```
+
+## MSRV
+
+The `naga` codebase's MSRV is 1.43. However some newer versions of our dependencies have newer MSRVs than that. Here are a list of all known MSRV breaking dependencies and the versions that hold to MSRV.
+
+- `bitflags`: `>1.3` have an MSRV of 1.46. `<=1.2` has an MSRV of 1.43 or earlier.
+
+If you want to use `naga` with `1.43` add the following to your Cargo.toml dependency list even if you don't use bitflags yourself:
+
+```toml
+bitflags = "<1.3"
+```
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1441,11 +1441,6 @@ impl<'a, W: Write> Writer<'a, W> {
for sta in case.body.iter() {
self.write_stmt(sta, ctx, indent + 2)?;
}
-
- // Write `break;` if the block isn't fallthrough
- if !case.fall_through {
- writeln!(self.out, "{}break;", INDENT.repeat(indent + 2))?;
- }
}
// Only write the default block if the block isn't empty
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -2117,13 +2112,13 @@ impl<'a, W: Write> Writer<'a, W> {
Expression::Binary { op, left, right } => {
// Holds `Some(function_name)` if the binary operation is
// implemented as a function call
- use crate::BinaryOperator as Bo;
+ use crate::{BinaryOperator as Bo, ScalarKind as Sk, TypeInner as Ti};
- let function = if let (&TypeInner::Vector { .. }, &TypeInner::Vector { .. }) = (
- ctx.info[left].ty.inner_with(&self.module.types),
- ctx.info[right].ty.inner_with(&self.module.types),
- ) {
- match op {
+ let left_inner = ctx.info[left].ty.inner_with(&self.module.types);
+ let right_inner = ctx.info[right].ty.inner_with(&self.module.types);
+
+ let function = match (left_inner, right_inner) {
+ (&Ti::Vector { .. }, &Ti::Vector { .. }) => match op {
Bo::Less => Some("lessThan"),
Bo::LessEqual => Some("lessThanEqual"),
Bo::Greater => Some("greaterThan"),
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -2131,9 +2126,14 @@ impl<'a, W: Write> Writer<'a, W> {
Bo::Equal => Some("equal"),
Bo::NotEqual => Some("notEqual"),
_ => None,
- }
- } else {
- None
+ },
+ _ => match (left_inner.scalar_kind(), right_inner.scalar_kind()) {
+ (Some(Sk::Float), _) | (_, Some(Sk::Float)) => match op {
+ Bo::Modulo => Some("mod"),
+ _ => None,
+ },
+ _ => None,
+ },
};
write!(self.out, "{}(", function.unwrap_or(""))?;
diff --git a/src/back/hlsl/mod.rs b/src/back/hlsl/mod.rs
--- a/src/back/hlsl/mod.rs
+++ b/src/back/hlsl/mod.rs
@@ -164,8 +164,8 @@ pub struct Writer<'a, W> {
namer: proc::Namer,
/// HLSL backend options
options: &'a Options,
- /// Information about entry point arguments wrapped into structure
- ep_inputs: Vec<Option<writer::EntryPointBinding>>,
+ /// Information about entry point arguments and result types.
+ entry_point_io: Vec<writer::EntryPointInterface>,
/// Set of expressions that have associated temporary variables
named_expressions: crate::NamedExpressions,
wrapped_array_lengths: crate::FastHashSet<help::WrappedArrayLength>,
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -17,20 +17,36 @@ const SPECIAL_BASE_VERTEX: &str = "base_vertex";
const SPECIAL_BASE_INSTANCE: &str = "base_instance";
const SPECIAL_OTHER: &str = "other";
+struct EpStructMember {
+ name: String,
+ ty: Handle<crate::Type>,
+ // technically, this should always be `Some`
+ binding: Option<crate::Binding>,
+ index: u32,
+}
+
/// Structure contains information required for generating
/// wrapped structure of all entry points arguments
-pub(super) struct EntryPointBinding {
+struct EntryPointBinding {
+ /// Name of the fake EP argument that contains the struct
+ /// with all the flattened input data.
+ arg_name: String,
/// Generated structure name
- name: String,
+ ty_name: String,
/// Members of generated structure
members: Vec<EpStructMember>,
}
-struct EpStructMember {
- name: String,
- ty: Handle<crate::Type>,
- binding: Option<crate::Binding>,
- index: usize,
+pub(super) struct EntryPointInterface {
+ /// If `Some`, the input of an entry point is gathered in a special
+ /// struct with members sorted by binding.
+ /// The `EntryPointBinding::members` array is sorted by index,
+ /// so that we can walk it in `write_ep_arguments_initialization`.
+ input: Option<EntryPointBinding>,
+ /// If `Some`, the output of an entry point is flattened.
+ /// The `EntryPointBinding::members` array is sorted by binding,
+ /// So that we can walk it in `Statement::Return` handler.
+ output: Option<EntryPointBinding>,
}
#[derive(Clone, Eq, PartialEq, PartialOrd, Ord)]
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -50,19 +66,6 @@ impl InterfaceKey {
}
}
-// Returns true for structures that need their members permuted,
-// so that first come the user-defined varyings
-// in ascending locations, and then built-ins. This allows VS and FS
-// interfaces to match with regards to order.
-fn needs_permutation(members: &[crate::StructMember]) -> bool {
- //Note: this is a bit of a hack. We need to re-order the output fields, but we can only do this
- // for non-layouted structures. It may be possible for an WGSL program can use the same struct
- // for both host sharing and the interface. This case isn't supported here.
- let has_layout = members.iter().any(|m| m.offset != 0);
- let has_binding = members.iter().any(|m| m.binding.is_some());
- has_binding && !has_layout
-}
-
#[derive(Copy, Clone, PartialEq)]
enum Io {
Input,
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -76,7 +79,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
names: crate::FastHashMap::default(),
namer: proc::Namer::default(),
options,
- ep_inputs: Vec::new(),
+ entry_point_io: Vec::new(),
named_expressions: crate::NamedExpressions::default(),
wrapped_array_lengths: crate::FastHashSet::default(),
wrapped_image_queries: crate::FastHashSet::default(),
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -88,7 +91,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
self.names.clear();
self.namer
.reset(module, super::keywords::RESERVED, &[], &mut self.names);
- self.ep_inputs.clear();
+ self.entry_point_io.clear();
self.named_expressions.clear();
self.wrapped_array_lengths.clear();
self.wrapped_image_queries.clear();
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -199,8 +202,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
// Write all entry points wrapped structs
for ep in module.entry_points.iter() {
- let ep_input = self.write_ep_input_struct(module, &ep.function, ep.stage, &ep.name)?;
- self.ep_inputs.push(ep_input);
+ let ep_io = self.write_ep_interface(module, &ep.function, ep.stage, &ep.name)?;
+ self.entry_point_io.push(ep_io);
}
// Write all regular functions
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -306,6 +309,8 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
Ok(super::ReflectionInfo { entry_point_names })
}
+ //TODO: we could force fragment outputs to always go through `entry_point_io.output` path
+ // if they are struct, so that the `stage` argument here could be omitted.
fn write_semantic(
&mut self,
binding: &crate::Binding,
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -328,67 +333,209 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
Ok(())
}
+ fn write_interface_struct(
+ &mut self,
+ module: &Module,
+ shader_stage: (ShaderStage, Io),
+ struct_name: String,
+ mut members: Vec<EpStructMember>,
+ ) -> Result<EntryPointBinding, Error> {
+ // Sort the members so that first come the user-defined varyings
+ // in ascending locations, and then built-ins. This allows VS and FS
+ // interfaces to match with regards to order.
+ members.sort_by_key(|m| InterfaceKey::new(m.binding.as_ref()));
+
+ write!(self.out, "struct {}", struct_name)?;
+ writeln!(self.out, " {{")?;
+ for m in members.iter() {
+ write!(self.out, "{}", back::INDENT)?;
+ self.write_type(module, m.ty)?;
+ write!(self.out, " {}", &m.name)?;
+ if let Some(ref binding) = m.binding {
+ self.write_semantic(binding, Some(shader_stage))?;
+ }
+ writeln!(self.out, ";")?;
+ }
+ writeln!(self.out, "}};")?;
+ writeln!(self.out)?;
+
+ match shader_stage.1 {
+ Io::Input => {
+ // bring back the original order
+ members.sort_by_key(|m| m.index);
+ }
+ Io::Output => {
+ // keep it sorted by binding
+ }
+ }
+
+ Ok(EntryPointBinding {
+ arg_name: self.namer.call_unique(struct_name.to_lowercase().as_str()),
+ ty_name: struct_name,
+ members,
+ })
+ }
+
+ /// Flatten all entry point arguments into a single struct.
+ /// This is needed since we need to re-order them: first placing user locations,
+ /// then built-ins.
fn write_ep_input_struct(
&mut self,
module: &Module,
func: &crate::Function,
stage: ShaderStage,
entry_point_name: &str,
- ) -> Result<Option<EntryPointBinding>, Error> {
- Ok(if !func.arguments.is_empty() {
- let struct_name_prefix = match stage {
- ShaderStage::Vertex => "VertexInput",
- ShaderStage::Fragment => "FragmentInput",
- ShaderStage::Compute => "ComputeInput",
- };
- let struct_name = format!("{}_{}", struct_name_prefix, entry_point_name);
-
- let mut members = Vec::with_capacity(func.arguments.len());
- for (index, arg) in func.arguments.iter().enumerate() {
- let member_name = if let Some(ref name) = arg.name {
- name
- } else {
- "member"
- };
- members.push(EpStructMember {
- name: self.namer.call_unique(member_name),
- ty: arg.ty,
- binding: arg.binding.clone(),
- index,
- });
+ ) -> Result<EntryPointBinding, Error> {
+ let struct_name = format!("{:?}Input_{}", stage, entry_point_name);
+
+ let mut fake_members = Vec::new();
+ for arg in func.arguments.iter() {
+ match module.types[arg.ty].inner {
+ TypeInner::Struct { ref members, .. } => {
+ for member in members.iter() {
+ let member_name = if let Some(ref name) = member.name {
+ name
+ } else {
+ "member"
+ };
+ let index = fake_members.len() as u32;
+ fake_members.push(EpStructMember {
+ name: self.namer.call_unique(member_name),
+ ty: member.ty,
+ binding: member.binding.clone(),
+ index,
+ });
+ }
+ }
+ _ => {
+ let member_name = if let Some(ref name) = arg.name {
+ name
+ } else {
+ "member"
+ };
+ let index = fake_members.len() as u32;
+ fake_members.push(EpStructMember {
+ name: self.namer.call_unique(member_name),
+ ty: arg.ty,
+ binding: arg.binding.clone(),
+ index,
+ });
+ }
}
+ }
- // Sort the members so that first come the user-defined varyings
- // in ascending locations, and then built-ins. This allows VS and FS
- // interfaces to match with regards to order.
- members.sort_by_key(|m| InterfaceKey::new(m.binding.as_ref()));
+ self.write_interface_struct(module, (stage, Io::Input), struct_name, fake_members)
+ }
- write!(self.out, "struct {}", &struct_name)?;
- writeln!(self.out, " {{")?;
- for m in members.iter() {
- write!(self.out, "{}", back::INDENT)?;
- self.write_type(module, m.ty)?;
- write!(self.out, " {}", &m.name)?;
- if let Some(ref binding) = m.binding {
- self.write_semantic(binding, Some((stage, Io::Input)))?;
- }
- writeln!(self.out, ";")?;
+ /// Flatten all entry point results into a single struct.
+ /// This is needed since we need to re-order them: first placing user locations,
+ /// then built-ins.
+ fn write_ep_output_struct(
+ &mut self,
+ module: &Module,
+ result: &crate::FunctionResult,
+ stage: ShaderStage,
+ entry_point_name: &str,
+ ) -> Result<EntryPointBinding, Error> {
+ let struct_name = format!("{:?}Output_{}", stage, entry_point_name);
+
+ let mut fake_members = Vec::new();
+ let empty = [];
+ let members = match module.types[result.ty].inner {
+ TypeInner::Struct { ref members, .. } => members,
+ ref other => {
+ log::error!("Unexpected {:?} output type without a binding", other);
+ &empty[..]
}
- writeln!(self.out, "}};")?;
- writeln!(self.out)?;
+ };
- // now bring back the old order
- members.sort_by_key(|m| m.index);
+ for member in members.iter() {
+ let member_name = if let Some(ref name) = member.name {
+ name
+ } else {
+ "member"
+ };
+ let index = fake_members.len() as u32;
+ fake_members.push(EpStructMember {
+ name: self.namer.call_unique(member_name),
+ ty: member.ty,
+ binding: member.binding.clone(),
+ index,
+ });
+ }
- Some(EntryPointBinding {
- name: struct_name,
- members,
- })
- } else {
- None
+ self.write_interface_struct(module, (stage, Io::Output), struct_name, fake_members)
+ }
+
+ /// Writes special interface structures for an entry point. The special structures have
+ /// all the fields flattened into them and sorted by binding. They are only needed for
+ /// VS outputs and FS inputs, so that these interfaces match.
+ fn write_ep_interface(
+ &mut self,
+ module: &Module,
+ func: &crate::Function,
+ stage: ShaderStage,
+ ep_name: &str,
+ ) -> Result<EntryPointInterface, Error> {
+ Ok(EntryPointInterface {
+ input: if !func.arguments.is_empty() && stage == ShaderStage::Fragment {
+ Some(self.write_ep_input_struct(module, func, stage, ep_name)?)
+ } else {
+ None
+ },
+ output: match func.result {
+ Some(ref fr) if fr.binding.is_none() && stage == ShaderStage::Vertex => {
+ Some(self.write_ep_output_struct(module, fr, stage, ep_name)?)
+ }
+ _ => None,
+ },
})
}
+ /// Write an entry point preface that initializes the arguments as specified in IR.
+ fn write_ep_arguments_initialization(
+ &mut self,
+ module: &Module,
+ func: &crate::Function,
+ ep_index: u16,
+ ) -> BackendResult {
+ let ep_input = match self.entry_point_io[ep_index as usize].input.take() {
+ Some(ep_input) => ep_input,
+ None => return Ok(()),
+ };
+ let mut fake_iter = ep_input.members.iter();
+ for (arg_index, arg) in func.arguments.iter().enumerate() {
+ write!(self.out, "{}", back::INDENT)?;
+ self.write_type(module, arg.ty)?;
+ let arg_name = &self.names[&NameKey::EntryPointArgument(ep_index, arg_index as u32)];
+ write!(self.out, " {}", arg_name)?;
+ match module.types[arg.ty].inner {
+ TypeInner::Array { size, .. } => {
+ self.write_array_size(module, size)?;
+ let fake_member = fake_iter.next().unwrap();
+ writeln!(self.out, " = {}.{};", ep_input.arg_name, fake_member.name)?;
+ }
+ TypeInner::Struct { ref members, .. } => {
+ write!(self.out, " = {{ ")?;
+ for index in 0..members.len() {
+ if index != 0 {
+ write!(self.out, ", ")?;
+ }
+ let fake_member = fake_iter.next().unwrap();
+ write!(self.out, "{}.{}", ep_input.arg_name, fake_member.name)?;
+ }
+ writeln!(self.out, " }};")?;
+ }
+ _ => {
+ let fake_member = fake_iter.next().unwrap();
+ writeln!(self.out, " = {}.{};", ep_input.arg_name, fake_member.name)?;
+ }
+ }
+ }
+ assert!(fake_iter.next().is_none());
+ Ok(())
+ }
+
/// Helper method used to write global variables
/// # Notes
/// Always adds a newline
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -571,28 +718,18 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
module: &Module,
handle: Handle<crate::Type>,
_block: bool,
- original_members: &[crate::StructMember],
+ members: &[crate::StructMember],
shader_stage: Option<(ShaderStage, Io)>,
) -> BackendResult {
// Write struct name
- write!(self.out, "struct {}", self.names[&NameKey::Type(handle)])?;
- writeln!(self.out, " {{")?;
-
- //TODO: avoid heap allocation
- let mut members = original_members
- .iter()
- .enumerate()
- .map(|(index, m)| (index, m.ty, m.binding.clone()))
- .collect::<Vec<_>>();
- if needs_permutation(original_members) {
- members.sort_by_key(|&(_, _, ref binding)| InterfaceKey::new(binding.as_ref()));
- }
+ let struct_name = &self.names[&NameKey::Type(handle)];
+ writeln!(self.out, "struct {} {{", struct_name)?;
- for (index, ty, binding) in members {
+ for (index, member) in members.iter().enumerate() {
// The indentation is only for readability
write!(self.out, "{}", back::INDENT)?;
- match module.types[ty].inner {
+ match module.types[member.ty].inner {
TypeInner::Array {
base,
size,
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -629,7 +766,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
interpolation,
sampling,
..
- }) = binding
+ }) = member.binding
{
if let Some(interpolation) = interpolation {
write!(self.out, "{} ", interpolation.to_hlsl_str())?
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -642,12 +779,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
}
}
- if let TypeInner::Matrix { .. } = module.types[ty].inner {
+ if let TypeInner::Matrix { .. } = module.types[member.ty].inner {
write!(self.out, "row_major ")?;
}
// Write the member type and name
- self.write_type(module, ty)?;
+ self.write_type(module, member.ty)?;
write!(
self.out,
" {}",
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -656,7 +793,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
}
}
- if let Some(ref binding) = binding {
+ if let Some(ref binding) = member.binding {
self.write_semantic(binding, shader_stage)?;
};
writeln!(self.out, ";")?;
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -748,7 +885,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
Ok(())
}
- /// Helper method used to write structs
+ /// Helper method used to write functions
/// # Notes
/// Ends in a newline
fn write_function(
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -760,7 +897,18 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
) -> BackendResult {
// Function Declaration Syntax - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-function-syntax
if let Some(ref result) = func.result {
- self.write_type(module, result.ty)?;
+ match func_ctx.ty {
+ back::FunctionType::Function(_) => {
+ self.write_type(module, result.ty)?;
+ }
+ back::FunctionType::EntryPoint(index) => {
+ if let Some(ref ep_output) = self.entry_point_io[index as usize].output {
+ write!(self.out, "{}", ep_output.ty_name)?;
+ } else {
+ self.write_type(module, result.ty)?;
+ }
+ }
+ }
} else {
write!(self.out, "void")?;
}
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -772,6 +920,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
match func_ctx.ty {
back::FunctionType::Function(handle) => {
for (index, arg) in func.arguments.iter().enumerate() {
+ if index != 0 {
+ write!(self.out, ", ")?;
+ }
// Write argument type
let arg_ty = match module.types[arg.ty].inner {
// pointers in function arguments are expected and resolve to `inout`
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -789,31 +940,33 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
// Write argument name. Space is important.
write!(self.out, " {}", argument_name)?;
- if index < func.arguments.len() - 1 {
- // Add a separator between args
- write!(self.out, ", ")?;
+ if let TypeInner::Array { size, .. } = module.types[arg.ty].inner {
+ self.write_array_size(module, size)?;
}
}
}
- back::FunctionType::EntryPoint(index) => {
- // EntryPoint arguments wrapped into structure
- // We need to ensure that entry points have arguments too.
- // For the case when we working with multiple entry points
- // for example vertex shader with arguments and fragment shader without arguments.
- if !self.ep_inputs.is_empty()
- && !module.entry_points[index as usize]
- .function
- .arguments
- .is_empty()
- {
- if let Some(ref ep_input) = self.ep_inputs[index as usize] {
- write!(
- self.out,
- "{} {}",
- ep_input.name,
- self.namer
- .call_unique(ep_input.name.to_lowercase().as_str())
- )?;
+ back::FunctionType::EntryPoint(ep_index) => {
+ if let Some(ref ep_input) = self.entry_point_io[ep_index as usize].input {
+ write!(self.out, "{} {}", ep_input.ty_name, ep_input.arg_name,)?;
+ } else {
+ let stage = module.entry_points[ep_index as usize].stage;
+ for (index, arg) in func.arguments.iter().enumerate() {
+ if index != 0 {
+ write!(self.out, ", ")?;
+ }
+ self.write_type(module, arg.ty)?;
+
+ let argument_name =
+ &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)];
+
+ write!(self.out, " {}", argument_name)?;
+ if let TypeInner::Array { size, .. } = module.types[arg.ty].inner {
+ self.write_array_size(module, size)?;
+ }
+
+ if let Some(ref binding) = arg.binding {
+ self.write_semantic(binding, Some((stage, Io::Input)))?;
+ }
}
}
}
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -822,21 +975,25 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
write!(self.out, ")")?;
// Write semantic if it present
- let stage = match func_ctx.ty {
- back::FunctionType::EntryPoint(index) => {
- Some(module.entry_points[index as usize].stage)
- }
- _ => None,
- };
- if let Some(ref result) = func.result {
- if let Some(ref binding) = result.binding {
- self.write_semantic(binding, stage.map(|s| (s, Io::Output)))?;
+ if let back::FunctionType::EntryPoint(index) = func_ctx.ty {
+ let stage = module.entry_points[index as usize].stage;
+ if let Some(crate::FunctionResult {
+ binding: Some(ref binding),
+ ..
+ }) = func.result
+ {
+ self.write_semantic(binding, Some((stage, Io::Output)))?;
}
}
// Function body start
writeln!(self.out)?;
writeln!(self.out, "{{")?;
+
+ if let back::FunctionType::EntryPoint(index) = func_ctx.ty {
+ self.write_ep_arguments_initialization(module, func, index)?;
+ }
+
// Write function local variables
for (handle, local) in func.local_variables.iter() {
// Write indentation (only for readability)
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -979,22 +1136,47 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
// We can safery unwrap here, since we now we working with struct
let ty = base_ty_res.handle().unwrap();
let struct_name = &self.names[&NameKey::Type(ty)];
- let variable_name = self.namer.call_unique(struct_name.as_str()).to_lowercase();
+ let variable_name = self.namer.call(&struct_name.to_lowercase());
write!(
self.out,
"{}const {} {} = ",
INDENT.repeat(indent),
struct_name,
- variable_name
+ variable_name,
)?;
self.write_expr(module, expr, func_ctx)?;
writeln!(self.out, ";")?;
- writeln!(
- self.out,
- "{}return {};",
- INDENT.repeat(indent),
- variable_name
- )?;
+
+ // for entry point returns, we may need to reshuffle the outputs into a different struct
+ let ep_output = match func_ctx.ty {
+ back::FunctionType::Function(_) => None,
+ back::FunctionType::EntryPoint(index) => {
+ self.entry_point_io[index as usize].output.as_ref()
+ }
+ };
+ let final_name = match ep_output {
+ Some(ep_output) => {
+ let final_name = self.namer.call_unique(&variable_name);
+ write!(
+ self.out,
+ "{}const {} {} = {{ ",
+ INDENT.repeat(indent),
+ ep_output.ty_name,
+ final_name,
+ )?;
+ for (index, m) in ep_output.members.iter().enumerate() {
+ if index != 0 {
+ write!(self.out, ", ")?;
+ }
+ let member_name = &self.names[&NameKey::StructMember(ty, m.index)];
+ write!(self.out, "{}.{}", variable_name, member_name)?;
+ }
+ writeln!(self.out, " }};")?;
+ final_name
+ }
+ None => variable_name,
+ };
+ writeln!(self.out, "{}return {};", INDENT.repeat(indent), final_name)?;
} else {
write!(self.out, "{}return ", INDENT.repeat(indent))?;
self.write_expr(module, expr, func_ctx)?;
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -1201,8 +1383,61 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
self.temp_access_chain = chain;
self.named_expressions.insert(result, res_name);
}
- Statement::Switch { .. } => {
- return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt)))
+ Statement::Switch {
+ selector,
+ ref cases,
+ ref default,
+ } => {
+ // Start the switch
+ write!(self.out, "{}", INDENT.repeat(indent))?;
+ write!(self.out, "switch(")?;
+ self.write_expr(module, selector, func_ctx)?;
+ writeln!(self.out, ") {{")?;
+
+ // Write all cases
+ let indent_str_1 = INDENT.repeat(indent + 1);
+ let indent_str_2 = INDENT.repeat(indent + 2);
+
+ for case in cases {
+ writeln!(self.out, "{}case {}: {{", &indent_str_1, case.value)?;
+
+ if case.fall_through {
+ // Generate each fallthrough case statement in a new block. This is done to
+ // prevent symbol collision of variables declared in these cases statements.
+ writeln!(self.out, "{}/* fallthrough */", &indent_str_2)?;
+ writeln!(self.out, "{}{{", &indent_str_2)?;
+ }
+ for sta in case.body.iter() {
+ self.write_stmt(
+ module,
+ sta,
+ func_ctx,
+ indent + 2 + usize::from(case.fall_through),
+ )?;
+ }
+
+ if case.fall_through {
+ writeln!(self.out, "{}}}", &indent_str_2)?;
+ } else {
+ writeln!(self.out, "{}break;", &indent_str_2)?;
+ }
+
+ writeln!(self.out, "{}}}", &indent_str_1)?;
+ }
+
+ // Only write the default block if the block isn't empty
+ // Writing default without a block is valid but it's more readable this way
+ if !default.is_empty() {
+ writeln!(self.out, "{}default: {{", &indent_str_1)?;
+
+ for sta in default {
+ self.write_stmt(module, sta, func_ctx, indent + 2)?;
+ }
+
+ writeln!(self.out, "{}}}", &indent_str_1)?;
+ }
+
+ writeln!(self.out, "{}}}", INDENT.repeat(indent))?
}
}
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -1269,24 +1504,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
match *expression {
Expression::Constant(constant) => self.write_constant(module, constant)?,
Expression::Compose { ty, ref components } => {
- let (braces_init, permutation) = match module.types[ty].inner {
- TypeInner::Struct { ref members, .. } => {
- let permutation = if needs_permutation(members) {
- //TODO: avoid heap allocation. We can pre-compute this at the module leve.
- let mut permutation = members
- .iter()
- .enumerate()
- .map(|(index, m)| (index, InterfaceKey::new(m.binding.as_ref())))
- .collect::<Vec<_>>();
- permutation.sort_by_key(|&(_, ref key)| key.clone());
- Some(permutation)
- } else {
- None
- };
- (true, permutation)
- }
- TypeInner::Array { .. } => (true, None),
- _ => (false, None),
+ let braces_init = match module.types[ty].inner {
+ TypeInner::Struct { .. } | TypeInner::Array { .. } => true,
+ _ => false,
};
if braces_init {
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -1296,16 +1516,12 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
write!(self.out, "(")?;
}
- for index in 0..components.len() {
+ for (index, &component) in components.iter().enumerate() {
if index != 0 {
// The leading space is for readability only
write!(self.out, ", ")?;
}
- let comp_index = match permutation {
- Some(ref perm) => perm[index].0,
- None => index,
- };
- self.write_expr(module, components[comp_index], func_ctx)?;
+ self.write_expr(module, component, func_ctx)?;
}
if braces_init {
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -1400,24 +1616,14 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
}
}
Expression::FunctionArgument(pos) => {
- match func_ctx.ty {
- back::FunctionType::Function(handle) => {
- let name = &self.names[&NameKey::FunctionArgument(handle, pos)];
- write!(self.out, "{}", name)?;
- }
+ let key = match func_ctx.ty {
+ back::FunctionType::Function(handle) => NameKey::FunctionArgument(handle, pos),
back::FunctionType::EntryPoint(index) => {
- // EntryPoint arguments wrapped into structure
- // We can safery unwrap here, because if we write function arguments it means, that ep_input struct already exists
- let ep_input = self.ep_inputs[index as usize].as_ref().unwrap();
- let member_name = &ep_input.members[pos as usize].name;
- write!(
- self.out,
- "{}.{}",
- &ep_input.name.to_lowercase(),
- member_name
- )?
+ NameKey::EntryPointArgument(index, pos)
}
};
+ let name = &self.names[&key];
+ write!(self.out, "{}", name)?;
}
Expression::ImageSample {
image,
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -1858,9 +2064,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
components: &[Handle<crate::Constant>],
) -> BackendResult {
let (open_b, close_b) = match module.types[ty].inner {
- TypeInner::Struct { .. } => ("{ ", " }"),
+ TypeInner::Array { .. } | TypeInner::Struct { .. } => ("{ ", " }"),
_ => {
- // We should write type only for non struct constants
+ // We should write type only for non struct/array constants
self.write_type(module, ty)?;
("(", ")")
}
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -610,7 +610,7 @@ impl<W: Write> Writer<W> {
write!(self.out, ")")?;
}
crate::SampleLevel::Gradient { x, y } => {
- write!(self.out, ", {}::gradient(", NAMESPACE)?;
+ write!(self.out, ", {}::gradient2d(", NAMESPACE)?;
self.put_expression(x, context, true)?;
write!(self.out, ", ")?;
self.put_expression(y, context, true)?;
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -1,6 +1,6 @@
use crate::arena::{Arena, Handle};
-use super::{flow::*, Error, FunctionInfo, Instruction, LookupExpression, LookupHelper as _};
+use super::{flow::*, Error, Instruction, LookupExpression, LookupHelper as _};
use crate::front::Emitter;
pub type BlockId = u32;
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -142,10 +142,8 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
// Read body
self.function_call_graph.add_node(fun_id);
let mut flow_graph = FlowGraph::new();
-
- let mut function_info = FunctionInfo {
- parameters_sampling: vec![super::image::SamplingFlags::empty(); fun.arguments.len()],
- };
+ let mut parameters_sampling =
+ vec![super::image::SamplingFlags::empty(); fun.arguments.len()];
// Scan the blocks and add them as nodes
loop {
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -166,7 +164,7 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
&module.types,
&module.global_variables,
&fun.arguments,
- &mut function_info,
+ &mut parameters_sampling,
)?;
flow_graph.add_node(node);
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -200,8 +198,14 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
// done
let fun_handle = module.functions.append(fun, self.span_from_with_op(start));
- self.lookup_function.insert(fun_id, fun_handle);
- self.function_info.push(function_info);
+ self.lookup_function.insert(
+ fun_id,
+ super::LookupFunction {
+ handle: fun_handle,
+ parameters_sampling,
+ },
+ );
+
if let Some(ep) = self.lookup_entry_point.remove(&fun_id) {
// create a wrapping function
let mut function = crate::Function {
diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs
--- a/src/front/spv/image.rs
+++ b/src/front/spv/image.rs
@@ -3,7 +3,7 @@ use crate::{
FunctionArgument,
};
-use super::{Error, FunctionInfo, LookupExpression, LookupHelper as _};
+use super::{Error, LookupExpression, LookupHelper as _};
#[derive(Clone, Debug)]
pub(super) struct LookupSampledImage {
diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs
--- a/src/front/spv/image.rs
+++ b/src/front/spv/image.rs
@@ -415,7 +415,7 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
global_arena: &Arena<crate::GlobalVariable>,
arguments: &[FunctionArgument],
expressions: &mut Arena<crate::Expression>,
- function_info: &mut FunctionInfo,
+ parameters_sampling: &mut [SamplingFlags],
) -> Result<(), Error> {
let start = self.data_offset;
let result_type_id = self.next()?;
diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs
--- a/src/front/spv/image.rs
+++ b/src/front/spv/image.rs
@@ -513,9 +513,7 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
global_arena[handle].ty
}
crate::Expression::FunctionArgument(i) => {
- let flags = &mut function_info.parameters_sampling[i as usize];
- *flags |= sampling_bit;
-
+ parameters_sampling[i as usize] |= sampling_bit;
arguments[i as usize].ty
}
ref other => return Err(Error::InvalidGlobalVar(other.clone())),
diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs
--- a/src/front/spv/image.rs
+++ b/src/front/spv/image.rs
@@ -525,8 +523,7 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
*self.handle_sampling.get_mut(&handle).unwrap() |= sampling_bit
}
crate::Expression::FunctionArgument(i) => {
- let flags = &mut function_info.parameters_sampling[i as usize];
- *flags |= sampling_bit;
+ parameters_sampling[i as usize] |= sampling_bit;
}
ref other => return Err(Error::InvalidGlobalVar(other.clone())),
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -296,6 +296,11 @@ struct LookupFunctionType {
return_type_id: spirv::Word,
}
+struct LookupFunction {
+ handle: Handle<crate::Function>,
+ parameters_sampling: Vec<image::SamplingFlags>,
+}
+
#[derive(Debug)]
struct EntryPoint {
stage: crate::ShaderStage,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -387,10 +392,6 @@ impl Default for Options {
}
}
-struct FunctionInfo {
- parameters_sampling: Vec<image::SamplingFlags>,
-}
-
pub struct Parser<I> {
data: I,
data_offset: usize,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -413,7 +414,7 @@ pub struct Parser<I> {
lookup_load_override: FastHashMap<spirv::Word, LookupLoadOverride>,
lookup_sampled_image: FastHashMap<spirv::Word, image::LookupSampledImage>,
lookup_function_type: FastHashMap<spirv::Word, LookupFunctionType>,
- lookup_function: FastHashMap<spirv::Word, Handle<crate::Function>>,
+ lookup_function: FastHashMap<spirv::Word, LookupFunction>,
lookup_entry_point: FastHashMap<spirv::Word, EntryPoint>,
//Note: each `OpFunctionCall` gets a single entry here, indexed by the
// dummy `Handle<crate::Function>` of the call site.
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -426,7 +427,6 @@ pub struct Parser<I> {
options: Options,
index_constants: Vec<Handle<crate::Constant>>,
index_constant_expressions: Vec<Handle<crate::Expression>>,
- function_info: Vec<FunctionInfo>,
}
impl<I: Iterator<Item = u32>> Parser<I> {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -459,7 +459,6 @@ impl<I: Iterator<Item = u32>> Parser<I> {
options: options.clone(),
index_constants: Vec::new(),
index_constant_expressions: Vec::new(),
- function_info: Vec::new(),
}
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -852,7 +851,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
type_arena: &Arena<crate::Type>,
global_arena: &Arena<crate::GlobalVariable>,
arguments: &[crate::FunctionArgument],
- function_info: &mut FunctionInfo,
+ parmeter_sampling: &mut [image::SamplingFlags],
) -> Result<ControlFlowNode, Error> {
let mut block = crate::Block::new();
let mut phis = Vec::new();
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1617,7 +1616,6 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::ImageWrite => {
let extra = inst.expect_at_least(4)?;
- block.extend(emitter.finish(expressions));
let stmt = self.parse_image_write(
extra,
type_arena,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1625,6 +1623,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
arguments,
expressions,
)?;
+ block.extend(emitter.finish(expressions));
block.push(stmt, span);
emitter.start(expressions);
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1645,7 +1644,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
global_arena,
arguments,
expressions,
- function_info,
+ parmeter_sampling,
)?;
}
Op::ImageSampleProjImplicitLod | Op::ImageSampleProjExplicitLod => {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1661,7 +1660,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
global_arena,
arguments,
expressions,
- function_info,
+ parmeter_sampling,
)?;
}
Op::ImageSampleDrefImplicitLod | Op::ImageSampleDrefExplicitLod => {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1677,7 +1676,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
global_arena,
arguments,
expressions,
- function_info,
+ parmeter_sampling,
)?;
}
Op::ImageSampleProjDrefImplicitLod | Op::ImageSampleProjDrefExplicitLod => {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1693,7 +1692,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
global_arena,
arguments,
expressions,
- function_info,
+ parmeter_sampling,
)?;
}
Op::ImageQuerySize => {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2411,7 +2410,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
&mut self,
statements: &mut crate::Block,
expressions: &mut Arena<crate::Expression>,
- function: Option<Handle<crate::Function>>,
+ fun_parameter_sampling: &mut [image::SamplingFlags],
) -> Result<(), Error> {
use crate::Statement as S;
let mut i = 0usize;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2419,7 +2418,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
match statements[i] {
S::Emit(_) => {}
S::Block(ref mut block) => {
- self.patch_statements(block, expressions, function)?;
+ self.patch_statements(block, expressions, fun_parameter_sampling)?;
}
S::If {
condition: _,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2431,8 +2430,8 @@ impl<I: Iterator<Item = u32>> Parser<I> {
let extracted = mem::take(accept);
statements.splice(i + 1..i + 1, extracted);
} else {
- self.patch_statements(reject, expressions, function)?;
- self.patch_statements(accept, expressions, function)?;
+ self.patch_statements(reject, expressions, fun_parameter_sampling)?;
+ self.patch_statements(accept, expressions, fun_parameter_sampling)?;
}
}
S::Switch {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2446,17 +2445,21 @@ impl<I: Iterator<Item = u32>> Parser<I> {
statements.splice(i + 1..i + 1, extracted);
} else {
for case in cases.iter_mut() {
- self.patch_statements(&mut case.body, expressions, function)?;
+ self.patch_statements(
+ &mut case.body,
+ expressions,
+ fun_parameter_sampling,
+ )?;
}
- self.patch_statements(default, expressions, function)?;
+ self.patch_statements(default, expressions, fun_parameter_sampling)?;
}
}
S::Loop {
ref mut body,
ref mut continuing,
} => {
- self.patch_statements(body, expressions, function)?;
- self.patch_statements(continuing, expressions, function)?;
+ self.patch_statements(body, expressions, fun_parameter_sampling)?;
+ self.patch_statements(continuing, expressions, fun_parameter_sampling)?;
}
S::Break
| S::Continue
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2472,21 +2475,16 @@ impl<I: Iterator<Item = u32>> Parser<I> {
..
} => {
let fun_id = self.deferred_function_calls[callee.index()];
- let handle = *self.lookup_function.lookup(fun_id)?;
+ let fun_lookup = self.lookup_function.lookup(fun_id)?;
+ *callee = fun_lookup.handle;
// Patch sampling flags
- for (i, arg) in arguments.iter().enumerate() {
- let callee_info = &self.function_info[handle.index()];
-
- let flags = match callee_info.parameters_sampling.get(i) {
- Some(&flags) => flags,
+ for (arg_index, arg) in arguments.iter().enumerate() {
+ let flags = match fun_lookup.parameters_sampling.get(arg_index) {
+ Some(&flags) if !flags.is_empty() => flags,
_ => continue,
};
- if flags.is_empty() {
- continue;
- }
-
match expressions[*arg] {
crate::Expression::GlobalVariable(handle) => {
if let Some(sampling) = self.handle_sampling.get_mut(&handle) {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2494,17 +2492,11 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
}
crate::Expression::FunctionArgument(i) => {
- if let Some(handle) = function {
- let function_info =
- self.function_info.get_mut(handle.index()).unwrap();
- function_info.parameters_sampling[i as usize] |= flags;
- }
+ fun_parameter_sampling[i as usize] |= flags;
}
ref other => return Err(Error::InvalidGlobalVar(other.clone())),
}
}
-
- *callee = handle;
}
}
i += 1;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2517,13 +2509,35 @@ impl<I: Iterator<Item = u32>> Parser<I> {
handle: Option<Handle<crate::Function>>,
fun: &mut crate::Function,
) -> Result<(), Error> {
+ // Note: this search is a bit unfortunate
+ let (fun_id, mut parameters_sampling) = match handle {
+ Some(h) => {
+ let (&fun_id, lookup) = self
+ .lookup_function
+ .iter_mut()
+ .find(|&(_, ref lookup)| lookup.handle == h)
+ .unwrap();
+ (fun_id, mem::take(&mut lookup.parameters_sampling))
+ }
+ None => (0, Vec::new()),
+ };
+
for (_, expr) in fun.expressions.iter_mut() {
if let crate::Expression::CallResult(ref mut function) = *expr {
let fun_id = self.deferred_function_calls[function.index()];
- *function = *self.lookup_function.lookup(fun_id)?;
+ *function = self.lookup_function.lookup(fun_id)?.handle;
}
}
- self.patch_statements(&mut fun.body, &mut fun.expressions, handle)?;
+
+ self.patch_statements(
+ &mut fun.body,
+ &mut fun.expressions,
+ &mut parameters_sampling,
+ )?;
+
+ if let Some(lookup) = self.lookup_function.get_mut(&fun_id) {
+ lookup.parameters_sampling = parameters_sampling;
+ }
Ok(())
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2629,13 +2643,13 @@ impl<I: Iterator<Item = u32>> Parser<I> {
// skip all the fake IDs registered for the entry points
continue;
}
- let handle = self.lookup_function.get_mut(&fun_id).unwrap();
+ let lookup = self.lookup_function.get_mut(&fun_id).unwrap();
// take out the function from the old array
- let fun = mem::take(&mut functions[*handle]);
+ let fun = mem::take(&mut functions[lookup.handle]);
// add it to the newly formed arena, and adjust the lookup
- *handle = module
+ lookup.handle = module
.functions
- .append(fun, functions.get_span(*handle).clone());
+ .append(fun, functions.get_span(lookup.handle).clone());
}
}
// patch all the functions
|
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- rust: [1.43.0, nightly]
+ rust: ["1.43.0", nightly]
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -16,6 +16,12 @@ jobs:
profile: minimal
toolchain: ${{ matrix.rust }}
override: true
+ - uses: actions-rs/cargo@v1
+ name: Downgrade bitflags to MSRV
+ if: ${{ matrix.rust }} == "1.43.0"
+ with:
+ command: update
+ args: -p bitflags --precise 1.2.1
- uses: actions-rs/cargo@v1
name: Default test
with:
diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl
--- a/tests/in/control-flow.wgsl
+++ b/tests/in/control-flow.wgsl
@@ -3,4 +3,30 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3<u32>) {
//TODO: execution-only barrier?
storageBarrier();
workgroupBarrier();
+
+ var pos: i32;
+ // switch without cases
+ switch (1) {
+ default: {
+ pos = 1;
+ }
+ }
+
+ switch (pos) {
+ case 1: {
+ pos = 0;
+ break;
+ }
+ case 2: {
+ pos = 1;
+ }
+ case 3: {
+ pos = 2;
+ fallthrough;
+ }
+ case 4: {}
+ default: {
+ pos = 3;
+ }
+ }
}
diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl
--- a/tests/out/glsl/control-flow.main.Compute.glsl
+++ b/tests/out/glsl/control-flow.main.Compute.glsl
@@ -8,8 +8,28 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
void main() {
uvec3 global_id = gl_GlobalInvocationID;
+ int pos = 0;
groupMemoryBarrier();
groupMemoryBarrier();
- return;
+ switch(1) {
+ default:
+ pos = 1;
+ }
+ int _e4 = pos;
+ switch(_e4) {
+ case 1:
+ pos = 0;
+ break;
+ case 2:
+ pos = 1;
+ return;
+ case 3:
+ pos = 2;
+ case 4:
+ return;
+ default:
+ pos = 3;
+ return;
+ }
}
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -1,10 +1,6 @@
RWByteAddressBuffer bar : register(u0);
-struct VertexInput_foo {
- uint vi1 : SV_VertexID;
-};
-
uint NagaBufferLengthRW(RWByteAddressBuffer buffer)
{
uint ret;
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -12,7 +8,7 @@ uint NagaBufferLengthRW(RWByteAddressBuffer buffer)
return ret;
}
-float4 foo(VertexInput_foo vertexinput_foo) : SV_Position
+float4 foo(uint vi : SV_VertexID) : SV_Position
{
float foo1 = 0.0;
int c[5] = {(int)0,(int)0,(int)0,(int)0,(int)0};
diff --git a/tests/out/hlsl/access.hlsl b/tests/out/hlsl/access.hlsl
--- a/tests/out/hlsl/access.hlsl
+++ b/tests/out/hlsl/access.hlsl
@@ -41,8 +37,8 @@ float4 foo(VertexInput_foo vertexinput_foo) : SV_Position
int _result[5]={ a, int(b), 3, 4, 5 };
for(int _i=0; _i<5; ++_i) c[_i] = _result[_i];
}
- c[(vertexinput_foo.vi1 + 1u)] = 42;
- int value = c[vertexinput_foo.vi1];
+ c[(vi + 1u)] = 42;
+ int value = c[vi];
return mul(float4(int4(value.xxxx)), matrix1);
}
diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl
--- a/tests/out/hlsl/boids.hlsl
+++ b/tests/out/hlsl/boids.hlsl
@@ -19,12 +19,8 @@ cbuffer params : register(b0) { SimParams params; }
ByteAddressBuffer particlesSrc : register(t1);
RWByteAddressBuffer particlesDst : register(u2);
-struct ComputeInput_main {
- uint3 global_invocation_id1 : SV_DispatchThreadID;
-};
-
[numthreads(64, 1, 1)]
-void main(ComputeInput_main computeinput_main)
+void main(uint3 global_invocation_id : SV_DispatchThreadID)
{
float2 vPos = (float2)0;
float2 vVel = (float2)0;
diff --git a/tests/out/hlsl/boids.hlsl b/tests/out/hlsl/boids.hlsl
--- a/tests/out/hlsl/boids.hlsl
+++ b/tests/out/hlsl/boids.hlsl
@@ -37,7 +33,7 @@ void main(ComputeInput_main computeinput_main)
float2 vel = (float2)0;
uint i = 0u;
- uint index = computeinput_main.global_invocation_id1.x;
+ uint index = global_invocation_id.x;
if ((index >= NUM_PARTICLES)) {
return;
}
diff --git a/tests/out/hlsl/collatz.hlsl b/tests/out/hlsl/collatz.hlsl
--- a/tests/out/hlsl/collatz.hlsl
+++ b/tests/out/hlsl/collatz.hlsl
@@ -1,10 +1,6 @@
RWByteAddressBuffer v_indices : register(u0);
-struct ComputeInput_main {
- uint3 global_id1 : SV_DispatchThreadID;
-};
-
uint collatz_iterations(uint n_base)
{
uint n = (uint)0;
diff --git a/tests/out/hlsl/collatz.hlsl b/tests/out/hlsl/collatz.hlsl
--- a/tests/out/hlsl/collatz.hlsl
+++ b/tests/out/hlsl/collatz.hlsl
@@ -32,10 +28,10 @@ uint collatz_iterations(uint n_base)
}
[numthreads(1, 1, 1)]
-void main(ComputeInput_main computeinput_main)
+void main(uint3 global_id : SV_DispatchThreadID)
{
- uint _expr8 = asuint(v_indices.Load(computeinput_main.global_id1.x*4+0));
+ uint _expr8 = asuint(v_indices.Load(global_id.x*4+0));
const uint _e9 = collatz_iterations(_expr8);
- v_indices.Store(computeinput_main.global_id1.x*4+0, asuint(_e9));
+ v_indices.Store(global_id.x*4+0, asuint(_e9));
return;
}
diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl
--- a/tests/out/hlsl/control-flow.hlsl
+++ b/tests/out/hlsl/control-flow.hlsl
@@ -1,12 +1,41 @@
-struct ComputeInput_main {
- uint3 global_id1 : SV_DispatchThreadID;
-};
-
[numthreads(1, 1, 1)]
-void main(ComputeInput_main computeinput_main)
+void main(uint3 global_id : SV_DispatchThreadID)
{
+ int pos = (int)0;
+
DeviceMemoryBarrierWithGroupSync();
GroupMemoryBarrierWithGroupSync();
- return;
+ switch(1) {
+ default: {
+ pos = 1;
+ }
+ }
+ int _expr4 = pos;
+ switch(_expr4) {
+ case 1: {
+ pos = 0;
+ break;
+ break;
+ }
+ case 2: {
+ pos = 1;
+ return;
+ break;
+ }
+ case 3: {
+ /* fallthrough */
+ {
+ pos = 2;
+ }
+ }
+ case 4: {
+ return;
+ break;
+ }
+ default: {
+ pos = 3;
+ return;
+ }
+ }
}
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -16,10 +16,6 @@ SamplerState sampler_reg : register(s0, space1);
SamplerComparisonState sampler_cmp : register(s1, space1);
Texture2D<float> image_2d_depth : register(t2, space1);
-struct ComputeInput_main {
- uint3 local_id1 : SV_GroupThreadID;
-};
-
int2 NagaRWDimensions2D(RWTexture2D<uint4> texture)
{
uint4 ret;
diff --git a/tests/out/hlsl/image.hlsl b/tests/out/hlsl/image.hlsl
--- a/tests/out/hlsl/image.hlsl
+++ b/tests/out/hlsl/image.hlsl
@@ -28,15 +24,15 @@ int2 NagaRWDimensions2D(RWTexture2D<uint4> texture)
}
[numthreads(16, 1, 1)]
-void main(ComputeInput_main computeinput_main)
+void main(uint3 local_id : SV_GroupThreadID)
{
int2 dim = NagaRWDimensions2D(image_storage_src);
- int2 itc = ((dim * int2(computeinput_main.local_id1.xy)) % int2(10, 20));
- uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(computeinput_main.local_id1.z)));
- uint4 value2_ = image_multisampled_src.Load(itc, int(computeinput_main.local_id1.z));
- float value3_ = image_depth_multisampled_src.Load(itc, int(computeinput_main.local_id1.z)).x;
+ int2 itc = ((dim * int2(local_id.xy)) % int2(10, 20));
+ uint4 value1_ = image_mipmapped_src.Load(int3(itc, int(local_id.z)));
+ uint4 value2_ = image_multisampled_src.Load(itc, int(local_id.z));
+ float value3_ = image_depth_multisampled_src.Load(itc, int(local_id.z)).x;
uint4 value4_ = image_storage_src.Load(itc);
- uint4 value5_ = image_array_src.Load(int4(itc, int(computeinput_main.local_id1.z), (int(computeinput_main.local_id1.z) + 1)));
+ uint4 value5_ = image_array_src.Load(int4(itc, int(local_id.z), (int(local_id.z) + 1)));
image_dst[itc.x] = ((((value1_ + value2_) + uint4(uint(value3_).xxxx)) + value4_) + value5_);
return;
}
diff --git a/tests/out/hlsl/interface.hlsl b/tests/out/hlsl/interface.hlsl
--- a/tests/out/hlsl/interface.hlsl
+++ b/tests/out/hlsl/interface.hlsl
@@ -18,45 +18,42 @@ struct FragmentOutput {
groupshared uint output[1];
-struct VertexInput_vertex {
- uint color1 : LOC10;
- uint instance_index1 : SV_InstanceID;
- uint vertex_index1 : SV_VertexID;
+struct VertexOutput_vertex {
+ float varying : LOC1;
+ float4 position : SV_Position;
};
struct FragmentInput_fragment {
+ float varying : LOC1;
+ float4 position : SV_Position;
bool front_facing1 : SV_IsFrontFace;
uint sample_index1 : SV_SampleIndex;
uint sample_mask1 : SV_Coverage;
- VertexOutput in2;
-};
-
-struct ComputeInput_compute {
- uint3 global_id1 : SV_DispatchThreadID;
- uint3 local_id1 : SV_GroupThreadID;
- uint local_index1 : SV_GroupIndex;
- uint3 wg_id1 : SV_GroupID;
- uint3 num_wgs1 : SV_GroupID;
};
-VertexOutput vertex(VertexInput_vertex vertexinput_vertex)
+VertexOutput_vertex vertex(uint vertex_index : SV_VertexID, uint instance_index : SV_InstanceID, uint color : LOC10)
{
- uint tmp = (((_NagaConstants.base_vertex + vertexinput_vertex.vertex_index1) + (_NagaConstants.base_instance + vertexinput_vertex.instance_index1)) + vertexinput_vertex.color1);
- const VertexOutput vertexoutput1 = { float4(1.0.xxxx), float(tmp) };
+ uint tmp = (((_NagaConstants.base_vertex + vertex_index) + (_NagaConstants.base_instance + instance_index)) + color);
+ const VertexOutput vertexoutput = { float4(1.0.xxxx), float(tmp) };
+ const VertexOutput_vertex vertexoutput1 = { vertexoutput.varying, vertexoutput.position };
return vertexoutput1;
}
FragmentOutput fragment(FragmentInput_fragment fragmentinput_fragment)
{
- uint mask = (fragmentinput_fragment.sample_mask1 & (1u << fragmentinput_fragment.sample_index1));
- float color2 = (fragmentinput_fragment.front_facing1 ? 1.0 : 0.0);
- const FragmentOutput fragmentoutput1 = { fragmentinput_fragment.in2.varying, mask, color2 };
- return fragmentoutput1;
+ VertexOutput in1 = { fragmentinput_fragment.position, fragmentinput_fragment.varying };
+ bool front_facing = fragmentinput_fragment.front_facing1;
+ uint sample_index = fragmentinput_fragment.sample_index1;
+ uint sample_mask = fragmentinput_fragment.sample_mask1;
+ uint mask = (sample_mask & (1u << sample_index));
+ float color1 = (front_facing ? 1.0 : 0.0);
+ const FragmentOutput fragmentoutput = { in1.varying, mask, color1 };
+ return fragmentoutput;
}
[numthreads(1, 1, 1)]
-void compute(ComputeInput_compute computeinput_compute)
+void compute(uint3 global_id : SV_DispatchThreadID, uint3 local_id : SV_GroupThreadID, uint local_index : SV_GroupIndex, uint3 wg_id : SV_GroupID, uint3 num_wgs : SV_GroupID)
{
- output[0] = ((((computeinput_compute.global_id1.x + computeinput_compute.local_id1.x) + computeinput_compute.local_index1) + computeinput_compute.wg_id1.x) + uint3(_NagaConstants.base_vertex, _NagaConstants.base_instance, _NagaConstants.other).x);
+ output[0] = ((((global_id.x + local_id.x) + local_index) + wg_id.x) + uint3(_NagaConstants.base_vertex, _NagaConstants.base_instance, _NagaConstants.other).x);
return;
}
diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl
--- a/tests/out/hlsl/interpolate.hlsl
+++ b/tests/out/hlsl/interpolate.hlsl
@@ -10,11 +10,29 @@ struct FragmentInput {
linear sample float perspective_sample : LOC6;
};
+struct VertexOutput_main {
+ uint flat : LOC0;
+ float linear1 : LOC1;
+ float2 linear_centroid : LOC2;
+ float3 linear_sample : LOC3;
+ float4 perspective : LOC4;
+ float perspective_centroid : LOC5;
+ float perspective_sample : LOC6;
+ float4 position : SV_Position;
+};
+
struct FragmentInput_main {
- FragmentInput val1;
+ uint flat : LOC0;
+ float linear2 : LOC1;
+ float2 linear_centroid : LOC2;
+ float3 linear_sample : LOC3;
+ float4 perspective : LOC4;
+ float perspective_centroid : LOC5;
+ float perspective_sample : LOC6;
+ float4 position : SV_Position;
};
-FragmentInput main()
+VertexOutput_main main()
{
FragmentInput out1 = (FragmentInput)0;
diff --git a/tests/out/hlsl/interpolate.hlsl b/tests/out/hlsl/interpolate.hlsl
--- a/tests/out/hlsl/interpolate.hlsl
+++ b/tests/out/hlsl/interpolate.hlsl
@@ -27,11 +45,13 @@ FragmentInput main()
out1.perspective_centroid = 2197.0;
out1.perspective_sample = 2744.0;
FragmentInput _expr30 = out1;
- const FragmentInput fragmentinput1 = _expr30;
+ const FragmentInput fragmentinput = _expr30;
+ const VertexOutput_main fragmentinput1 = { fragmentinput.flat, fragmentinput.linear1, fragmentinput.linear_centroid, fragmentinput.linear_sample, fragmentinput.perspective, fragmentinput.perspective_centroid, fragmentinput.perspective_sample, fragmentinput.position };
return fragmentinput1;
}
void main1(FragmentInput_main fragmentinput_main)
{
+ FragmentInput val = { fragmentinput_main.position, fragmentinput_main.flat, fragmentinput_main.linear2, fragmentinput_main.linear_centroid, fragmentinput_main.linear_sample, fragmentinput_main.perspective, fragmentinput_main.perspective_centroid, fragmentinput_main.perspective_sample };
return;
}
diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl
--- a/tests/out/hlsl/quad-vert.hlsl
+++ b/tests/out/hlsl/quad-vert.hlsl
@@ -1,27 +1,30 @@
struct gl_PerVertex {
float4 gl_Position : SV_Position;
+ float gl_PointSize : PSIZE;
float gl_ClipDistance[1] : SV_ClipDistance;
float gl_CullDistance[1] : SV_CullDistance;
- float gl_PointSize : PSIZE;
};
struct type10 {
linear float2 member : LOC0;
float4 gl_Position : SV_Position;
+ float gl_PointSize : PSIZE;
float gl_ClipDistance[1] : SV_ClipDistance;
float gl_CullDistance[1] : SV_CullDistance;
- float gl_PointSize : PSIZE;
};
static float2 v_uv = (float2)0;
static float2 a_uv1 = (float2)0;
-static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, float(0.0), float(0.0) };
+static gl_PerVertex perVertexStruct = { float4(0.0, 0.0, 0.0, 1.0), 1.0, { 0.0 }, { 0.0 } };
static float2 a_pos1 = (float2)0;
-struct VertexInput_main {
- float2 a_pos2 : LOC0;
- float2 a_uv2 : LOC1;
+struct VertexOutput_main {
+ float2 member : LOC0;
+ float4 gl_Position : SV_Position;
+ float gl_ClipDistance : SV_ClipDistance;
+ float gl_CullDistance : SV_CullDistance;
+ float gl_PointSize : PSIZE;
};
void main1()
diff --git a/tests/out/hlsl/quad-vert.hlsl b/tests/out/hlsl/quad-vert.hlsl
--- a/tests/out/hlsl/quad-vert.hlsl
+++ b/tests/out/hlsl/quad-vert.hlsl
@@ -33,16 +36,17 @@ void main1()
return;
}
-type10 main(VertexInput_main vertexinput_main)
+VertexOutput_main main(float2 a_uv : LOC1, float2 a_pos : LOC0)
{
- a_uv1 = vertexinput_main.a_uv2;
- a_pos1 = vertexinput_main.a_pos2;
+ a_uv1 = a_uv;
+ a_pos1 = a_pos;
main1();
float2 _expr10 = v_uv;
float4 _expr11 = perVertexStruct.gl_Position;
float _expr12 = perVertexStruct.gl_PointSize;
float _expr13[1] = perVertexStruct.gl_ClipDistance;
float _expr14[1] = perVertexStruct.gl_CullDistance;
- const type10 type10_ = { _expr10, _expr11, _expr13, _expr14, _expr12 };
- return type10_;
+ const type10 type10_ = { _expr10, _expr11, _expr12, _expr13, _expr14 };
+ const VertexOutput_main type10_1 = { type10_.member, type10_.gl_Position, type10_.gl_ClipDistance, type10_.gl_CullDistance, type10_.gl_PointSize };
+ return type10_1;
}
diff --git a/tests/out/hlsl/quad.hlsl b/tests/out/hlsl/quad.hlsl
--- a/tests/out/hlsl/quad.hlsl
+++ b/tests/out/hlsl/quad.hlsl
@@ -8,24 +8,26 @@ struct VertexOutput {
Texture2D<float4> u_texture : register(t0);
SamplerState u_sampler : register(s1);
-struct VertexInput_main {
- float2 pos1 : LOC0;
- float2 uv2 : LOC1;
+struct VertexOutput_main {
+ float2 uv2 : LOC0;
+ float4 position : SV_Position;
};
struct FragmentInput_main {
float2 uv3 : LOC0;
};
-VertexOutput main(VertexInput_main vertexinput_main)
+VertexOutput_main main(float2 pos : LOC0, float2 uv : LOC1)
{
- const VertexOutput vertexoutput1 = { vertexinput_main.uv2, float4((c_scale * vertexinput_main.pos1), 0.0, 1.0) };
+ const VertexOutput vertexoutput = { uv, float4((c_scale * pos), 0.0, 1.0) };
+ const VertexOutput_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position };
return vertexoutput1;
}
float4 main1(FragmentInput_main fragmentinput_main) : SV_Target0
{
- float4 color = u_texture.Sample(u_sampler, fragmentinput_main.uv3);
+ float2 uv1 = fragmentinput_main.uv3;
+ float4 color = u_texture.Sample(u_sampler, uv1);
if ((color.w == 0.0)) {
discard;
}
diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl
--- a/tests/out/hlsl/shadow.hlsl
+++ b/tests/out/hlsl/shadow.hlsl
@@ -34,10 +34,12 @@ float fetch_shadow(uint light_id, float4 homogeneous_coords)
float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0
{
+ float3 raw_normal = fragmentinput_fs_main.raw_normal1;
+ float4 position = fragmentinput_fs_main.position1;
float3 color = float3(0.05, 0.05, 0.05);
uint i = 0u;
- float3 normal = normalize(fragmentinput_fs_main.raw_normal1);
+ float3 normal = normalize(raw_normal);
bool loop_init = true;
while(true) {
if (!loop_init) {
diff --git a/tests/out/hlsl/shadow.hlsl b/tests/out/hlsl/shadow.hlsl
--- a/tests/out/hlsl/shadow.hlsl
+++ b/tests/out/hlsl/shadow.hlsl
@@ -53,8 +55,8 @@ float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0
uint _expr19 = i;
Light light = {float4x4(asfloat(s_lights.Load4(_expr19*96+0+0+0)), asfloat(s_lights.Load4(_expr19*96+0+0+16)), asfloat(s_lights.Load4(_expr19*96+0+0+32)), asfloat(s_lights.Load4(_expr19*96+0+0+48))), asfloat(s_lights.Load4(_expr19*96+0+64)), asfloat(s_lights.Load4(_expr19*96+0+80))};
uint _expr22 = i;
- const float _e25 = fetch_shadow(_expr22, mul(fragmentinput_fs_main.position1, light.proj));
- float3 light_dir = normalize((light.pos.xyz - fragmentinput_fs_main.position1.xyz));
+ const float _e25 = fetch_shadow(_expr22, mul(position, light.proj));
+ float3 light_dir = normalize((light.pos.xyz - position.xyz));
float diffuse = max(0.0, dot(normal, light_dir));
float3 _expr34 = color;
color = (_expr34 + ((_e25 * diffuse) * light.color.xyz));
diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl
--- a/tests/out/hlsl/skybox.hlsl
+++ b/tests/out/hlsl/skybox.hlsl
@@ -19,21 +19,23 @@ cbuffer r_data : register(b0) { Data r_data; }
TextureCube<float4> r_texture : register(t0);
SamplerState r_sampler : register(s0, space1);
-struct VertexInput_vs_main {
- uint vertex_index1 : SV_VertexID;
+struct VertexOutput_vs_main {
+ float3 uv : LOC0;
+ float4 position : SV_Position;
};
struct FragmentInput_fs_main {
- VertexOutput in2;
+ float3 uv : LOC0;
+ float4 position : SV_Position;
};
-VertexOutput vs_main(VertexInput_vs_main vertexinput_vs_main)
+VertexOutput_vs_main vs_main(uint vertex_index : SV_VertexID)
{
int tmp1_ = (int)0;
int tmp2_ = (int)0;
- tmp1_ = (int((_NagaConstants.base_vertex + vertexinput_vs_main.vertex_index1)) / 2);
- tmp2_ = (int((_NagaConstants.base_vertex + vertexinput_vs_main.vertex_index1)) & 1);
+ tmp1_ = (int((_NagaConstants.base_vertex + vertex_index)) / 2);
+ tmp2_ = (int((_NagaConstants.base_vertex + vertex_index)) & 1);
int _expr10 = tmp1_;
int _expr16 = tmp2_;
float4 pos = float4(((float(_expr10) * 4.0) - 1.0), ((float(_expr16) * 4.0) - 1.0), 0.0, 1.0);
diff --git a/tests/out/hlsl/skybox.hlsl b/tests/out/hlsl/skybox.hlsl
--- a/tests/out/hlsl/skybox.hlsl
+++ b/tests/out/hlsl/skybox.hlsl
@@ -43,12 +45,14 @@ VertexOutput vs_main(VertexInput_vs_main vertexinput_vs_main)
float3x3 inv_model_view = transpose(float3x3(_expr27.xyz, _expr31.xyz, _expr35.xyz));
float4x4 _expr40 = r_data.proj_inv;
float4 unprojected = mul(pos, _expr40);
- const VertexOutput vertexoutput1 = { pos, mul(unprojected.xyz, inv_model_view) };
+ const VertexOutput vertexoutput = { pos, mul(unprojected.xyz, inv_model_view) };
+ const VertexOutput_vs_main vertexoutput1 = { vertexoutput.uv, vertexoutput.position };
return vertexoutput1;
}
float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0
{
- float4 _expr5 = r_texture.Sample(r_sampler, fragmentinput_fs_main.in2.uv);
+ VertexOutput in1 = { fragmentinput_fs_main.position, fragmentinput_fs_main.uv };
+ float4 _expr5 = r_texture.Sample(r_sampler, in1.uv);
return _expr5;
}
diff --git a/tests/out/hlsl/standard.hlsl b/tests/out/hlsl/standard.hlsl
--- a/tests/out/hlsl/standard.hlsl
+++ b/tests/out/hlsl/standard.hlsl
@@ -5,8 +5,9 @@ struct FragmentInput_derivatives {
float4 derivatives(FragmentInput_derivatives fragmentinput_derivatives) : SV_Target0
{
- float4 x = ddx(fragmentinput_derivatives.foo1);
- float4 y = ddy(fragmentinput_derivatives.foo1);
- float4 z = fwidth(fragmentinput_derivatives.foo1);
+ float4 foo = fragmentinput_derivatives.foo1;
+ float4 x = ddx(foo);
+ float4 y = ddy(foo);
+ float4 z = fwidth(foo);
return ((x + y) * z);
}
diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl
--- a/tests/out/msl/control-flow.msl
+++ b/tests/out/msl/control-flow.msl
@@ -8,7 +8,36 @@ struct main1Input {
kernel void main1(
metal::uint3 global_id [[thread_position_in_grid]]
) {
+ int pos;
metal::threadgroup_barrier(metal::mem_flags::mem_device);
metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup);
- return;
+ switch(1) {
+ default: {
+ pos = 1;
+ }
+ }
+ int _e4 = pos;
+ switch(_e4) {
+ case 1: {
+ pos = 0;
+ break;
+ break;
+ }
+ case 2: {
+ pos = 1;
+ return;
+ break;
+ }
+ case 3: {
+ pos = 2;
+ }
+ case 4: {
+ return;
+ break;
+ }
+ default: {
+ pos = 3;
+ return;
+ }
+ }
}
diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl
--- a/tests/out/wgsl/control-flow.wgsl
+++ b/tests/out/wgsl/control-flow.wgsl
@@ -1,6 +1,34 @@
[[stage(compute), workgroup_size(1, 1, 1)]]
fn main([[builtin(global_invocation_id)]] global_id: vec3<u32>) {
+ var pos: i32;
+
storageBarrier();
workgroupBarrier();
- return;
+ switch(1) {
+ default: {
+ pos = 1;
+ }
+ }
+ let _e4: i32 = pos;
+ switch(_e4) {
+ case 1: {
+ pos = 0;
+ break;
+ }
+ case 2: {
+ pos = 1;
+ return;
+ }
+ case 3: {
+ pos = 2;
+ fallthrough;
+ }
+ case 4: {
+ return;
+ }
+ default: {
+ pos = 3;
+ return;
+ }
+ }
}
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -425,7 +425,9 @@ fn convert_wgsl() {
),
(
"control-flow",
- Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL,
+ // TODO: SPIRV https://github.com/gfx-rs/naga/issues/1017
+ //Targets::SPIRV |
+ Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL,
),
(
"standard",
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -454,7 +456,7 @@ fn convert_wgsl() {
.expect("Couldn't find wgsl file");
match naga::front::wgsl::parse_str(&file) {
Ok(module) => check_targets(&module, name, targets),
- Err(e) => panic!("{}", e),
+ Err(e) => panic!("{}", e.emit_to_string(&file)),
}
}
}
|
[glsl-out] Operands to "%" must be integral
### Example:
This valid glsl:
```glsl
float out = mod(1.0,1.0);
```
Translates to this wgls
```rs
let out: f32 = 1.0 % 1.0;
```
And this wgls translates to this glsl:
```glsl
float out = 1.0 % 1.0;
```
The resulting shader does not work.
When run with wgpu it outputs:
`Internal error in VERTEX shader: 0(27) : error C1021: operands to "%" must be integral`
|
2021-08-25T06:12:39Z
|
0.6
|
2021-08-24T22:17:23Z
|
2e7d629aefe6857ade4f96fe2c3dc1a09f0fa4db
|
[
"convert_wgsl"
] |
[
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"front::glsl::parser_tests::declarations",
"front::glsl::constants::tests::unary_op",
"back::spv::layout::test_physical_layout_in_words",
"front::glsl::parser_tests::function_overloading",
"back::spv::writer::test_write_physical_layout",
"front::glsl::parser_tests::constants",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::constants::tests::cast",
"front::glsl::parser_tests::functions",
"back::msl::test_error_size",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::constants::tests::access",
"back::msl::writer::test_stack_size",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::control_flow",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::vector_indexing",
"front::glsl::parser_tests::structs",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_if",
"front::spv::test::parse",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_type_inference",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_texture_load",
"proc::test_matrix_size",
"front::wgsl::type_inner_tests::to_wgsl",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_loop",
"convert_spv_pointer_access",
"convert_spv_shadow",
"convert_spv_quad_vert",
"convert_glsl_folder",
"function_without_identifier",
"bad_texture_sample_type",
"bad_for_initializer",
"inconsistent_binding",
"invalid_float",
"invalid_integer",
"invalid_scalar_width",
"invalid_texture_sample_type",
"bad_type_cast",
"local_var_missing_type",
"bad_texture",
"let_type_mismatch",
"invalid_arrays",
"invalid_local_vars",
"invalid_structs",
"unknown_attribute",
"invalid_functions",
"struct_member_zero_size",
"unknown_conservative_depth",
"unknown_access",
"invalid_access",
"struct_member_zero_align",
"local_var_type_mismatch",
"unknown_built_in",
"unknown_ident",
"unknown_shader_stage",
"unknown_storage_class",
"unknown_scalar_type",
"unknown_storage_format",
"missing_bindings",
"unknown_type",
"unknown_local_function",
"unknown_identifier",
"zero_array_stride",
"negative_index",
"valid_access",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 26)",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 17)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,265
|
gfx-rs__naga-1265
|
[
"1261"
] |
70be72d9b9615557fa8726829813755ee6b52279
|
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1441,11 +1441,6 @@ impl<'a, W: Write> Writer<'a, W> {
for sta in case.body.iter() {
self.write_stmt(sta, ctx, indent + 2)?;
}
-
- // Write `break;` if the block isn't fallthrough
- if !case.fall_through {
- writeln!(self.out, "{}break;", INDENT.repeat(indent + 2))?;
- }
}
// Only write the default block if the block isn't empty
diff --git a/src/back/hlsl/writer.rs b/src/back/hlsl/writer.rs
--- a/src/back/hlsl/writer.rs
+++ b/src/back/hlsl/writer.rs
@@ -1204,8 +1204,61 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
self.temp_access_chain = chain;
self.named_expressions.insert(result, res_name);
}
- Statement::Switch { .. } => {
- return Err(Error::Unimplemented(format!("write_stmt {:?}", stmt)))
+ Statement::Switch {
+ selector,
+ ref cases,
+ ref default,
+ } => {
+ // Start the switch
+ write!(self.out, "{}", INDENT.repeat(indent))?;
+ write!(self.out, "switch(")?;
+ self.write_expr(module, selector, func_ctx)?;
+ writeln!(self.out, ") {{")?;
+
+ // Write all cases
+ let indent_str_1 = INDENT.repeat(indent + 1);
+ let indent_str_2 = INDENT.repeat(indent + 2);
+
+ for case in cases {
+ writeln!(self.out, "{}case {}: {{", &indent_str_1, case.value)?;
+
+ if case.fall_through {
+ // Generate each fallthrough case statement in a new block. This is done to
+ // prevent symbol collision of variables declared in these cases statements.
+ writeln!(self.out, "{}/* fallthrough */", &indent_str_2)?;
+ writeln!(self.out, "{}{{", &indent_str_2)?;
+ }
+ for sta in case.body.iter() {
+ self.write_stmt(
+ module,
+ sta,
+ func_ctx,
+ indent + 2 + usize::from(case.fall_through),
+ )?;
+ }
+
+ if case.fall_through {
+ writeln!(self.out, "{}}}", &indent_str_2)?;
+ } else {
+ writeln!(self.out, "{}break;", &indent_str_2)?;
+ }
+
+ writeln!(self.out, "{}}}", &indent_str_1)?;
+ }
+
+ // Only write the default block if the block isn't empty
+ // Writing default without a block is valid but it's more readable this way
+ if !default.is_empty() {
+ writeln!(self.out, "{}default: {{", &indent_str_1)?;
+
+ for sta in default {
+ self.write_stmt(module, sta, func_ctx, indent + 2)?;
+ }
+
+ writeln!(self.out, "{}}}", &indent_str_1)?;
+ }
+
+ writeln!(self.out, "{}}}", INDENT.repeat(indent))?
}
}
|
diff --git a/tests/in/control-flow.wgsl b/tests/in/control-flow.wgsl
--- a/tests/in/control-flow.wgsl
+++ b/tests/in/control-flow.wgsl
@@ -3,4 +3,30 @@ fn main([[builtin(global_invocation_id)]] global_id: vec3<u32>) {
//TODO: execution-only barrier?
storageBarrier();
workgroupBarrier();
+
+ var pos: i32;
+ // switch without cases
+ switch (1) {
+ default: {
+ pos = 1;
+ }
+ }
+
+ switch (pos) {
+ case 1: {
+ pos = 0;
+ break;
+ }
+ case 2: {
+ pos = 1;
+ }
+ case 3: {
+ pos = 2;
+ fallthrough;
+ }
+ case 4: {}
+ default: {
+ pos = 3;
+ }
+ }
}
diff --git a/tests/out/glsl/control-flow.main.Compute.glsl b/tests/out/glsl/control-flow.main.Compute.glsl
--- a/tests/out/glsl/control-flow.main.Compute.glsl
+++ b/tests/out/glsl/control-flow.main.Compute.glsl
@@ -8,8 +8,28 @@ layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
void main() {
uvec3 global_id = gl_GlobalInvocationID;
+ int pos = 0;
groupMemoryBarrier();
groupMemoryBarrier();
- return;
+ switch(1) {
+ default:
+ pos = 1;
+ }
+ int _e4 = pos;
+ switch(_e4) {
+ case 1:
+ pos = 0;
+ break;
+ case 2:
+ pos = 1;
+ return;
+ case 3:
+ pos = 2;
+ case 4:
+ return;
+ default:
+ pos = 3;
+ return;
+ }
}
diff --git a/tests/out/hlsl/control-flow.hlsl b/tests/out/hlsl/control-flow.hlsl
--- a/tests/out/hlsl/control-flow.hlsl
+++ b/tests/out/hlsl/control-flow.hlsl
@@ -6,7 +6,40 @@ struct ComputeInput_main {
[numthreads(1, 1, 1)]
void main(ComputeInput_main computeinput_main)
{
+ int pos = (int)0;
+
DeviceMemoryBarrierWithGroupSync();
GroupMemoryBarrierWithGroupSync();
- return;
+ switch(1) {
+ default: {
+ pos = 1;
+ }
+ }
+ int _expr4 = pos;
+ switch(_expr4) {
+ case 1: {
+ pos = 0;
+ break;
+ break;
+ }
+ case 2: {
+ pos = 1;
+ return;
+ break;
+ }
+ case 3: {
+ /* fallthrough */
+ {
+ pos = 2;
+ }
+ }
+ case 4: {
+ return;
+ break;
+ }
+ default: {
+ pos = 3;
+ return;
+ }
+ }
}
diff --git a/tests/out/msl/control-flow.msl b/tests/out/msl/control-flow.msl
--- a/tests/out/msl/control-flow.msl
+++ b/tests/out/msl/control-flow.msl
@@ -8,7 +8,36 @@ struct main1Input {
kernel void main1(
metal::uint3 global_id [[thread_position_in_grid]]
) {
+ int pos;
metal::threadgroup_barrier(metal::mem_flags::mem_device);
metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup);
- return;
+ switch(1) {
+ default: {
+ pos = 1;
+ }
+ }
+ int _e4 = pos;
+ switch(_e4) {
+ case 1: {
+ pos = 0;
+ break;
+ break;
+ }
+ case 2: {
+ pos = 1;
+ return;
+ break;
+ }
+ case 3: {
+ pos = 2;
+ }
+ case 4: {
+ return;
+ break;
+ }
+ default: {
+ pos = 3;
+ return;
+ }
+ }
}
diff --git a/tests/out/wgsl/control-flow.wgsl b/tests/out/wgsl/control-flow.wgsl
--- a/tests/out/wgsl/control-flow.wgsl
+++ b/tests/out/wgsl/control-flow.wgsl
@@ -1,6 +1,34 @@
[[stage(compute), workgroup_size(1, 1, 1)]]
fn main([[builtin(global_invocation_id)]] global_id: vec3<u32>) {
+ var pos: i32;
+
storageBarrier();
workgroupBarrier();
- return;
+ switch(1) {
+ default: {
+ pos = 1;
+ }
+ }
+ let _e4: i32 = pos;
+ switch(_e4) {
+ case 1: {
+ pos = 0;
+ break;
+ }
+ case 2: {
+ pos = 1;
+ return;
+ }
+ case 3: {
+ pos = 2;
+ fallthrough;
+ }
+ case 4: {
+ return;
+ }
+ default: {
+ pos = 3;
+ return;
+ }
+ }
}
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -425,7 +425,9 @@ fn convert_wgsl() {
),
(
"control-flow",
- Targets::SPIRV | Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL,
+ // TODO: SPIRV https://github.com/gfx-rs/naga/issues/1017
+ //Targets::SPIRV |
+ Targets::METAL | Targets::GLSL | Targets::HLSL | Targets::WGSL,
),
(
"standard",
|
[hlsl-out] Unimplemented Switch
One of the shaders that is in my dependency tree ([wgpu_glyph shader](https://github.com/hecrj/wgpu_glyph/blob/master/src/shader/glyph.wgsl)) uses a switch statement, which causes a panic because of unimplemented switch writer in hlsl. It's especially problematic because DX12 is the default wgpu backend on Windows.
https://github.com/gfx-rs/naga/blob/dfcb79880f3a42781efc72ae47ea291cbea8efec/src/back/hlsl/writer.rs#L1208
|
2021-08-21T04:39:34Z
|
0.6
|
2021-08-24T22:15:33Z
|
2e7d629aefe6857ade4f96fe2c3dc1a09f0fa4db
|
[
"convert_wgsl"
] |
[
"back::msl::test_error_size",
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout::test_physical_layout_in_words",
"arena::tests::fetch_or_append_unique",
"front::glsl::constants::tests::access",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::constants",
"back::msl::writer::test_stack_size",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::glsl::parser_tests::version",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::expressions",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::control_flow",
"front::glsl::parser_tests::swizzles",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::function_overloading",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::declarations",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_switch",
"proc::test_matrix_size",
"front::wgsl::type_inner_tests::to_wgsl",
"valid::analyzer::uniform_control_flow",
"proc::typifier::test_error_size",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::functions",
"convert_spv_pointer_access",
"convert_spv_shadow",
"convert_spv_inverse_hyperbolic_trig_functions",
"convert_spv_quad_vert",
"convert_glsl_folder",
"function_without_identifier",
"bad_for_initializer",
"inconsistent_binding",
"bad_texture_sample_type",
"bad_type_cast",
"invalid_integer",
"invalid_float",
"invalid_texture_sample_type",
"invalid_scalar_width",
"let_type_mismatch",
"invalid_structs",
"invalid_functions",
"local_var_missing_type",
"invalid_arrays",
"struct_member_zero_align",
"bad_texture",
"struct_member_zero_size",
"invalid_local_vars",
"invalid_access",
"unknown_built_in",
"unknown_attribute",
"unknown_access",
"local_var_type_mismatch",
"negative_index",
"unknown_conservative_depth",
"unknown_shader_stage",
"unknown_storage_class",
"unknown_local_function",
"unknown_scalar_type",
"zero_array_stride",
"unknown_ident",
"unknown_storage_format",
"unknown_identifier",
"missing_bindings",
"unknown_type",
"valid_access",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 17)",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 26)",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
|
gfx-rs/naga
| 1,249
|
gfx-rs__naga-1249
|
[
"1237"
] |
fc47008d0c01fd1658626f6ed7fa4a7a695da3be
|
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -1,6 +1,6 @@
use std::fmt;
-use super::{builtins::MacroCall, SourceMetadata};
+use super::{builtins::MacroCall, context::ExprPos, SourceMetadata};
use crate::{
BinaryOperator, Binding, Constant, Expression, Function, GlobalVariable, Handle, Interpolation,
Sampling, StorageAccess, StorageClass, Type, UnaryOperator,
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -214,6 +214,14 @@ impl ParameterQualifier {
_ => false,
}
}
+
+ /// Converts from a parameter qualifier into a [`ExprPos`](ExprPos)
+ pub fn as_pos(&self) -> ExprPos {
+ match *self {
+ ParameterQualifier::Out | ParameterQualifier::InOut => ExprPos::Lhs,
+ _ => ExprPos::Rhs,
+ }
+ }
}
/// The glsl profile used by a shader
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -15,6 +15,28 @@ use crate::{
};
use std::{convert::TryFrom, ops::Index};
+/// The position at which an expression is, used while lowering
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum ExprPos {
+ /// The expression is in the left hand side of an assignment
+ Lhs,
+ /// The expression is in the right hand side of an assignment
+ Rhs,
+ /// The expression is an array being indexed, needed to allow constant
+ /// arrays to be dinamically indexed
+ ArrayBase,
+}
+
+impl ExprPos {
+ /// Returns an lhs position if the current position is lhs otherwise ArrayBase
+ fn maybe_array_base(&self) -> Self {
+ match *self {
+ ExprPos::Lhs => *self,
+ _ => ExprPos::ArrayBase,
+ }
+ }
+}
+
#[derive(Debug)]
pub struct Context {
pub expressions: Arena<Expression>,
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -323,10 +345,10 @@ impl Context {
mut stmt: StmtContext,
parser: &mut Parser,
expr: Handle<HirExpr>,
- lhs: bool,
+ pos: ExprPos,
body: &mut Block,
) -> Result<(Option<Handle<Expression>>, SourceMetadata)> {
- let res = self.lower_inner(&stmt, parser, expr, lhs, body);
+ let res = self.lower_inner(&stmt, parser, expr, pos, body);
stmt.hir_exprs.clear();
self.stmt_ctx = Some(stmt);
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -344,10 +366,10 @@ impl Context {
mut stmt: StmtContext,
parser: &mut Parser,
expr: Handle<HirExpr>,
- lhs: bool,
+ pos: ExprPos,
body: &mut Block,
) -> Result<(Handle<Expression>, SourceMetadata)> {
- let res = self.lower_expect_inner(&stmt, parser, expr, lhs, body);
+ let res = self.lower_expect_inner(&stmt, parser, expr, pos, body);
stmt.hir_exprs.clear();
self.stmt_ctx = Some(stmt);
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -365,10 +387,10 @@ impl Context {
stmt: &StmtContext,
parser: &mut Parser,
expr: Handle<HirExpr>,
- lhs: bool,
+ pos: ExprPos,
body: &mut Block,
) -> Result<(Handle<Expression>, SourceMetadata)> {
- let (maybe_expr, meta) = self.lower_inner(stmt, parser, expr, lhs, body)?;
+ let (maybe_expr, meta) = self.lower_inner(stmt, parser, expr, pos, body)?;
let expr = match maybe_expr {
Some(e) => e,
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -389,16 +411,18 @@ impl Context {
stmt: &StmtContext,
parser: &mut Parser,
expr: Handle<HirExpr>,
- lhs: bool,
+ pos: ExprPos,
body: &mut Block,
) -> Result<(Option<Handle<Expression>>, SourceMetadata)> {
let HirExpr { ref kind, meta } = stmt.hir_exprs[expr];
let handle = match *kind {
HirExprKind::Access { base, index } => {
- let base = self.lower_expect_inner(stmt, parser, base, true, body)?.0;
+ let base = self
+ .lower_expect_inner(stmt, parser, base, pos.maybe_array_base(), body)?
+ .0;
let (index, index_meta) =
- self.lower_expect_inner(stmt, parser, index, false, body)?;
+ self.lower_expect_inner(stmt, parser, index, ExprPos::Rhs, body)?;
let pointer = parser
.solve_constant(self, index, index_meta)
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -427,7 +451,7 @@ impl Context {
self.add_expression(Expression::Access { base, index }, meta, body)
});
- if !lhs {
+ if ExprPos::Rhs == pos {
let resolved = parser.resolve_type(self, pointer, meta)?;
if resolved.pointer_class().is_some() {
return Ok((
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -440,18 +464,18 @@ impl Context {
pointer
}
HirExprKind::Select { base, ref field } => {
- let base = self.lower_expect_inner(stmt, parser, base, lhs, body)?.0;
+ let base = self.lower_expect_inner(stmt, parser, base, pos, body)?.0;
- parser.field_selection(self, lhs, body, base, field, meta)?
+ parser.field_selection(self, ExprPos::Lhs == pos, body, base, field, meta)?
}
- HirExprKind::Constant(constant) if !lhs => {
+ HirExprKind::Constant(constant) if pos == ExprPos::Rhs => {
self.add_expression(Expression::Constant(constant), meta, body)
}
- HirExprKind::Binary { left, op, right } if !lhs => {
+ HirExprKind::Binary { left, op, right } if pos == ExprPos::Rhs => {
let (mut left, left_meta) =
- self.lower_expect_inner(stmt, parser, left, false, body)?;
+ self.lower_expect_inner(stmt, parser, left, pos, body)?;
let (mut right, right_meta) =
- self.lower_expect_inner(stmt, parser, right, false, body)?;
+ self.lower_expect_inner(stmt, parser, right, pos, body)?;
match op {
BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => self
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -543,14 +567,14 @@ impl Context {
_ => self.add_expression(Expression::Binary { left, op, right }, meta, body),
}
}
- HirExprKind::Unary { op, expr } if !lhs => {
- let expr = self.lower_expect_inner(stmt, parser, expr, false, body)?.0;
+ HirExprKind::Unary { op, expr } if pos == ExprPos::Rhs => {
+ let expr = self.lower_expect_inner(stmt, parser, expr, pos, body)?.0;
self.add_expression(Expression::Unary { op, expr }, meta, body)
}
HirExprKind::Variable(ref var) => {
- if lhs {
- if !var.mutable {
+ if pos != ExprPos::Rhs {
+ if !var.mutable && ExprPos::Lhs == pos {
parser.errors.push(Error {
kind: ErrorKind::SemanticError(
"Variable cannot be used in LHS position".into(),
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -566,7 +590,7 @@ impl Context {
var.expr
}
}
- HirExprKind::Call(ref call) if !lhs => {
+ HirExprKind::Call(ref call) if pos != ExprPos::Lhs => {
let maybe_expr = parser.function_or_constructor_call(
self,
stmt,
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -581,14 +605,14 @@ impl Context {
condition,
accept,
reject,
- } if !lhs => {
+ } if ExprPos::Lhs != pos => {
let condition = self
- .lower_expect_inner(stmt, parser, condition, false, body)?
+ .lower_expect_inner(stmt, parser, condition, ExprPos::Rhs, body)?
.0;
let (mut accept, accept_meta) =
- self.lower_expect_inner(stmt, parser, accept, false, body)?;
+ self.lower_expect_inner(stmt, parser, accept, pos, body)?;
let (mut reject, reject_meta) =
- self.lower_expect_inner(stmt, parser, reject, false, body)?;
+ self.lower_expect_inner(stmt, parser, reject, pos, body)?;
self.binary_implicit_conversion(
parser,
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -608,10 +632,11 @@ impl Context {
body,
)
}
- HirExprKind::Assign { tgt, value } if !lhs => {
- let (pointer, ptr_meta) = self.lower_expect_inner(stmt, parser, tgt, true, body)?;
+ HirExprKind::Assign { tgt, value } if ExprPos::Lhs != pos => {
+ let (pointer, ptr_meta) =
+ self.lower_expect_inner(stmt, parser, tgt, ExprPos::Lhs, body)?;
let (mut value, value_meta) =
- self.lower_expect_inner(stmt, parser, value, false, body)?;
+ self.lower_expect_inner(stmt, parser, value, ExprPos::Rhs, body)?;
let scalar_components = self.expr_scalar_components(parser, pointer, ptr_meta)?;
diff --git a/src/front/glsl/context.rs b/src/front/glsl/context.rs
--- a/src/front/glsl/context.rs
+++ b/src/front/glsl/context.rs
@@ -686,7 +711,9 @@ impl Context {
false => BinaryOperator::Subtract,
};
- let pointer = self.lower_expect_inner(stmt, parser, expr, true, body)?.0;
+ let pointer = self
+ .lower_expect_inner(stmt, parser, expr, ExprPos::Lhs, body)?
+ .0;
let left = self.add_expression(Expression::Load { pointer }, meta, body);
let uint = match parser.resolve_type(self, left, meta)?.scalar_kind() {
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -1,7 +1,7 @@
use super::{
ast::*,
builtins::{inject_builtin, inject_double_builtin, sampled_to_depth},
- context::{Context, StmtContext},
+ context::{Context, ExprPos, StmtContext},
error::{Error, ErrorKind},
types::scalar_components,
Parser, Result, SourceMetadata,
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -48,7 +48,7 @@ impl Parser {
) -> Result<Option<Handle<Expression>>> {
let args: Vec<_> = raw_args
.iter()
- .map(|e| ctx.lower_expect_inner(stmt, self, *e, false, body))
+ .map(|e| ctx.lower_expect_inner(stmt, self, *e, ExprPos::Rhs, body))
.collect::<Result<_>>()?;
match fc {
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -565,7 +565,7 @@ impl Parser {
.zip(raw_args.iter().zip(parameters.iter()))
{
let (mut handle, meta) =
- ctx.lower_expect_inner(stmt, self, *expr, parameter_info.qualifier.is_lhs(), body)?;
+ ctx.lower_expect_inner(stmt, self, *expr, parameter_info.qualifier.as_pos(), body)?;
if let TypeInner::Vector { size, kind, width } =
*self.resolve_type(ctx, handle, meta)?
diff --git a/src/front/glsl/functions.rs b/src/front/glsl/functions.rs
--- a/src/front/glsl/functions.rs
+++ b/src/front/glsl/functions.rs
@@ -638,7 +638,9 @@ impl Parser {
ctx.emit_start();
for (tgt, pointer) in proxy_writes {
let value = ctx.add_expression(Expression::Load { pointer }, meta, body);
- let target = ctx.lower_expect_inner(stmt, self, tgt, true, body)?.0;
+ let target = ctx
+ .lower_expect_inner(stmt, self, tgt, ExprPos::Rhs, body)?
+ .0;
ctx.emit_flush(body);
body.push(
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -1,6 +1,6 @@
use super::{
ast::{FunctionKind, Profile, TypeQualifier},
- context::Context,
+ context::{Context, ExprPos},
error::ExpectedToken,
error::{Error, ErrorKind},
lex::{Lexer, LexerResultKind},
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -199,7 +199,7 @@ impl<'source> ParsingContext<'source> {
let mut stmt_ctx = ctx.stmt_ctx();
let expr = self.parse_conditional(parser, &mut ctx, &mut stmt_ctx, &mut block, None)?;
- let (root, meta) = ctx.lower_expect(stmt_ctx, parser, expr, false, &mut block)?;
+ let (root, meta) = ctx.lower_expect(stmt_ctx, parser, expr, ExprPos::Rhs, &mut block)?;
Ok((parser.solve_constant(&ctx, root, meta)?, meta))
}
diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs
--- a/src/front/glsl/parser/declarations.rs
+++ b/src/front/glsl/parser/declarations.rs
@@ -4,7 +4,7 @@ use crate::{
GlobalLookup, GlobalLookupKind, Precision, StorageQualifier, StructLayout,
TypeQualifier,
},
- context::Context,
+ context::{Context, ExprPos},
error::ExpectedToken,
offset,
token::{Token, TokenValue},
diff --git a/src/front/glsl/parser/declarations.rs b/src/front/glsl/parser/declarations.rs
--- a/src/front/glsl/parser/declarations.rs
+++ b/src/front/glsl/parser/declarations.rs
@@ -103,7 +103,7 @@ impl<'source> ParsingContext<'source> {
} else {
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_assignment(parser, ctx, &mut stmt, body)?;
- let (mut init, init_meta) = ctx.lower_expect(stmt, parser, expr, false, body)?;
+ let (mut init, init_meta) = ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?;
let scalar_components = scalar_components(&parser.module.types[ty].inner);
if let Some((kind, width)) = scalar_components {
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -1,3 +1,4 @@
+use crate::front::glsl::context::ExprPos;
use crate::front::glsl::SourceMetadata;
use crate::{
front::glsl::{
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -77,7 +78,8 @@ impl<'source> ParsingContext<'source> {
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
self.expect(parser, TokenValue::Semicolon)?;
- let (handle, meta) = ctx.lower_expect(stmt, parser, expr, false, body)?;
+ let (handle, meta) =
+ ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?;
(Some(handle), meta)
}
};
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -99,7 +101,8 @@ impl<'source> ParsingContext<'source> {
let condition = {
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
- let (handle, more_meta) = ctx.lower_expect(stmt, parser, expr, false, body)?;
+ let (handle, more_meta) =
+ ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?;
meta = meta.union(&more_meta);
handle
};
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -139,7 +142,7 @@ impl<'source> ParsingContext<'source> {
let selector = {
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
- ctx.lower_expect(stmt, parser, expr, false, body)?.0
+ ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?.0
};
self.expect(parser, TokenValue::RightParen)?;
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -158,7 +161,7 @@ impl<'source> ParsingContext<'source> {
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
let (root, meta) =
- ctx.lower_expect(stmt, parser, expr, false, body)?;
+ ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?;
let constant = parser.solve_constant(ctx, root, meta)?;
match parser.module.constants[constant].inner {
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -287,7 +290,7 @@ impl<'source> ParsingContext<'source> {
let meta = meta.union(&self.expect(parser, TokenValue::RightParen)?.meta);
let (expr, expr_meta) =
- ctx.lower_expect(stmt, parser, root, false, &mut loop_body)?;
+ ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?;
let condition = ctx.add_expression(
Expression::Unary {
op: UnaryOperator::Not,
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -340,7 +343,7 @@ impl<'source> ParsingContext<'source> {
let meta = start_meta.union(&end_meta);
let (expr, expr_meta) =
- ctx.lower_expect(stmt, parser, root, false, &mut loop_body)?;
+ ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?;
let condition = ctx.add_expression(
Expression::Unary {
op: UnaryOperator::Not,
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -383,7 +386,7 @@ impl<'source> ParsingContext<'source> {
} else {
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
- ctx.lower(stmt, parser, expr, false, body)?;
+ ctx.lower(stmt, parser, expr, ExprPos::Rhs, body)?;
self.expect(parser, TokenValue::Semicolon)?;
}
}
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -422,7 +425,7 @@ impl<'source> ParsingContext<'source> {
} else {
let mut stmt = ctx.stmt_ctx();
let root = self.parse_expression(parser, ctx, &mut stmt, &mut block)?;
- ctx.lower_expect(stmt, parser, root, false, &mut block)?
+ ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut block)?
};
let condition = ctx.add_expression(
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -455,7 +458,7 @@ impl<'source> ParsingContext<'source> {
let mut stmt = ctx.stmt_ctx();
let rest =
self.parse_expression(parser, ctx, &mut stmt, &mut continuing)?;
- ctx.lower(stmt, parser, rest, false, &mut continuing)?;
+ ctx.lower(stmt, parser, rest, ExprPos::Rhs, &mut continuing)?;
}
}
diff --git a/src/front/glsl/parser/functions.rs b/src/front/glsl/parser/functions.rs
--- a/src/front/glsl/parser/functions.rs
+++ b/src/front/glsl/parser/functions.rs
@@ -504,7 +507,7 @@ impl<'source> ParsingContext<'source> {
| TokenValue::FloatConstant(_) => {
let mut stmt = ctx.stmt_ctx();
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
- ctx.lower(stmt, parser, expr, false, body)?;
+ ctx.lower(stmt, parser, expr, ExprPos::Rhs, body)?;
self.expect(parser, TokenValue::Semicolon)?.meta
}
TokenValue::Semicolon => self.bump(parser)?.meta,
|
diff --git a/src/front/glsl/parser_tests.rs b/src/front/glsl/parser_tests.rs
--- a/src/front/glsl/parser_tests.rs
+++ b/src/front/glsl/parser_tests.rs
@@ -812,4 +812,19 @@ fn expressions() {
"#,
)
.unwrap();
+
+ // Dynamic indexing of array
+ parser
+ .parse(
+ &Options::from(ShaderStage::Vertex),
+ r#"
+ # version 450
+ void main() {
+ const vec4 positions[1] = { vec4(0) };
+
+ gl_Position = positions[gl_VertexIndex];
+ }
+ "#,
+ )
+ .unwrap();
}
|
[glsl-in] cannot index into const array
The following:
```glsl
#version 450
void main() {
const vec2 positions[3] = {
vec2(0, 0.5),
vec2(-0.5, -0.5),
vec2(0.5, -0.5)
};
gl_Position = vec4(positions[gl_VertexIndex], 0, 1);
}
```
produces the error (naga 0.6.0):
```
ERROR: Variable cannot be used in LHS position
--> shaders/basic.vert line 10:24-33
| gl_Position = vec4(positions[gl_VertexIndex], 0, 1);
^^^^^^^^^
```
I wouldn't expect this to throw an error since it is allowed by `glslangValidator`. Though, if the `const` is removed, the shader compiles successfully.
The issue seems to originate from [here](https://github.com/gfx-rs/naga/blob/4e181d6af4b758c11482b633b3a54b58bfbd4a59/src/front/glsl/context.rs#L556) where `lhs` is incorrectly set to `true` (the `position` variable is obviously only used in the RHS of the expression).
|
2021-08-20T05:16:22Z
|
0.6
|
2021-08-19T23:59:48Z
|
2e7d629aefe6857ade4f96fe2c3dc1a09f0fa4db
|
[
"front::glsl::parser_tests::expressions"
] |
[
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"back::msl::test_error_size",
"arena::tests::fetch_or_append_unique",
"front::glsl::parser_tests::declarations",
"back::spv::writer::test_write_physical_layout",
"front::glsl::parser_tests::function_overloading",
"back::spv::layout::test_physical_layout_in_words",
"back::msl::writer::test_stack_size",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::cast",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::implicit_conversions",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::parser_tests::functions",
"front::glsl::constants::tests::unary_op",
"front::spv::test::parse",
"front::wgsl::tests::parse_array_length",
"front::glsl::parser_tests::constants",
"front::wgsl::lexer::test_tokens",
"front::wgsl::tests::parse_expressions",
"front::wgsl::lexer::test_variable_decl",
"front::glsl::parser_tests::swizzles",
"front::glsl::constants::tests::access",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_pointers",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::structs",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_switch",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_types",
"front::wgsl::type_inner_tests::to_wgsl",
"proc::test_matrix_size",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_storage_buffers",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_type_cast",
"convert_spv_pointer_access",
"convert_spv_quad_vert",
"convert_spv_shadow",
"convert_glsl_folder",
"convert_wgsl",
"function_without_identifier",
"inconsistent_binding",
"bad_for_initializer",
"bad_texture_sample_type",
"bad_type_cast",
"invalid_scalar_width",
"invalid_float",
"invalid_texture_sample_type",
"invalid_integer",
"local_var_missing_type",
"let_type_mismatch",
"invalid_structs",
"bad_texture",
"local_var_type_mismatch",
"invalid_arrays",
"invalid_functions",
"struct_member_zero_align",
"unknown_attribute",
"invalid_access",
"unknown_conservative_depth",
"struct_member_zero_size",
"unknown_access",
"invalid_local_vars",
"unknown_built_in",
"unknown_shader_stage",
"unknown_type",
"unknown_storage_class",
"unknown_ident",
"unknown_identifier",
"zero_array_stride",
"negative_index",
"missing_bindings",
"unknown_scalar_type",
"unknown_storage_format",
"valid_access",
"unknown_local_function",
"src/front/glsl/mod.rs - front::glsl::Options (line 38)",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 17)",
"src/front/glsl/token.rs - front::glsl::token::SourceMetadata (line 26)",
"src/front/glsl/mod.rs - front::glsl::Parser (line 136)"
] |
[] |
[] |
|
gfx-rs/naga
| 546
|
gfx-rs__naga-546
|
[
"542"
] |
50e5904addf8d5e1d486a26a0464914d978d5d1b
|
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -22,6 +22,7 @@ thiserror = "1.0.21"
serde = { version = "1.0", features = ["derive"], optional = true }
petgraph = { version ="0.5", optional = true }
pp-rs = { git = "https://github.com/Kangz/glslpp-rs", rev = "4f2f72a", optional = true }
+#env_logger = "0.8" # uncomment temporarily for developing with `convert`
[features]
default = []
diff --git a/bin/convert.rs b/bin/convert.rs
--- a/bin/convert.rs
+++ b/bin/convert.rs
@@ -39,6 +39,8 @@ impl<T, E: Error> PrettyResult for Result<T, E> {
}
fn main() {
+ //env_logger::init(); // uncomment during development
+
let mut input_path = None;
let mut output_path = None;
//TODO: read the parameters from RON?
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -538,11 +538,21 @@ impl<'a, W: Write> Writer<'a, W> {
fn write_type(&mut self, ty: Handle<Type>) -> BackendResult {
match self.module.types[ty].inner {
// Scalars are simple we just get the full name from `glsl_scalar`
- TypeInner::Scalar { kind, width } => {
- write!(self.out, "{}", glsl_scalar(kind, width)?.full)?
- }
+ TypeInner::Scalar { kind, width }
+ | TypeInner::ValuePointer {
+ size: None,
+ kind,
+ width,
+ class: _,
+ } => write!(self.out, "{}", glsl_scalar(kind, width)?.full)?,
// Vectors are just `gvecN` where `g` is the scalar prefix and `N` is the vector size
- TypeInner::Vector { size, kind, width } => write!(
+ TypeInner::Vector { size, kind, width }
+ | TypeInner::ValuePointer {
+ size: Some(size),
+ kind,
+ width,
+ class: _,
+ } => write!(
self.out,
"{}vec{}",
glsl_scalar(kind, width)?.prefix,
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1250,14 +1260,24 @@ impl<'a, W: Write> Writer<'a, W> {
Expression::AccessIndex { base, index } => {
self.write_expr(base, ctx)?;
- match *ctx.typifier.get(base, &self.module.types) {
+ let mut resolved = ctx.typifier.get(base, &self.module.types);
+ let base_ty_handle = match *resolved {
+ TypeInner::Pointer { base, class: _ } => {
+ resolved = &self.module.types[base].inner;
+ Ok(base)
+ }
+ _ => ctx.typifier.get_handle(base),
+ };
+
+ match *resolved {
TypeInner::Vector { .. }
| TypeInner::Matrix { .. }
- | TypeInner::Array { .. } => write!(self.out, "[{}]", index)?,
+ | TypeInner::Array { .. }
+ | TypeInner::ValuePointer { .. } => write!(self.out, "[{}]", index)?,
TypeInner::Struct { .. } => {
// This will never panic in case the type is a `Struct`, this is not true
// for other types so we can only check while inside this match arm
- let ty = ctx.typifier.get_handle(base).unwrap();
+ let ty = base_ty_handle.unwrap();
write!(
self.out,
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -118,6 +118,20 @@ impl crate::StorageClass {
_ => false,
}
}
+
+ fn get_name(&self, global_use: GlobalUse) -> Option<&'static str> {
+ match *self {
+ Self::Input | Self::Output | Self::Handle => None,
+ Self::Uniform => Some("constant"),
+ //TODO: should still be "constant" for read-only buffers
+ Self::Storage => Some(if global_use.contains(GlobalUse::WRITE) {
+ "device"
+ } else {
+ "storage "
+ }),
+ Self::Private | Self::Function | Self::WorkGroup | Self::PushConstant => Some(""),
+ }
+ }
}
enum FunctionOrigin {
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -208,14 +222,21 @@ impl<W: Write> Writer<W> {
}
crate::Expression::AccessIndex { base, index } => {
self.put_expression(base, context)?;
- let resolved = self.typifier.get(base, &context.module.types);
+ let mut resolved = self.typifier.get(base, &context.module.types);
+ let base_ty_handle = match *resolved {
+ crate::TypeInner::Pointer { base, class: _ } => {
+ resolved = &context.module.types[base].inner;
+ Ok(base)
+ }
+ _ => self.typifier.get_handle(base),
+ };
match *resolved {
crate::TypeInner::Struct { .. } => {
- let base_ty = self.typifier.get_handle(base).unwrap();
+ let base_ty = base_ty_handle.unwrap();
let name = &self.names[&NameKey::StructMember(base_ty, index)];
write!(self.out, ".{}", name)?;
}
- crate::TypeInner::Vector { .. } => {
+ crate::TypeInner::ValuePointer { .. } | crate::TypeInner::Vector { .. } => {
write!(self.out, ".{}", COMPONENTS[index as usize])?;
}
crate::TypeInner::Matrix { .. } => {
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -852,6 +873,7 @@ impl<W: Write> Writer<W> {
fn write_type_defs(&mut self, module: &crate::Module) -> Result<(), Error> {
for (handle, ty) in module.types.iter() {
let name = &self.names[&NameKey::Type(handle)];
+ let global_use = GlobalUse::all(); //TODO
match ty.inner {
crate::TypeInner::Scalar { kind, .. } => {
write!(self.out, "typedef {} {}", scalar_kind_string(kind), name)?;
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -878,20 +900,51 @@ impl<W: Write> Writer<W> {
)?;
}
crate::TypeInner::Pointer { base, class } => {
- use crate::StorageClass as Sc;
let base_name = &self.names[&NameKey::Type(base)];
- let class_name = match class {
- Sc::Input | Sc::Output => continue,
- Sc::Uniform => "constant",
- Sc::Storage => "device",
- Sc::Handle
- | Sc::Private
- | Sc::Function
- | Sc::WorkGroup
- | Sc::PushConstant => "",
+ let class_name = match class.get_name(global_use) {
+ Some(name) => name,
+ None => continue,
};
write!(self.out, "typedef {} {} *{}", class_name, base_name, name)?;
}
+ crate::TypeInner::ValuePointer {
+ size: None,
+ kind,
+ width: _,
+ class,
+ } => {
+ let class_name = match class.get_name(global_use) {
+ Some(name) => name,
+ None => continue,
+ };
+ write!(
+ self.out,
+ "typedef {} {} *{}",
+ class_name,
+ scalar_kind_string(kind),
+ name
+ )?;
+ }
+ crate::TypeInner::ValuePointer {
+ size: Some(size),
+ kind,
+ width: _,
+ class,
+ } => {
+ let class_name = match class.get_name(global_use) {
+ Some(name) => name,
+ None => continue,
+ };
+ write!(
+ self.out,
+ "typedef {} {}::{}{} {}",
+ class_name,
+ NAMESPACE,
+ scalar_kind_string(kind),
+ vector_size_string(size),
+ name
+ )?;
+ }
crate::TypeInner::Array {
base,
size,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -82,14 +82,11 @@ impl Function {
#[derive(Debug, PartialEq, Hash, Eq, Copy, Clone)]
enum LocalType {
- Scalar {
- kind: crate::ScalarKind,
- width: crate::Bytes,
- },
- Vector {
- size: crate::VectorSize,
+ Value {
+ vector_size: Option<crate::VectorSize>,
kind: crate::ScalarKind,
width: crate::Bytes,
+ pointer_class: Option<crate::StorageClass>,
},
Matrix {
columns: crate::VectorSize,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -108,10 +105,18 @@ enum LocalType {
impl LocalType {
fn from_inner(inner: &crate::TypeInner) -> Option<Self> {
Some(match *inner {
- crate::TypeInner::Scalar { kind, width } => LocalType::Scalar { kind, width },
- crate::TypeInner::Vector { size, kind, width } => {
- LocalType::Vector { size, kind, width }
- }
+ crate::TypeInner::Scalar { kind, width } => LocalType::Value {
+ vector_size: None,
+ kind,
+ width,
+ pointer_class: None,
+ },
+ crate::TypeInner::Vector { size, kind, width } => LocalType::Value {
+ vector_size: Some(size),
+ kind,
+ width,
+ pointer_class: None,
+ },
crate::TypeInner::Matrix {
columns,
rows,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -122,6 +127,17 @@ impl LocalType {
width,
},
crate::TypeInner::Pointer { base, class } => LocalType::Pointer { base, class },
+ crate::TypeInner::ValuePointer {
+ size,
+ kind,
+ width,
+ class,
+ } => LocalType::Value {
+ vector_size: size,
+ kind,
+ width,
+ pointer_class: Some(class),
+ },
_ => return None,
})
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -302,26 +318,9 @@ impl Writer {
Ok(*e.get())
} else {
match lookup_ty {
- LookupType::Handle(handle) => match arena[handle].inner {
- crate::TypeInner::Scalar { kind, width } => self
- .get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width })),
- crate::TypeInner::Vector { size, kind, width } => self.get_type_id(
- arena,
- LookupType::Local(LocalType::Vector { size, kind, width }),
- ),
- crate::TypeInner::Matrix {
- columns,
- rows,
- width,
- } => self.get_type_id(
- arena,
- LookupType::Local(LocalType::Matrix {
- columns,
- rows,
- width,
- }),
- ),
- _ => self.write_type_declaration_arena(arena, handle),
+ LookupType::Handle(handle) => match LocalType::from_inner(&arena[handle].inner) {
+ Some(local) => self.get_type_id(arena, LookupType::Local(local)),
+ None => self.write_type_declaration_arena(arena, handle),
},
LookupType::Local(local_ty) => self.write_type_declaration_local(arena, local_ty),
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -364,13 +363,6 @@ impl Writer {
)
}
- fn create_pointer_type(&mut self, type_id: Word, class: spirv::StorageClass) -> Word {
- let id = self.generate_id();
- let instruction = Instruction::type_pointer(id, class, type_id);
- instruction.to_words(&mut self.logical_layout.declarations);
- id
- }
-
fn create_constant(&mut self, type_id: Word, value: &[Word]) -> Word {
let id = self.generate_id();
let instruction = Instruction::constant(type_id, id, value);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -607,10 +599,27 @@ impl Writer {
) -> Result<Word, Error> {
let id = self.generate_id();
let instruction = match local_ty {
- LocalType::Scalar { kind, width } => self.write_scalar(id, kind, width),
- LocalType::Vector { size, kind, width } => {
- let scalar_id =
- self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width }))?;
+ LocalType::Value {
+ vector_size: None,
+ kind,
+ width,
+ pointer_class: None,
+ } => self.write_scalar(id, kind, width),
+ LocalType::Value {
+ vector_size: Some(size),
+ kind,
+ width,
+ pointer_class: None,
+ } => {
+ let scalar_id = self.get_type_id(
+ arena,
+ LookupType::Local(LocalType::Value {
+ vector_size: None,
+ kind,
+ width,
+ pointer_class: None,
+ }),
+ )?;
Instruction::type_vector(id, scalar_id, size)
}
LocalType::Matrix {
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -620,16 +629,35 @@ impl Writer {
} => {
let vector_id = self.get_type_id(
arena,
- LookupType::Local(LocalType::Vector {
- size: rows,
+ LookupType::Local(LocalType::Value {
+ vector_size: Some(rows),
kind: crate::ScalarKind::Float,
width,
+ pointer_class: None,
}),
)?;
Instruction::type_matrix(id, vector_id, columns)
}
- LocalType::Pointer { .. } => {
- return Err(Error::FeatureNotImplemented("pointer declaration"))
+ LocalType::Pointer { base, class } => {
+ let type_id = self.get_type_id(arena, LookupType::Handle(base))?;
+ Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id)
+ }
+ LocalType::Value {
+ vector_size,
+ kind,
+ width,
+ pointer_class: Some(class),
+ } => {
+ let type_id = self.get_type_id(
+ arena,
+ LookupType::Local(LocalType::Value {
+ vector_size,
+ kind,
+ width,
+ pointer_class: None,
+ }),
+ )?;
+ Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id)
}
LocalType::SampledImage { image_type } => {
let image_type_id = self.get_type_id(arena, LookupType::Handle(image_type))?;
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -658,15 +686,34 @@ impl Writer {
let instruction = match ty.inner {
crate::TypeInner::Scalar { kind, width } => {
- self.lookup_type
- .insert(LookupType::Local(LocalType::Scalar { kind, width }), id);
+ self.lookup_type.insert(
+ LookupType::Local(LocalType::Value {
+ vector_size: None,
+ kind,
+ width,
+ pointer_class: None,
+ }),
+ id,
+ );
self.write_scalar(id, kind, width)
}
crate::TypeInner::Vector { size, kind, width } => {
- let scalar_id =
- self.get_type_id(arena, LookupType::Local(LocalType::Scalar { kind, width }))?;
+ let scalar_id = self.get_type_id(
+ arena,
+ LookupType::Local(LocalType::Value {
+ vector_size: None,
+ kind,
+ width,
+ pointer_class: None,
+ }),
+ )?;
self.lookup_type.insert(
- LookupType::Local(LocalType::Vector { size, kind, width }),
+ LookupType::Local(LocalType::Value {
+ vector_size: Some(size),
+ kind,
+ width,
+ pointer_class: None,
+ }),
id,
);
Instruction::type_vector(id, scalar_id, size)
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -678,10 +725,11 @@ impl Writer {
} => {
let vector_id = self.get_type_id(
arena,
- LookupType::Local(LocalType::Vector {
- size: columns,
+ LookupType::Local(LocalType::Value {
+ vector_size: Some(columns),
kind: crate::ScalarKind::Float,
width,
+ pointer_class: None,
}),
)?;
self.lookup_type.insert(
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -699,19 +747,16 @@ impl Writer {
arrayed,
class,
} => {
- let width = 4;
- let local_type = match class {
- crate::ImageClass::Sampled { kind, multi: _ } => {
- LocalType::Scalar { kind, width }
- }
- crate::ImageClass::Depth => LocalType::Scalar {
- kind: crate::ScalarKind::Float,
- width,
- },
- crate::ImageClass::Storage(format) => LocalType::Scalar {
- kind: format.into(),
- width,
- },
+ let kind = match class {
+ crate::ImageClass::Sampled { kind, multi: _ } => kind,
+ crate::ImageClass::Depth => crate::ScalarKind::Float,
+ crate::ImageClass::Storage(format) => format.into(),
+ };
+ let local_type = LocalType::Value {
+ vector_size: None,
+ kind,
+ width: 4,
+ pointer_class: None,
};
let type_id = self.get_type_id(arena, LookupType::Local(local_type))?;
let dim = map_dim(dim);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -820,6 +865,32 @@ impl Writer {
.insert(LookupType::Local(LocalType::Pointer { base, class }), id);
Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id)
}
+ crate::TypeInner::ValuePointer {
+ size,
+ kind,
+ width,
+ class,
+ } => {
+ let type_id = self.get_type_id(
+ arena,
+ LookupType::Local(LocalType::Value {
+ vector_size: size,
+ kind,
+ width,
+ pointer_class: None,
+ }),
+ )?;
+ self.lookup_type.insert(
+ LookupType::Local(LocalType::Value {
+ vector_size: size,
+ kind,
+ width,
+ pointer_class: Some(class),
+ }),
+ id,
+ );
+ Instruction::type_pointer(id, self.parse_to_spirv_storage_class(class), type_id)
+ }
};
self.lookup_type.insert(LookupType::Handle(handle), id);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -837,9 +908,11 @@ impl Writer {
crate::ConstantInner::Scalar { width, ref value } => {
let type_id = self.get_type_id(
types,
- LookupType::Local(LocalType::Scalar {
+ LookupType::Local(LocalType::Value {
+ vector_size: None,
kind: value.scalar_kind(),
width,
+ pointer_class: None,
}),
)?;
let (solo, pair);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1061,9 +1134,11 @@ impl Writer {
Ok(if let Some(array_index) = array_index {
let coordinate_scalar_type_id = self.get_type_id(
&ir_module.types,
- LookupType::Local(LocalType::Scalar {
+ LookupType::Local(LocalType::Value {
+ vector_size: None,
kind: crate::ScalarKind::Float,
width: 4,
+ pointer_class: None,
}),
)?;
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1109,10 +1184,11 @@ impl Writer {
let extended_coordinate_type_id = self.get_type_id(
&ir_module.types,
- LookupType::Local(LocalType::Vector {
- size,
+ LookupType::Local(LocalType::Value {
+ vector_size: Some(size),
kind: crate::ScalarKind::Float,
width: 4,
+ pointer_class: None,
}),
)?;
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1757,6 +1833,7 @@ impl Writer {
Err(inner) => LookupType::Local(LocalType::from_inner(inner).unwrap()),
};
let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?;
+
self.temp_chain.clear();
let (root_id, class) = loop {
expr_handle = match ir_function.expressions[expr_handle] {
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1768,9 +1845,11 @@ impl Writer {
crate::Expression::AccessIndex { base, index } => {
let const_ty_id = self.get_type_id(
&ir_module.types,
- LookupType::Local(LocalType::Scalar {
+ LookupType::Local(LocalType::Value {
+ vector_size: None,
kind: crate::ScalarKind::Sint,
width: 4,
+ pointer_class: None,
}),
)?;
let const_id = self.create_constant(const_ty_id, &[index]);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1794,9 +1873,8 @@ impl Writer {
} else {
self.temp_chain.reverse();
let id = self.generate_id();
- let pointer_type_id = self.create_pointer_type(result_type_id, class);
block.body.push(Instruction::access_chain(
- pointer_type_id,
+ result_type_id,
id,
root_id,
&self.temp_chain,
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -5,12 +5,13 @@ pomelo! {
%include {
use super::super::{error::ErrorKind, token::*, ast::*};
use crate::{
+ BOOL_WIDTH,
Arena, BinaryOperator, Binding, Block, Constant,
ConstantInner, Expression,
Function, GlobalVariable, Handle, Interpolation,
LocalVariable, ScalarValue, ScalarKind,
Statement, StorageAccess, StorageClass, StructMember,
- SwitchCase, Type, TypeInner, UnaryOperator, FunctionArgument
+ SwitchCase, Type, TypeInner, UnaryOperator, FunctionArgument,
};
use pp_rs::token::PreprocessorError;
}
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -212,7 +213,7 @@ pomelo! {
name: None,
specialization: None,
inner: ConstantInner::Scalar {
- width: 1,
+ width: BOOL_WIDTH,
value: ScalarValue::Bool(b.1)
},
});
diff --git a/src/front/mod.rs b/src/front/mod.rs
--- a/src/front/mod.rs
+++ b/src/front/mod.rs
@@ -32,3 +32,13 @@ impl Emitter {
}
}
}
+
+#[allow(dead_code)]
+impl super::ConstantInner {
+ fn boolean(value: bool) -> Self {
+ Self::Scalar {
+ width: super::BOOL_WIDTH,
+ value: super::ScalarValue::Bool(value),
+ }
+ }
+}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2000,7 +2000,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
let id = self.next()?;
let inner = crate::TypeInner::Scalar {
kind: crate::ScalarKind::Bool,
- width: 1,
+ width: crate::BOOL_WIDTH,
};
self.lookup_type.insert(
id,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2608,10 +2608,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
handle: module.constants.append(crate::Constant {
name: self.future_decor.remove(&id).and_then(|dec| dec.name),
specialization: None, //TODO
- inner: crate::ConstantInner::Scalar {
- width: 1,
- value: crate::ScalarValue::Bool(value),
- },
+ inner: crate::ConstantInner::boolean(value),
}),
type_id,
},
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -136,6 +136,8 @@ pub enum Error<'a> {
InvalidResolve(ResolveError),
#[error("invalid statement {0:?}, expected {1}")]
InvalidStatement(crate::Statement, &'a str),
+ #[error("resource type {0:?} is invalid")]
+ InvalidResourceType(Handle<crate::Type>),
#[error("unknown import: `{0}`")]
UnknownImport(&'a str),
#[error("unknown storage class: `{0}`")]
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -170,6 +172,8 @@ pub enum Error<'a> {
FunctionRedefinition(&'a str),
#[error("call to local `{0}(..)` can't be resolved")]
UnknownLocalFunction(&'a str),
+ #[error("builtin {0:?} is not implemented")]
+ UnimplementedBuiltin(crate::BuiltIn),
#[error("other error")]
Other,
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -343,6 +347,23 @@ impl Composition {
}
}
+ fn extract(
+ base: Handle<crate::Expression>,
+ base_size: crate::VectorSize,
+ name: &str,
+ name_span: Range<usize>,
+ ) -> Result<crate::Expression, Error> {
+ let ch = name
+ .chars()
+ .next()
+ .ok_or_else(|| Error::BadAccessor(name_span.clone()))?;
+ let index = Self::letter_pos(ch);
+ if index >= base_size as u32 {
+ return Err(Error::BadAccessor(name_span));
+ }
+ Ok(crate::Expression::AccessIndex { base, index })
+ }
+
fn make<'a>(
base: Handle<crate::Expression>,
base_size: crate::VectorSize,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -350,7 +371,7 @@ impl Composition {
name_span: Range<usize>,
expressions: &mut Arena<crate::Expression>,
) -> Result<Self, Error<'a>> {
- Ok(if name.len() > 1 {
+ if name.len() > 1 {
let mut components = Vec::with_capacity(name.len());
for ch in name.chars() {
let index = Self::letter_pos(ch);
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -367,18 +388,10 @@ impl Composition {
4 => crate::VectorSize::Quad,
_ => return Err(Error::BadAccessor(name_span)),
};
- Composition::Multi(size, components)
+ Ok(Composition::Multi(size, components))
} else {
- let ch = name
- .chars()
- .next()
- .ok_or_else(|| Error::BadAccessor(name_span.clone()))?;
- let index = Self::letter_pos(ch);
- if index >= base_size as u32 {
- return Err(Error::BadAccessor(name_span));
- }
- Composition::Single(crate::Expression::AccessIndex { base, index })
- })
+ Self::extract(base, base_size, name, name_span).map(Composition::Single)
+ }
}
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -894,14 +907,8 @@ impl Parser {
) -> Result<Handle<crate::Constant>, Error<'a>> {
self.scopes.push(Scope::ConstantExpr);
let inner = match first_token_span {
- (Token::Word("true"), _) => crate::ConstantInner::Scalar {
- width: 1,
- value: crate::ScalarValue::Bool(true),
- },
- (Token::Word("false"), _) => crate::ConstantInner::Scalar {
- width: 1,
- value: crate::ScalarValue::Bool(false),
- },
+ (Token::Word("true"), _) => crate::ConstantInner::boolean(true),
+ (Token::Word("false"), _) => crate::ConstantInner::boolean(false),
(
Token::Number {
ref value,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1070,10 +1077,19 @@ impl Parser {
};
loop {
// insert the E::Load when we reach a value
- if needs_deref && ctx.resolve_type(handle)?.scalar_kind().is_some() {
- let expression = crate::Expression::Load { pointer: handle };
- handle = ctx.expressions.append(expression);
- needs_deref = false;
+ if needs_deref {
+ let now = match *ctx.resolve_type(handle)? {
+ crate::TypeInner::Pointer { base, class: _ } => {
+ ctx.types[base].inner.scalar_kind().is_some()
+ }
+ crate::TypeInner::ValuePointer { .. } => true,
+ _ => false,
+ };
+ if now {
+ let expression = crate::Expression::Load { pointer: handle };
+ handle = ctx.expressions.append(expression);
+ needs_deref = false;
+ }
}
let expression = match lexer.peek().0 {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1133,6 +1149,30 @@ impl Parser {
}
Composition::Single(expr) => expr,
},
+ crate::TypeInner::ValuePointer {
+ size: Some(size), ..
+ } => Composition::extract(handle, size, name, name_span)?,
+ crate::TypeInner::Pointer { base, class: _ } => match ctx.types[base].inner
+ {
+ crate::TypeInner::Struct { ref members, .. } => {
+ let index = members
+ .iter()
+ .position(|m| m.name.as_deref() == Some(name))
+ .ok_or(Error::BadAccessor(name_span))?
+ as u32;
+ crate::Expression::AccessIndex {
+ base: handle,
+ index,
+ }
+ }
+ crate::TypeInner::Vector { size, .. } => {
+ Composition::extract(handle, size, name, name_span)?
+ }
+ crate::TypeInner::Matrix { columns, .. } => {
+ Composition::extract(handle, columns, name, name_span)?
+ }
+ _ => return Err(Error::BadAccessor(name_span)),
+ },
_ => return Err(Error::BadAccessor(name_span)),
}
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1470,7 +1510,7 @@ impl Parser {
},
"bool" => crate::TypeInner::Scalar {
kind: crate::ScalarKind::Bool,
- width: 1,
+ width: crate::BOOL_WIDTH,
},
"vec2" => {
let (kind, width) = lexer.next_scalar_generic()?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2453,18 +2493,29 @@ impl Parser {
Some(crate::Binding::BuiltIn(builtin)) => match builtin {
crate::BuiltIn::GlobalInvocationId => crate::StorageClass::Input,
crate::BuiltIn::Position => crate::StorageClass::Output,
- _ => unimplemented!(),
+ _ => return Err(Error::UnimplementedBuiltin(builtin)),
},
Some(crate::Binding::Resource { .. }) => {
match module.types[pvar.ty].inner {
crate::TypeInner::Struct { .. } if pvar.access.is_empty() => {
crate::StorageClass::Uniform
}
- crate::TypeInner::Struct { .. } => crate::StorageClass::Storage,
- _ => crate::StorageClass::Handle,
+ crate::TypeInner::Struct { .. }
+ | crate::TypeInner::Array { .. } => crate::StorageClass::Storage,
+ crate::TypeInner::Image { .. }
+ | crate::TypeInner::Sampler { .. } => crate::StorageClass::Handle,
+ ref other => {
+ log::error!("Resource type {:?}", other);
+ return Err(Error::InvalidResourceType(pvar.ty));
+ }
}
}
- _ => crate::StorageClass::Private,
+ _ => match module.types[pvar.ty].inner {
+ crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => {
+ crate::StorageClass::Handle
+ }
+ _ => crate::StorageClass::Private,
+ },
},
};
let var_handle = module.global_variables.append(crate::GlobalVariable {
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -53,6 +53,9 @@ use serde::Deserialize;
#[cfg(feature = "serialize")]
use serde::Serialize;
+/// Width of a boolean type, in bytes.
+pub const BOOL_WIDTH: Bytes = 1;
+
/// Hash map that is faster but not resilient to DoS attacks.
pub type FastHashMap<K, T> = HashMap<K, T, BuildHasherDefault<fxhash::FxHasher>>;
/// Hash set that is faster but not resilient to DoS attacks.
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -371,11 +374,18 @@ pub enum TypeInner {
rows: VectorSize,
width: Bytes,
},
- /// Pointer to a value.
+ /// Pointer to another type.
Pointer {
base: Handle<Type>,
class: StorageClass,
},
+ /// Pointer to a value.
+ ValuePointer {
+ size: Option<VectorSize>,
+ kind: ScalarKind,
+ width: Bytes,
+ class: StorageClass,
+ },
/// Homogenous list of elements.
Array {
base: Handle<Type>,
diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs
--- a/src/proc/layouter.rs
+++ b/src/proc/layouter.rs
@@ -62,7 +62,7 @@ impl Layouter {
size: (columns as u8 * rows as u8 * width) as u32,
alignment: Alignment::new((columns as u8 * width) as u32).unwrap(),
},
- Ti::Pointer { .. } => TypeLayout {
+ Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout {
size: 4,
alignment: Alignment::new(1).unwrap(),
},
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -11,26 +11,34 @@ enum Resolution {
// Clone is only implemented for numeric variants of `TypeInner`.
impl Clone for Resolution {
fn clone(&self) -> Self {
+ use crate::TypeInner as Ti;
match *self {
Resolution::Handle(handle) => Resolution::Handle(handle),
Resolution::Value(ref v) => Resolution::Value(match *v {
- crate::TypeInner::Scalar { kind, width } => {
- crate::TypeInner::Scalar { kind, width }
- }
- crate::TypeInner::Vector { size, kind, width } => {
- crate::TypeInner::Vector { size, kind, width }
- }
- crate::TypeInner::Matrix {
+ Ti::Scalar { kind, width } => Ti::Scalar { kind, width },
+ Ti::Vector { size, kind, width } => Ti::Vector { size, kind, width },
+ Ti::Matrix {
rows,
columns,
width,
- } => crate::TypeInner::Matrix {
+ } => Ti::Matrix {
rows,
columns,
width,
},
- #[allow(clippy::panic)]
- _ => panic!("Unexpected clone type: {:?}", v),
+ Ti::Pointer { base, class } => Ti::Pointer { base, class },
+ Ti::ValuePointer {
+ size,
+ kind,
+ width,
+ class,
+ } => Ti::ValuePointer {
+ size,
+ kind,
+ width,
+ class,
+ },
+ _ => unreachable!("Unexpected clone type: {:?}", v),
}),
}
}
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -44,8 +52,25 @@ pub struct Typifier {
#[derive(Clone, Debug, Error, PartialEq)]
pub enum ResolveError {
- #[error("Invalid index into array")]
- InvalidAccessIndex,
+ #[error("Index {index} is out of bounds for expression {expr:?}")]
+ OutOfBoundsIndex {
+ expr: Handle<crate::Expression>,
+ index: u32,
+ },
+ #[error("Invalid access into expression {expr:?}, indexed: {indexed}")]
+ InvalidAccess {
+ expr: Handle<crate::Expression>,
+ indexed: bool,
+ },
+ #[error("Invalid sub-access into type {ty:?}, indexed: {indexed}")]
+ InvalidSubAccess {
+ ty: Handle<crate::Type>,
+ indexed: bool,
+ },
+ #[error("Invalid pointer {0:?}")]
+ InvalidPointer(Handle<crate::Expression>),
+ #[error("Invalid image {0:?}")]
+ InvalidImage(Handle<crate::Expression>),
#[error("Function {name} not defined")]
FunctionNotDefined { name: String },
#[error("Function without return type")]
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -118,51 +143,74 @@ impl Typifier {
}
}
- //TODO: resolve `*Variable` and `Access*` expressions to `Pointer` type.
fn resolve_impl(
&self,
expr: &crate::Expression,
types: &Arena<crate::Type>,
ctx: &ResolveContext,
) -> Result<Resolution, ResolveError> {
+ use crate::TypeInner as Ti;
Ok(match *expr {
crate::Expression::Access { base, .. } => match *self.get(base, types) {
- crate::TypeInner::Array { base, .. } => Resolution::Handle(base),
- crate::TypeInner::Vector {
+ Ti::Array { base, .. } => Resolution::Handle(base),
+ Ti::Vector {
size: _,
kind,
width,
- } => Resolution::Value(crate::TypeInner::Scalar { kind, width }),
- crate::TypeInner::Matrix {
- rows: size,
- columns: _,
+ } => Resolution::Value(Ti::Scalar { kind, width }),
+ Ti::ValuePointer {
+ size: Some(_),
+ kind,
width,
- } => Resolution::Value(crate::TypeInner::Vector {
- size,
- kind: crate::ScalarKind::Float,
+ class,
+ } => Resolution::Value(Ti::ValuePointer {
+ size: None,
+ kind,
width,
+ class,
+ }),
+ Ti::Pointer { base, class } => Resolution::Value(match types[base].inner {
+ Ti::Array { base, .. } => Ti::Pointer { base, class },
+ Ti::Vector {
+ size: _,
+ kind,
+ width,
+ } => Ti::ValuePointer {
+ size: None,
+ kind,
+ width,
+ class,
+ },
+ ref other => {
+ log::error!("Access sub-type {:?}", other);
+ return Err(ResolveError::InvalidSubAccess {
+ ty: base,
+ indexed: false,
+ });
+ }
}),
ref other => {
- return Err(ResolveError::IncompatibleOperand {
- op: "access".to_string(),
- operand: format!("{:?}", other),
- })
+ log::error!("Access type {:?}", other);
+ return Err(ResolveError::InvalidAccess {
+ expr: base,
+ indexed: false,
+ });
}
},
crate::Expression::AccessIndex { base, index } => match *self.get(base, types) {
- crate::TypeInner::Vector { size, kind, width } => {
+ Ti::Vector { size, kind, width } => {
if index >= size as u32 {
- return Err(ResolveError::InvalidAccessIndex);
+ return Err(ResolveError::OutOfBoundsIndex { expr: base, index });
}
- Resolution::Value(crate::TypeInner::Scalar { kind, width })
+ Resolution::Value(Ti::Scalar { kind, width })
}
- crate::TypeInner::Matrix {
+ Ti::Matrix {
columns,
rows,
width,
} => {
if index >= columns as u32 {
- return Err(ResolveError::InvalidAccessIndex);
+ return Err(ResolveError::OutOfBoundsIndex { expr: base, index });
}
Resolution::Value(crate::TypeInner::Vector {
size: rows,
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -170,26 +218,94 @@ impl Typifier {
width,
})
}
- crate::TypeInner::Array { base, .. } => Resolution::Handle(base),
- crate::TypeInner::Struct {
+ Ti::Array { base, .. } => Resolution::Handle(base),
+ Ti::Struct {
block: _,
ref members,
} => {
let member = members
.get(index as usize)
- .ok_or(ResolveError::InvalidAccessIndex)?;
+ .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?;
Resolution::Handle(member.ty)
}
- ref other => {
- return Err(ResolveError::IncompatibleOperand {
- op: "access index".to_string(),
- operand: format!("{:?}", other),
+ Ti::ValuePointer {
+ size: Some(size),
+ kind,
+ width,
+ class,
+ } => {
+ if index >= size as u32 {
+ return Err(ResolveError::OutOfBoundsIndex { expr: base, index });
+ }
+ Resolution::Value(Ti::ValuePointer {
+ size: None,
+ kind,
+ width,
+ class,
})
}
+ Ti::Pointer {
+ base: ty_base,
+ class,
+ } => Resolution::Value(match types[ty_base].inner {
+ Ti::Array { base, .. } => Ti::Pointer { base, class },
+ Ti::Vector { size, kind, width } => {
+ if index >= size as u32 {
+ return Err(ResolveError::OutOfBoundsIndex { expr: base, index });
+ }
+ Ti::ValuePointer {
+ size: None,
+ kind,
+ width,
+ class,
+ }
+ }
+ Ti::Matrix {
+ rows,
+ columns,
+ width,
+ } => {
+ if index >= columns as u32 {
+ return Err(ResolveError::OutOfBoundsIndex { expr: base, index });
+ }
+ Ti::ValuePointer {
+ size: Some(rows),
+ kind: crate::ScalarKind::Float,
+ width,
+ class,
+ }
+ }
+ Ti::Struct {
+ block: _,
+ ref members,
+ } => {
+ let member = members
+ .get(index as usize)
+ .ok_or(ResolveError::OutOfBoundsIndex { expr: base, index })?;
+ Ti::Pointer {
+ base: member.ty,
+ class,
+ }
+ }
+ ref other => {
+ log::error!("Access index sub-type {:?}", other);
+ return Err(ResolveError::InvalidSubAccess {
+ ty: ty_base,
+ indexed: true,
+ });
+ }
+ }),
+ ref other => {
+ log::error!("Access index type {:?}", other);
+ return Err(ResolveError::InvalidAccess {
+ expr: base,
+ indexed: true,
+ });
+ }
},
crate::Expression::Constant(h) => match ctx.constants[h].inner {
crate::ConstantInner::Scalar { width, ref value } => {
- Resolution::Value(crate::TypeInner::Scalar {
+ Resolution::Value(Ti::Scalar {
kind: value.scalar_kind(),
width,
})
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -200,55 +316,89 @@ impl Typifier {
crate::Expression::FunctionArgument(index) => {
Resolution::Handle(ctx.arguments[index as usize].ty)
}
- crate::Expression::GlobalVariable(h) => Resolution::Handle(ctx.global_vars[h].ty),
- crate::Expression::LocalVariable(h) => Resolution::Handle(ctx.local_vars[h].ty),
- // we treat Load as a transparent operation for the type system
- crate::Expression::Load { pointer } => self.resolutions[pointer.index()].clone(),
+ crate::Expression::GlobalVariable(h) => {
+ let var = &ctx.global_vars[h];
+ if var.class == crate::StorageClass::Handle {
+ Resolution::Handle(var.ty)
+ } else {
+ Resolution::Value(Ti::Pointer {
+ base: var.ty,
+ class: var.class,
+ })
+ }
+ }
+ crate::Expression::LocalVariable(h) => {
+ let var = &ctx.local_vars[h];
+ Resolution::Value(Ti::Pointer {
+ base: var.ty,
+ class: crate::StorageClass::Function,
+ })
+ }
+ crate::Expression::Load { pointer } => match *self.get(pointer, types) {
+ Ti::Pointer { base, class: _ } => Resolution::Handle(base),
+ Ti::ValuePointer {
+ size,
+ kind,
+ width,
+ class: _,
+ } => Resolution::Value(match size {
+ Some(size) => Ti::Vector { size, kind, width },
+ None => Ti::Scalar { kind, width },
+ }),
+ ref other => {
+ log::error!("Pointer type {:?}", other);
+ return Err(ResolveError::InvalidPointer(pointer));
+ }
+ },
crate::Expression::ImageSample { image, .. }
| crate::Expression::ImageLoad { image, .. } => match *self.get(image, types) {
- crate::TypeInner::Image { class, .. } => Resolution::Value(match class {
- crate::ImageClass::Depth => crate::TypeInner::Scalar {
+ Ti::Image { class, .. } => Resolution::Value(match class {
+ crate::ImageClass::Depth => Ti::Scalar {
kind: crate::ScalarKind::Float,
width: 4,
},
- crate::ImageClass::Sampled { kind, multi: _ } => crate::TypeInner::Vector {
+ crate::ImageClass::Sampled { kind, multi: _ } => Ti::Vector {
kind,
width: 4,
size: crate::VectorSize::Quad,
},
- crate::ImageClass::Storage(format) => crate::TypeInner::Vector {
+ crate::ImageClass::Storage(format) => Ti::Vector {
kind: format.into(),
width: 4,
size: crate::VectorSize::Quad,
},
}),
- _ => unreachable!(),
+ ref other => {
+ log::error!("Image type {:?}", other);
+ return Err(ResolveError::InvalidImage(image));
+ }
},
crate::Expression::ImageQuery { image, query } => Resolution::Value(match query {
crate::ImageQuery::Size { level: _ } => match *self.get(image, types) {
- crate::TypeInner::Image { dim, .. } => match dim {
- crate::ImageDimension::D1 => crate::TypeInner::Scalar {
+ Ti::Image { dim, .. } => match dim {
+ crate::ImageDimension::D1 => Ti::Scalar {
kind: crate::ScalarKind::Sint,
width: 4,
},
- crate::ImageDimension::D2 => crate::TypeInner::Vector {
+ crate::ImageDimension::D2 => Ti::Vector {
size: crate::VectorSize::Bi,
kind: crate::ScalarKind::Sint,
width: 4,
},
- crate::ImageDimension::D3 | crate::ImageDimension::Cube => {
- crate::TypeInner::Vector {
- size: crate::VectorSize::Tri,
- kind: crate::ScalarKind::Sint,
- width: 4,
- }
- }
+ crate::ImageDimension::D3 | crate::ImageDimension::Cube => Ti::Vector {
+ size: crate::VectorSize::Tri,
+ kind: crate::ScalarKind::Sint,
+ width: 4,
+ },
},
- _ => unreachable!(),
+ ref other => {
+ log::error!("Image type {:?}", other);
+ return Err(ResolveError::InvalidImage(image));
+ }
},
crate::ImageQuery::NumLevels
| crate::ImageQuery::NumLayers
- | crate::ImageQuery::NumSamples => crate::TypeInner::Scalar {
+ | crate::ImageQuery::NumSamples => Ti::Scalar {
kind: crate::ScalarKind::Sint,
width: 4,
},
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -264,28 +414,28 @@ impl Typifier {
let ty_right = self.get(right, types);
if ty_left == ty_right {
self.resolutions[left.index()].clone()
- } else if let crate::TypeInner::Scalar { .. } = *ty_left {
+ } else if let Ti::Scalar { .. } = *ty_left {
self.resolutions[right.index()].clone()
- } else if let crate::TypeInner::Scalar { .. } = *ty_right {
+ } else if let Ti::Scalar { .. } = *ty_right {
self.resolutions[left.index()].clone()
- } else if let crate::TypeInner::Matrix {
+ } else if let Ti::Matrix {
columns: _,
rows,
width,
} = *ty_left
{
- Resolution::Value(crate::TypeInner::Vector {
+ Resolution::Value(Ti::Vector {
size: rows,
kind: crate::ScalarKind::Float,
width,
})
- } else if let crate::TypeInner::Matrix {
+ } else if let Ti::Matrix {
columns,
rows: _,
width,
} = *ty_right
{
- Resolution::Value(crate::TypeInner::Vector {
+ Resolution::Value(Ti::Vector {
size: columns,
kind: crate::ScalarKind::Float,
width,
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -309,10 +459,8 @@ impl Typifier {
let kind = crate::ScalarKind::Bool;
let width = 1;
let inner = match *self.get(left, types) {
- crate::TypeInner::Scalar { .. } => crate::TypeInner::Scalar { kind, width },
- crate::TypeInner::Vector { size, .. } => {
- crate::TypeInner::Vector { size, kind, width }
- }
+ Ti::Scalar { .. } => Ti::Scalar { kind, width },
+ Ti::Vector { size, .. } => Ti::Vector { size, kind, width },
ref other => {
return Err(ResolveError::IncompatibleOperand {
op: "logical".to_string(),
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -332,7 +480,7 @@ impl Typifier {
crate::Expression::Derivative { axis: _, expr } => {
self.resolutions[expr.index()].clone()
}
- crate::Expression::Relational { .. } => Resolution::Value(crate::TypeInner::Scalar {
+ crate::Expression::Relational { .. } => Resolution::Value(Ti::Scalar {
kind: crate::ScalarKind::Bool,
width: 4,
}),
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -377,11 +525,11 @@ impl Typifier {
Mf::Pow => self.resolutions[arg.index()].clone(),
// geometry
Mf::Dot => match *self.get(arg, types) {
- crate::TypeInner::Vector {
+ Ti::Vector {
kind,
size: _,
width,
- } => Resolution::Value(crate::TypeInner::Scalar { kind, width }),
+ } => Resolution::Value(Ti::Scalar { kind, width }),
ref other => {
return Err(ResolveError::IncompatibleOperand {
op: "dot product".to_string(),
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -395,7 +543,7 @@ impl Typifier {
operand: "".to_string(),
})?;
match (self.get(arg, types), self.get(arg1,types)) {
- (&crate::TypeInner::Vector {kind: _, size: columns,width}, &crate::TypeInner::Vector{ size: rows, .. }) => Resolution::Value(crate::TypeInner::Matrix { columns, rows, width }),
+ (&Ti::Vector {kind: _, size: columns,width}, &Ti::Vector{ size: rows, .. }) => Resolution::Value(Ti::Matrix { columns, rows, width }),
(left, right) => {
return Err(ResolveError::IncompatibleOperands {
op: "outer product".to_string(),
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -408,8 +556,8 @@ impl Typifier {
Mf::Cross => self.resolutions[arg.index()].clone(),
Mf::Distance |
Mf::Length => match *self.get(arg, types) {
- crate::TypeInner::Scalar {width,kind} |
- crate::TypeInner::Vector {width,kind,size:_} => Resolution::Value(crate::TypeInner::Scalar { kind, width }),
+ Ti::Scalar {width,kind} |
+ Ti::Vector {width,kind,size:_} => Resolution::Value(Ti::Scalar { kind, width }),
ref other => {
return Err(ResolveError::IncompatibleOperand {
op: format!("{:?}", fun),
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -429,11 +577,11 @@ impl Typifier {
Mf::Sqrt |
Mf::InverseSqrt => self.resolutions[arg.index()].clone(),
Mf::Transpose => match *self.get(arg, types) {
- crate::TypeInner::Matrix {
+ Ti::Matrix {
columns,
rows,
width,
- } => Resolution::Value(crate::TypeInner::Matrix {
+ } => Resolution::Value(Ti::Matrix {
columns: rows,
rows: columns,
width,
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -446,11 +594,11 @@ impl Typifier {
}
},
Mf::Inverse => match *self.get(arg, types) {
- crate::TypeInner::Matrix {
+ Ti::Matrix {
columns,
rows,
width,
- } if columns == rows => Resolution::Value(crate::TypeInner::Matrix {
+ } if columns == rows => Resolution::Value(Ti::Matrix {
columns,
rows,
width,
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -463,10 +611,10 @@ impl Typifier {
}
},
Mf::Determinant => match *self.get(arg, types) {
- crate::TypeInner::Matrix {
+ Ti::Matrix {
width,
..
- } => Resolution::Value(crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width }),
+ } => Resolution::Value(Ti::Scalar { kind: crate::ScalarKind::Float, width }),
ref other => {
return Err(ResolveError::IncompatibleOperand {
op: "determinant".to_string(),
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -484,14 +632,12 @@ impl Typifier {
kind,
convert: _,
} => match *self.get(expr, types) {
- crate::TypeInner::Scalar { kind: _, width } => {
- Resolution::Value(crate::TypeInner::Scalar { kind, width })
- }
- crate::TypeInner::Vector {
+ Ti::Scalar { kind: _, width } => Resolution::Value(Ti::Scalar { kind, width }),
+ Ti::Vector {
kind: _,
size,
width,
- } => Resolution::Value(crate::TypeInner::Vector { kind, size, width }),
+ } => Resolution::Value(Ti::Vector { kind, size, width }),
ref other => {
return Err(ResolveError::IncompatibleOperand {
op: "as".to_string(),
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -505,7 +651,7 @@ impl Typifier {
.ok_or(ResolveError::FunctionReturnsVoid)?;
Resolution::Handle(ty)
}
- crate::Expression::ArrayLength(_) => Resolution::Value(crate::TypeInner::Scalar {
+ crate::Expression::ArrayLength(_) => Resolution::Value(Ti::Scalar {
kind: crate::ScalarKind::Uint,
width: 4,
}),
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -523,15 +669,7 @@ impl Typifier {
for (eh, expr) in expressions.iter().skip(self.resolutions.len()) {
let resolution = self.resolve_impl(expr, types, ctx)?;
log::debug!("Resolving {:?} = {:?} : {:?}", eh, expr, resolution);
-
- let ty_handle = match resolution {
- Resolution::Handle(h) => h,
- Resolution::Value(inner) => types
- .fetch_if_or_append(crate::Type { name: None, inner }, |a, b| {
- a.inner == b.inner
- }),
- };
- self.resolutions.push(Resolution::Handle(ty_handle));
+ self.resolutions.push(resolution);
}
}
Ok(())
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -346,7 +346,7 @@ impl crate::GlobalVariable {
}),
Bi::FrontFacing => Some(Ti::Scalar {
kind: Sk::Bool,
- width: 1,
+ width: crate::BOOL_WIDTH,
}),
Bi::GlobalInvocationId
| Bi::LocalInvocationId
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -455,7 +455,7 @@ impl Validator {
fn check_width(kind: crate::ScalarKind, width: crate::Bytes) -> bool {
match kind {
- crate::ScalarKind::Bool => width == 1,
+ crate::ScalarKind::Bool => width == crate::BOOL_WIDTH,
_ => width == 4,
}
}
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -486,6 +486,17 @@ impl Validator {
}
TypeFlags::DATA | TypeFlags::SIZED
}
+ Ti::ValuePointer {
+ size: _,
+ kind,
+ width,
+ class: _,
+ } => {
+ if !Self::check_width(kind, width) {
+ return Err(TypeError::InvalidWidth(kind, width));
+ }
+ TypeFlags::SIZED //TODO: `DATA`?
+ }
Ti::Array { base, size, stride } => {
if base >= handle {
return Err(TypeError::UnresolvedBase(base));
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -917,7 +928,25 @@ impl Validator {
}
_ => {}
}
- if self.typifier.try_get(pointer, context.types) != Some(value_ty) {
+ let good = match self.typifier.try_get(pointer, context.types) {
+ Some(&Ti::Pointer { base, class: _ }) => {
+ *value_ty == context.types[base].inner
+ }
+ Some(&Ti::ValuePointer {
+ size: Some(size),
+ kind,
+ width,
+ class: _,
+ }) => *value_ty == Ti::Vector { size, kind, width },
+ Some(&Ti::ValuePointer {
+ size: None,
+ kind,
+ width,
+ class: _,
+ }) => *value_ty == Ti::Scalar { kind, width },
+ _ => false,
+ };
+ if !good {
return Err(FunctionError::InvalidStoreTypes { pointer, value });
}
}
|
diff --git a/tests/out/boids.msl.snap b/tests/out/boids.msl.snap
--- a/tests/out/boids.msl.snap
+++ b/tests/out/boids.msl.snap
@@ -36,8 +36,6 @@ typedef metal::uint3 type4;
typedef int type5;
-typedef bool type6;
-
constexpr constant int NUM_PARTICLES = 1500;
constexpr constant float const_0f = 0.0;
constexpr constant int const_0i = 0;
diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap
--- a/tests/out/boids.spvasm.snap
+++ b/tests/out/boids.spvasm.snap
@@ -5,7 +5,7 @@ expression: dis
; SPIR-V
; Version: 1.0
; Generator: rspirv
-; Bound: 233
+; Bound: 221
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap
--- a/tests/out/boids.spvasm.snap
+++ b/tests/out/boids.spvasm.snap
@@ -94,46 +94,34 @@ OpDecorate %25 BuiltIn GlobalInvocationId
%40 = OpTypePointer Function %9
%42 = OpTypeFunction %2
%47 = OpTypeBool
-%51 = OpConstant %4 0
-%52 = OpConstant %4 0
-%54 = OpTypePointer Uniform %22
-%56 = OpConstant %4 1
-%57 = OpConstant %4 0
-%59 = OpTypePointer Uniform %22
-%77 = OpConstant %4 0
+%51 = OpTypePointer Uniform %20
+%52 = OpTypePointer Uniform %21
+%53 = OpTypePointer Uniform %22
+%54 = OpConstant %4 0
+%55 = OpConstant %4 0
+%58 = OpConstant %4 1
+%59 = OpConstant %4 0
%78 = OpConstant %4 0
-%80 = OpTypePointer Uniform %22
+%79 = OpConstant %4 0
%83 = OpConstant %4 1
%84 = OpConstant %4 0
-%86 = OpTypePointer Uniform %22
+%90 = OpTypePointer Uniform %6
%91 = OpConstant %4 1
-%93 = OpTypePointer Uniform %6
-%106 = OpConstant %4 2
-%108 = OpTypePointer Uniform %6
-%121 = OpConstant %4 3
-%123 = OpTypePointer Uniform %6
-%157 = OpConstant %4 4
-%159 = OpTypePointer Uniform %6
-%164 = OpConstant %4 5
-%166 = OpTypePointer Uniform %6
-%171 = OpConstant %4 6
-%173 = OpTypePointer Uniform %6
-%185 = OpConstant %4 0
-%187 = OpTypePointer Uniform %6
-%196 = OpConstant %4 0
-%198 = OpTypePointer Function %6
-%204 = OpConstant %4 0
-%206 = OpTypePointer Function %6
-%212 = OpConstant %4 1
-%214 = OpTypePointer Function %6
-%220 = OpConstant %4 1
-%222 = OpTypePointer Function %6
-%224 = OpConstant %4 0
-%225 = OpConstant %4 0
-%227 = OpTypePointer Uniform %22
-%229 = OpConstant %4 1
-%230 = OpConstant %4 0
-%232 = OpTypePointer Uniform %22
+%105 = OpConstant %4 2
+%119 = OpConstant %4 3
+%154 = OpConstant %4 4
+%160 = OpConstant %4 5
+%166 = OpConstant %4 6
+%179 = OpConstant %4 0
+%189 = OpTypePointer Function %6
+%190 = OpConstant %4 0
+%197 = OpConstant %4 0
+%204 = OpConstant %4 1
+%211 = OpConstant %4 1
+%214 = OpConstant %4 0
+%215 = OpConstant %4 0
+%218 = OpConstant %4 1
+%219 = OpConstant %4 0
%41 = OpFunction %2 None %42
%43 = OpLabel
%39 = OpVariable %40 Function %8
diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap
--- a/tests/out/boids.spvasm.snap
+++ b/tests/out/boids.spvasm.snap
@@ -156,209 +144,209 @@ OpBranchConditional %48 %50 %49
%50 = OpLabel
OpReturn
%49 = OpLabel
-%53 = OpAccessChain %54 %18 %52 %46 %51
-%55 = OpLoad %22 %53
-OpStore %28 %55
-%58 = OpAccessChain %59 %18 %57 %46 %56
-%60 = OpLoad %22 %58
-OpStore %30 %60
-%61 = OpCompositeConstruct %22 %5 %5
-OpStore %31 %61
+%56 = OpAccessChain %53 %18 %55 %46 %54
+%57 = OpLoad %22 %56
+OpStore %28 %57
+%60 = OpAccessChain %53 %18 %59 %46 %58
+%61 = OpLoad %22 %60
+OpStore %30 %61
%62 = OpCompositeConstruct %22 %5 %5
-OpStore %32 %62
+OpStore %31 %62
%63 = OpCompositeConstruct %22 %5 %5
-OpStore %33 %63
-OpBranch %64
-%64 = OpLabel
-OpLoopMerge %65 %67 None
+OpStore %32 %63
+%64 = OpCompositeConstruct %22 %5 %5
+OpStore %33 %64
+OpBranch %65
+%65 = OpLabel
+OpLoopMerge %66 %68 None
+OpBranch %67
+%67 = OpLabel
+%69 = OpLoad %9 %39
+%70 = OpUGreaterThanEqual %47 %69 %3
+OpSelectionMerge %71 None
+OpBranchConditional %70 %72 %71
+%72 = OpLabel
OpBranch %66
-%66 = OpLabel
-%68 = OpLoad %9 %39
-%69 = OpUGreaterThanEqual %47 %68 %3
-OpSelectionMerge %70 None
-OpBranchConditional %69 %71 %70
%71 = OpLabel
-OpBranch %65
-%70 = OpLabel
-%72 = OpLoad %9 %39
-%73 = OpIEqual %47 %72 %46
-OpSelectionMerge %74 None
-OpBranchConditional %73 %75 %74
+%73 = OpLoad %9 %39
+%74 = OpIEqual %47 %73 %46
+OpSelectionMerge %75 None
+OpBranchConditional %74 %76 %75
+%76 = OpLabel
+OpBranch %68
%75 = OpLabel
-OpBranch %67
-%74 = OpLabel
-%76 = OpLoad %9 %39
-%79 = OpAccessChain %80 %18 %78 %76 %77
-%81 = OpLoad %22 %79
+%77 = OpLoad %9 %39
+%80 = OpAccessChain %53 %18 %79 %77 %78
+%81 = OpLoad %22 %80
OpStore %37 %81
%82 = OpLoad %9 %39
-%85 = OpAccessChain %86 %18 %84 %82 %83
-%87 = OpLoad %22 %85
-OpStore %38 %87
-%88 = OpLoad %22 %37
-%89 = OpLoad %22 %28
-%90 = OpExtInst %6 %1 Distance %88 %89
-%92 = OpAccessChain %93 %15 %91
-%94 = OpLoad %6 %92
-%95 = OpFOrdLessThan %47 %90 %94
-OpSelectionMerge %96 None
-OpBranchConditional %95 %97 %96
-%97 = OpLabel
-%98 = OpLoad %22 %31
-%99 = OpLoad %22 %37
-%100 = OpFAdd %22 %98 %99
-OpStore %31 %100
-%101 = OpLoad %4 %34
-%102 = OpIAdd %4 %101 %10
-OpStore %34 %102
-OpBranch %96
+%85 = OpAccessChain %53 %18 %84 %82 %83
+%86 = OpLoad %22 %85
+OpStore %38 %86
+%87 = OpLoad %22 %37
+%88 = OpLoad %22 %28
+%89 = OpExtInst %6 %1 Distance %87 %88
+%92 = OpAccessChain %90 %15 %91
+%93 = OpLoad %6 %92
+%94 = OpFOrdLessThan %47 %89 %93
+OpSelectionMerge %95 None
+OpBranchConditional %94 %96 %95
%96 = OpLabel
-%103 = OpLoad %22 %37
-%104 = OpLoad %22 %28
-%105 = OpExtInst %6 %1 Distance %103 %104
-%107 = OpAccessChain %108 %15 %106
-%109 = OpLoad %6 %107
-%110 = OpFOrdLessThan %47 %105 %109
-OpSelectionMerge %111 None
-OpBranchConditional %110 %112 %111
-%112 = OpLabel
-%113 = OpLoad %22 %33
-%114 = OpLoad %22 %37
-%115 = OpLoad %22 %28
-%116 = OpFSub %22 %114 %115
-%117 = OpFSub %22 %113 %116
-OpStore %33 %117
-OpBranch %111
-%111 = OpLabel
-%118 = OpLoad %22 %37
-%119 = OpLoad %22 %28
-%120 = OpExtInst %6 %1 Distance %118 %119
-%122 = OpAccessChain %123 %15 %121
-%124 = OpLoad %6 %122
-%125 = OpFOrdLessThan %47 %120 %124
-OpSelectionMerge %126 None
-OpBranchConditional %125 %127 %126
-%127 = OpLabel
-%128 = OpLoad %22 %32
-%129 = OpLoad %22 %38
-%130 = OpFAdd %22 %128 %129
-OpStore %32 %130
-%131 = OpLoad %4 %36
-%132 = OpIAdd %4 %131 %10
-OpStore %36 %132
-OpBranch %126
-%126 = OpLabel
-OpBranch %67
-%67 = OpLabel
-%133 = OpLoad %9 %39
-%134 = OpIAdd %9 %133 %11
-OpStore %39 %134
-OpBranch %64
-%65 = OpLabel
-%135 = OpLoad %4 %34
-%136 = OpSGreaterThan %47 %135 %7
-OpSelectionMerge %137 None
-OpBranchConditional %136 %138 %137
-%138 = OpLabel
-%139 = OpLoad %22 %31
-%140 = OpLoad %4 %34
-%141 = OpConvertSToF %6 %140
-%142 = OpFDiv %6 %12 %141
-%143 = OpVectorTimesScalar %22 %139 %142
-%144 = OpLoad %22 %28
-%145 = OpFSub %22 %143 %144
-OpStore %31 %145
-OpBranch %137
-%137 = OpLabel
-%146 = OpLoad %4 %36
-%147 = OpSGreaterThan %47 %146 %7
-OpSelectionMerge %148 None
-OpBranchConditional %147 %149 %148
-%149 = OpLabel
-%150 = OpLoad %22 %32
-%151 = OpLoad %4 %36
-%152 = OpConvertSToF %6 %151
-%153 = OpFDiv %6 %12 %152
-%154 = OpVectorTimesScalar %22 %150 %153
-OpStore %32 %154
-OpBranch %148
-%148 = OpLabel
-%155 = OpLoad %22 %30
-%156 = OpLoad %22 %31
-%158 = OpAccessChain %159 %15 %157
-%160 = OpLoad %6 %158
-%161 = OpVectorTimesScalar %22 %156 %160
-%162 = OpFAdd %22 %155 %161
-%163 = OpLoad %22 %33
-%165 = OpAccessChain %166 %15 %164
-%167 = OpLoad %6 %165
-%168 = OpVectorTimesScalar %22 %163 %167
-%169 = OpFAdd %22 %162 %168
-%170 = OpLoad %22 %32
-%172 = OpAccessChain %173 %15 %171
-%174 = OpLoad %6 %172
-%175 = OpVectorTimesScalar %22 %170 %174
-%176 = OpFAdd %22 %169 %175
+%97 = OpLoad %22 %31
+%98 = OpLoad %22 %37
+%99 = OpFAdd %22 %97 %98
+OpStore %31 %99
+%100 = OpLoad %4 %34
+%101 = OpIAdd %4 %100 %10
+OpStore %34 %101
+OpBranch %95
+%95 = OpLabel
+%102 = OpLoad %22 %37
+%103 = OpLoad %22 %28
+%104 = OpExtInst %6 %1 Distance %102 %103
+%106 = OpAccessChain %90 %15 %105
+%107 = OpLoad %6 %106
+%108 = OpFOrdLessThan %47 %104 %107
+OpSelectionMerge %109 None
+OpBranchConditional %108 %110 %109
+%110 = OpLabel
+%111 = OpLoad %22 %33
+%112 = OpLoad %22 %37
+%113 = OpLoad %22 %28
+%114 = OpFSub %22 %112 %113
+%115 = OpFSub %22 %111 %114
+OpStore %33 %115
+OpBranch %109
+%109 = OpLabel
+%116 = OpLoad %22 %37
+%117 = OpLoad %22 %28
+%118 = OpExtInst %6 %1 Distance %116 %117
+%120 = OpAccessChain %90 %15 %119
+%121 = OpLoad %6 %120
+%122 = OpFOrdLessThan %47 %118 %121
+OpSelectionMerge %123 None
+OpBranchConditional %122 %124 %123
+%124 = OpLabel
+%125 = OpLoad %22 %32
+%126 = OpLoad %22 %38
+%127 = OpFAdd %22 %125 %126
+OpStore %32 %127
+%128 = OpLoad %4 %36
+%129 = OpIAdd %4 %128 %10
+OpStore %36 %129
+OpBranch %123
+%123 = OpLabel
+OpBranch %68
+%68 = OpLabel
+%130 = OpLoad %9 %39
+%131 = OpIAdd %9 %130 %11
+OpStore %39 %131
+OpBranch %65
+%66 = OpLabel
+%132 = OpLoad %4 %34
+%133 = OpSGreaterThan %47 %132 %7
+OpSelectionMerge %134 None
+OpBranchConditional %133 %135 %134
+%135 = OpLabel
+%136 = OpLoad %22 %31
+%137 = OpLoad %4 %34
+%138 = OpConvertSToF %6 %137
+%139 = OpFDiv %6 %12 %138
+%140 = OpVectorTimesScalar %22 %136 %139
+%141 = OpLoad %22 %28
+%142 = OpFSub %22 %140 %141
+OpStore %31 %142
+OpBranch %134
+%134 = OpLabel
+%143 = OpLoad %4 %36
+%144 = OpSGreaterThan %47 %143 %7
+OpSelectionMerge %145 None
+OpBranchConditional %144 %146 %145
+%146 = OpLabel
+%147 = OpLoad %22 %32
+%148 = OpLoad %4 %36
+%149 = OpConvertSToF %6 %148
+%150 = OpFDiv %6 %12 %149
+%151 = OpVectorTimesScalar %22 %147 %150
+OpStore %32 %151
+OpBranch %145
+%145 = OpLabel
+%152 = OpLoad %22 %30
+%153 = OpLoad %22 %31
+%155 = OpAccessChain %90 %15 %154
+%156 = OpLoad %6 %155
+%157 = OpVectorTimesScalar %22 %153 %156
+%158 = OpFAdd %22 %152 %157
+%159 = OpLoad %22 %33
+%161 = OpAccessChain %90 %15 %160
+%162 = OpLoad %6 %161
+%163 = OpVectorTimesScalar %22 %159 %162
+%164 = OpFAdd %22 %158 %163
+%165 = OpLoad %22 %32
+%167 = OpAccessChain %90 %15 %166
+%168 = OpLoad %6 %167
+%169 = OpVectorTimesScalar %22 %165 %168
+%170 = OpFAdd %22 %164 %169
+OpStore %30 %170
+%171 = OpLoad %22 %30
+%172 = OpExtInst %22 %1 Normalize %171
+%173 = OpLoad %22 %30
+%174 = OpExtInst %6 %1 Length %173
+%175 = OpExtInst %6 %1 FClamp %174 %5 %13
+%176 = OpVectorTimesScalar %22 %172 %175
OpStore %30 %176
-%177 = OpLoad %22 %30
-%178 = OpExtInst %22 %1 Normalize %177
-%179 = OpLoad %22 %30
-%180 = OpExtInst %6 %1 Length %179
-%181 = OpExtInst %6 %1 FClamp %180 %5 %13
+%177 = OpLoad %22 %28
+%178 = OpLoad %22 %30
+%180 = OpAccessChain %90 %15 %179
+%181 = OpLoad %6 %180
%182 = OpVectorTimesScalar %22 %178 %181
-OpStore %30 %182
-%183 = OpLoad %22 %28
-%184 = OpLoad %22 %30
-%186 = OpAccessChain %187 %15 %185
-%188 = OpLoad %6 %186
-%189 = OpVectorTimesScalar %22 %184 %188
-%190 = OpFAdd %22 %183 %189
-OpStore %28 %190
-%191 = OpLoad %22 %28
-%192 = OpCompositeExtract %6 %191 0
-%193 = OpFOrdLessThan %47 %192 %14
-OpSelectionMerge %194 None
-OpBranchConditional %193 %195 %194
+%183 = OpFAdd %22 %177 %182
+OpStore %28 %183
+%184 = OpLoad %22 %28
+%185 = OpCompositeExtract %6 %184 0
+%186 = OpFOrdLessThan %47 %185 %14
+OpSelectionMerge %187 None
+OpBranchConditional %186 %188 %187
+%188 = OpLabel
+%191 = OpAccessChain %189 %28 %190
+OpStore %191 %12
+OpBranch %187
+%187 = OpLabel
+%192 = OpLoad %22 %28
+%193 = OpCompositeExtract %6 %192 0
+%194 = OpFOrdGreaterThan %47 %193 %12
+OpSelectionMerge %195 None
+OpBranchConditional %194 %196 %195
+%196 = OpLabel
+%198 = OpAccessChain %189 %28 %197
+OpStore %198 %14
+OpBranch %195
%195 = OpLabel
-%197 = OpAccessChain %198 %28 %196
-OpStore %197 %12
-OpBranch %194
-%194 = OpLabel
%199 = OpLoad %22 %28
-%200 = OpCompositeExtract %6 %199 0
-%201 = OpFOrdGreaterThan %47 %200 %12
+%200 = OpCompositeExtract %6 %199 1
+%201 = OpFOrdLessThan %47 %200 %14
OpSelectionMerge %202 None
OpBranchConditional %201 %203 %202
%203 = OpLabel
-%205 = OpAccessChain %206 %28 %204
-OpStore %205 %14
+%205 = OpAccessChain %189 %28 %204
+OpStore %205 %12
OpBranch %202
%202 = OpLabel
-%207 = OpLoad %22 %28
-%208 = OpCompositeExtract %6 %207 1
-%209 = OpFOrdLessThan %47 %208 %14
-OpSelectionMerge %210 None
-OpBranchConditional %209 %211 %210
-%211 = OpLabel
-%213 = OpAccessChain %214 %28 %212
-OpStore %213 %12
-OpBranch %210
+%206 = OpLoad %22 %28
+%207 = OpCompositeExtract %6 %206 1
+%208 = OpFOrdGreaterThan %47 %207 %12
+OpSelectionMerge %209 None
+OpBranchConditional %208 %210 %209
%210 = OpLabel
-%215 = OpLoad %22 %28
-%216 = OpCompositeExtract %6 %215 1
-%217 = OpFOrdGreaterThan %47 %216 %12
-OpSelectionMerge %218 None
-OpBranchConditional %217 %219 %218
-%219 = OpLabel
-%221 = OpAccessChain %222 %28 %220
-OpStore %221 %14
-OpBranch %218
-%218 = OpLabel
-%223 = OpLoad %22 %28
-%226 = OpAccessChain %227 %24 %225 %46 %224
-OpStore %226 %223
-%228 = OpLoad %22 %30
-%231 = OpAccessChain %232 %24 %230 %46 %229
-OpStore %231 %228
+%212 = OpAccessChain %189 %28 %211
+OpStore %212 %14
+OpBranch %209
+%209 = OpLabel
+%213 = OpLoad %22 %28
+%216 = OpAccessChain %53 %24 %215 %46 %214
+OpStore %216 %213
+%217 = OpLoad %22 %30
+%220 = OpAccessChain %53 %24 %219 %46 %218
+OpStore %220 %217
OpReturn
OpFunctionEnd
diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap
--- a/tests/out/collatz.spvasm.snap
+++ b/tests/out/collatz.spvasm.snap
@@ -44,11 +44,11 @@ OpDecorate %11 Binding 0
%20 = OpTypeFunction %4 %4
%28 = OpTypeBool
%47 = OpTypeFunction %2
-%54 = OpTypeInt 32 1
-%55 = OpConstant %54 0
-%57 = OpTypePointer Uniform %4
-%60 = OpConstant %54 0
-%62 = OpTypePointer Uniform %4
+%50 = OpTypePointer Uniform %13
+%53 = OpTypePointer Uniform %4
+%56 = OpTypeInt 32 1
+%57 = OpConstant %56 0
+%61 = OpConstant %56 0
%19 = OpFunction %4 None %20
%18 = OpFunctionParameter %4
%21 = OpLabel
diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap
--- a/tests/out/collatz.spvasm.snap
+++ b/tests/out/collatz.spvasm.snap
@@ -100,14 +100,14 @@ OpFunctionEnd
%48 = OpLabel
OpBranch %49
%49 = OpLabel
-%50 = OpLoad %9 %8
-%51 = OpCompositeExtract %4 %50 0
-%52 = OpLoad %9 %8
-%53 = OpCompositeExtract %4 %52 0
-%56 = OpAccessChain %57 %11 %55 %53
-%58 = OpLoad %4 %56
-%59 = OpFunctionCall %4 %19 %58
-%61 = OpAccessChain %62 %11 %60 %51
-OpStore %61 %59
+%51 = OpLoad %9 %8
+%52 = OpCompositeExtract %4 %51 0
+%54 = OpLoad %9 %8
+%55 = OpCompositeExtract %4 %54 0
+%58 = OpAccessChain %53 %11 %57 %55
+%59 = OpLoad %4 %58
+%60 = OpFunctionCall %4 %19 %59
+%62 = OpAccessChain %53 %11 %61 %52
+OpStore %62 %60
OpReturn
OpFunctionEnd
diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap
--- a/tests/out/shadow.msl.snap
+++ b/tests/out/shadow.msl.snap
@@ -39,8 +39,6 @@ typedef metal::float2 type8;
typedef metal::float3 type9;
-typedef bool type10;
-
constexpr constant float const_0f = 0.0;
constexpr constant float const_1f = 1.0;
constexpr constant float const_0_50f = 0.5;
diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap
--- a/tests/out/shadow.spvasm.snap
+++ b/tests/out/shadow.spvasm.snap
@@ -5,7 +5,7 @@ expression: dis
; SPIR-V
; Version: 1.2
; Generator: rspirv
-; Bound: 137
+; Bound: 138
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap
--- a/tests/out/shadow.spvasm.snap
+++ b/tests/out/shadow.spvasm.snap
@@ -101,10 +101,11 @@ OpDecorate %36 Location 0
%75 = OpTypePointer Function %10
%77 = OpTypePointer Function %12
%79 = OpTypeFunction %2
-%91 = OpConstant %62 0
-%93 = OpTypePointer Uniform %17
-%101 = OpConstant %62 0
-%103 = OpTypePointer Uniform %22
+%91 = OpTypePointer Uniform %17
+%92 = OpConstant %62 0
+%100 = OpTypePointer Uniform %21
+%102 = OpTypePointer Uniform %22
+%103 = OpConstant %62 0
%40 = OpFunction %4 None %41
%38 = OpFunctionParameter %12
%39 = OpFunctionParameter %24
diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap
--- a/tests/out/shadow.spvasm.snap
+++ b/tests/out/shadow.spvasm.snap
@@ -157,8 +158,8 @@ OpLoopMerge %87 %89 None
OpBranch %88
%88 = OpLabel
%90 = OpLoad %12 %76
-%92 = OpAccessChain %93 %15 %91
-%94 = OpLoad %17 %92
+%93 = OpAccessChain %91 %15 %92
+%94 = OpLoad %17 %93
%95 = OpCompositeExtract %12 %94 0
%96 = OpExtInst %12 %1 UMin %95 %11
%97 = OpUGreaterThanEqual %47 %90 %96
diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap
--- a/tests/out/shadow.spvasm.snap
+++ b/tests/out/shadow.spvasm.snap
@@ -167,47 +168,47 @@ OpBranchConditional %97 %99 %98
%99 = OpLabel
OpBranch %87
%98 = OpLabel
-%100 = OpLoad %12 %76
-%102 = OpAccessChain %103 %19 %101 %100
-%104 = OpLoad %22 %102
-%105 = OpLoad %12 %76
-%106 = OpCompositeExtract %23 %104 0
-%107 = OpLoad %24 %34
-%108 = OpMatrixTimesVector %24 %106 %107
-%109 = OpFunctionCall %4 %40 %105 %108
-%110 = OpCompositeExtract %24 %104 1
-%111 = OpCompositeExtract %4 %110 0
-%112 = OpCompositeExtract %4 %110 1
-%113 = OpCompositeExtract %4 %110 2
-%114 = OpCompositeConstruct %10 %111 %112 %113
-%115 = OpLoad %24 %34
-%116 = OpCompositeExtract %4 %115 0
-%117 = OpCompositeExtract %4 %115 1
-%118 = OpCompositeExtract %4 %115 2
-%119 = OpCompositeConstruct %10 %116 %117 %118
-%120 = OpFSub %10 %114 %119
-%121 = OpExtInst %10 %1 Normalize %120
-%122 = OpDot %4 %85 %121
-%123 = OpExtInst %4 %1 FMax %3 %122
-%124 = OpLoad %10 %74
-%125 = OpFMul %4 %109 %123
-%126 = OpCompositeExtract %24 %104 2
-%127 = OpCompositeExtract %4 %126 0
-%128 = OpCompositeExtract %4 %126 1
-%129 = OpCompositeExtract %4 %126 2
-%130 = OpCompositeConstruct %10 %127 %128 %129
-%131 = OpVectorTimesScalar %10 %130 %125
-%132 = OpFAdd %10 %124 %131
-OpStore %74 %132
+%101 = OpLoad %12 %76
+%104 = OpAccessChain %102 %19 %103 %101
+%105 = OpLoad %22 %104
+%106 = OpLoad %12 %76
+%107 = OpCompositeExtract %23 %105 0
+%108 = OpLoad %24 %34
+%109 = OpMatrixTimesVector %24 %107 %108
+%110 = OpFunctionCall %4 %40 %106 %109
+%111 = OpCompositeExtract %24 %105 1
+%112 = OpCompositeExtract %4 %111 0
+%113 = OpCompositeExtract %4 %111 1
+%114 = OpCompositeExtract %4 %111 2
+%115 = OpCompositeConstruct %10 %112 %113 %114
+%116 = OpLoad %24 %34
+%117 = OpCompositeExtract %4 %116 0
+%118 = OpCompositeExtract %4 %116 1
+%119 = OpCompositeExtract %4 %116 2
+%120 = OpCompositeConstruct %10 %117 %118 %119
+%121 = OpFSub %10 %115 %120
+%122 = OpExtInst %10 %1 Normalize %121
+%123 = OpDot %4 %85 %122
+%124 = OpExtInst %4 %1 FMax %3 %123
+%125 = OpLoad %10 %74
+%126 = OpFMul %4 %110 %124
+%127 = OpCompositeExtract %24 %105 2
+%128 = OpCompositeExtract %4 %127 0
+%129 = OpCompositeExtract %4 %127 1
+%130 = OpCompositeExtract %4 %127 2
+%131 = OpCompositeConstruct %10 %128 %129 %130
+%132 = OpVectorTimesScalar %10 %131 %126
+%133 = OpFAdd %10 %125 %132
+OpStore %74 %133
OpBranch %89
%89 = OpLabel
-%133 = OpLoad %12 %76
-%134 = OpIAdd %12 %133 %14
-OpStore %76 %134
+%134 = OpLoad %12 %76
+%135 = OpIAdd %12 %134 %14
+OpStore %76 %135
OpBranch %86
%87 = OpLabel
-%135 = OpLoad %10 %74
-%136 = OpCompositeConstruct %24 %135 %5
-OpStore %36 %136
+%136 = OpLoad %10 %74
+%137 = OpCompositeConstruct %24 %136 %5
+OpStore %36 %137
OpReturn
OpFunctionEnd
diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap
--- a/tests/out/skybox.msl.snap
+++ b/tests/out/skybox.msl.snap
@@ -20,13 +20,11 @@ struct Data {
typedef int type4;
-typedef float type5;
+typedef metal::float3x3 type5;
-typedef metal::float3x3 type6;
+typedef metal::texturecube<float, metal::access::sample> type6;
-typedef metal::texturecube<float, metal::access::sample> type7;
-
-typedef metal::sampler type8;
+typedef metal::sampler type7;
constexpr constant int const_2i = 2;
constexpr constant int const_1i = 1;
diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap
--- a/tests/out/skybox.msl.snap
+++ b/tests/out/skybox.msl.snap
@@ -70,8 +68,8 @@ struct fs_mainOutput {
fragment fs_mainOutput fs_main(
fs_mainInput input [[stage_in]],
- type7 r_texture [[texture(0)]],
- type8 r_sampler [[sampler(1)]]
+ type6 r_texture [[texture(0)]],
+ type7 r_sampler [[sampler(1)]]
) {
fs_mainOutput output;
metal::float4 _expr9 = r_texture.sample(r_sampler, input.in_uv);
diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap
--- a/tests/out/skybox.spvasm.snap
+++ b/tests/out/skybox.spvasm.snap
@@ -5,13 +5,13 @@ expression: dis
; SPIR-V
; Version: 1.0
; Generator: rspirv
-; Bound: 106
+; Bound: 103
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Vertex %37 "vs_main" %10 %13 %16
-OpEntryPoint Fragment %97 "fs_main" %29 %31
-OpExecutionMode %97 OriginUpperLeft
+OpEntryPoint Fragment %94 "fs_main" %29 %31
+OpExecutionMode %94 OriginUpperLeft
OpSource GLSL 450
OpName %10 "out_position"
OpName %13 "out_uv"
diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap
--- a/tests/out/skybox.spvasm.snap
+++ b/tests/out/skybox.spvasm.snap
@@ -29,8 +29,8 @@ OpName %34 "tmp2"
OpName %35 "unprojected"
OpName %37 "vs_main"
OpName %37 "vs_main"
-OpName %97 "fs_main"
-OpName %97 "fs_main"
+OpName %94 "fs_main"
+OpName %94 "fs_main"
OpDecorate %10 BuiltIn Position
OpDecorate %13 Location 0
OpDecorate %16 BuiltIn VertexIndex
diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap
--- a/tests/out/skybox.spvasm.snap
+++ b/tests/out/skybox.spvasm.snap
@@ -82,16 +82,13 @@ OpDecorate %31 Location 0
%33 = OpTypePointer Function %4
%36 = OpTypePointer Function %11
%38 = OpTypeFunction %2
-%56 = OpConstant %4 1
-%58 = OpTypePointer Uniform %21
+%56 = OpTypePointer Uniform %21
+%57 = OpConstant %4 1
%65 = OpConstant %4 1
-%67 = OpTypePointer Uniform %21
-%74 = OpConstant %4 1
-%76 = OpTypePointer Uniform %21
-%83 = OpTypeMatrix %14 3
-%86 = OpConstant %4 0
-%88 = OpTypePointer Uniform %21
-%103 = OpTypeSampledImage %24
+%73 = OpConstant %4 1
+%81 = OpTypeMatrix %14 3
+%84 = OpConstant %4 0
+%100 = OpTypeSampledImage %24
%37 = OpFunction %2 None %38
%39 = OpLabel
%32 = OpVariable %33 Function
diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap
--- a/tests/out/skybox.spvasm.snap
+++ b/tests/out/skybox.spvasm.snap
@@ -116,52 +113,52 @@ OpStore %34 %46
%53 = OpFMul %7 %52 %6
%54 = OpFSub %7 %53 %8
%55 = OpCompositeConstruct %11 %50 %54 %9 %8
-%57 = OpAccessChain %58 %19 %56
-%59 = OpLoad %21 %57
+%58 = OpAccessChain %56 %19 %57
+%59 = OpLoad %21 %58
%60 = OpCompositeExtract %11 %59 0
%61 = OpCompositeExtract %7 %60 0
%62 = OpCompositeExtract %7 %60 1
%63 = OpCompositeExtract %7 %60 2
%64 = OpCompositeConstruct %14 %61 %62 %63
-%66 = OpAccessChain %67 %19 %65
-%68 = OpLoad %21 %66
-%69 = OpCompositeExtract %11 %68 1
-%70 = OpCompositeExtract %7 %69 0
-%71 = OpCompositeExtract %7 %69 1
-%72 = OpCompositeExtract %7 %69 2
-%73 = OpCompositeConstruct %14 %70 %71 %72
-%75 = OpAccessChain %76 %19 %74
-%77 = OpLoad %21 %75
-%78 = OpCompositeExtract %11 %77 2
-%79 = OpCompositeExtract %7 %78 0
-%80 = OpCompositeExtract %7 %78 1
-%81 = OpCompositeExtract %7 %78 2
-%82 = OpCompositeConstruct %14 %79 %80 %81
-%84 = OpCompositeConstruct %83 %64 %73 %82
-%85 = OpTranspose %83 %84
-%87 = OpAccessChain %88 %19 %86
-%89 = OpLoad %21 %87
-%90 = OpMatrixTimesVector %11 %89 %55
-OpStore %35 %90
-%91 = OpLoad %11 %35
-%92 = OpCompositeExtract %7 %91 0
-%93 = OpCompositeExtract %7 %91 1
-%94 = OpCompositeExtract %7 %91 2
-%95 = OpCompositeConstruct %14 %92 %93 %94
-%96 = OpMatrixTimesVector %14 %85 %95
-OpStore %13 %96
+%66 = OpAccessChain %56 %19 %65
+%67 = OpLoad %21 %66
+%68 = OpCompositeExtract %11 %67 1
+%69 = OpCompositeExtract %7 %68 0
+%70 = OpCompositeExtract %7 %68 1
+%71 = OpCompositeExtract %7 %68 2
+%72 = OpCompositeConstruct %14 %69 %70 %71
+%74 = OpAccessChain %56 %19 %73
+%75 = OpLoad %21 %74
+%76 = OpCompositeExtract %11 %75 2
+%77 = OpCompositeExtract %7 %76 0
+%78 = OpCompositeExtract %7 %76 1
+%79 = OpCompositeExtract %7 %76 2
+%80 = OpCompositeConstruct %14 %77 %78 %79
+%82 = OpCompositeConstruct %81 %64 %72 %80
+%83 = OpTranspose %81 %82
+%85 = OpAccessChain %56 %19 %84
+%86 = OpLoad %21 %85
+%87 = OpMatrixTimesVector %11 %86 %55
+OpStore %35 %87
+%88 = OpLoad %11 %35
+%89 = OpCompositeExtract %7 %88 0
+%90 = OpCompositeExtract %7 %88 1
+%91 = OpCompositeExtract %7 %88 2
+%92 = OpCompositeConstruct %14 %89 %90 %91
+%93 = OpMatrixTimesVector %14 %83 %92
+OpStore %13 %93
OpStore %10 %55
OpReturn
OpFunctionEnd
-%97 = OpFunction %2 None %38
+%94 = OpFunction %2 None %38
+%95 = OpLabel
+%96 = OpLoad %24 %23
+%97 = OpLoad %27 %26
+OpBranch %98
%98 = OpLabel
-%99 = OpLoad %24 %23
-%100 = OpLoad %27 %26
-OpBranch %101
-%101 = OpLabel
-%102 = OpLoad %14 %29
-%104 = OpSampledImage %103 %99 %100
-%105 = OpImageSampleImplicitLod %11 %104 %102
-OpStore %31 %105
+%99 = OpLoad %14 %29
+%101 = OpSampledImage %100 %96 %97
+%102 = OpImageSampleImplicitLod %11 %101 %99
+OpStore %31 %102
OpReturn
OpFunctionEnd
diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap
--- a/tests/out/texture-array.spvasm.snap
+++ b/tests/out/texture-array.spvasm.snap
@@ -54,8 +54,8 @@ OpDecorate %20 Location 1
%22 = OpTypePointer Output %21
%20 = OpVariable %22 Output
%24 = OpTypeFunction %2
-%30 = OpConstant %4 0
-%32 = OpTypePointer PushConstant %18
+%30 = OpTypePointer PushConstant %18
+%31 = OpConstant %4 0
%34 = OpTypeBool
%40 = OpTypeSampledImage %10
%23 = OpFunction %2 None %24
diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap
--- a/tests/out/texture-array.spvasm.snap
+++ b/tests/out/texture-array.spvasm.snap
@@ -65,8 +65,8 @@ OpDecorate %20 Location 1
%28 = OpLoad %14 %13
OpBranch %29
%29 = OpLabel
-%31 = OpAccessChain %32 %16 %30
-%33 = OpLoad %18 %31
+%32 = OpAccessChain %30 %16 %31
+%33 = OpLoad %18 %32
%35 = OpIEqual %34 %33 %3
OpSelectionMerge %36 None
OpBranchConditional %35 %37 %38
diff --git a/tests/parse.rs b/tests/parse.rs
--- a/tests/parse.rs
+++ b/tests/parse.rs
@@ -38,5 +38,5 @@ fn parse_glsl() {
//check_glsl("glsl_constant_expression.vert"); //TODO
//check_glsl("glsl_if_preprocessor.vert");
check_glsl("glsl_preprocessor_abuse.vert");
- check_glsl("glsl_vertex_test_shader.vert");
+ //check_glsl("glsl_vertex_test_shader.vert"); //TODO
}
|
Real SSA based on pointer semantics for variables
Right now, the `LocalVariable` and `GlobalVariable` aren't really pointers. They are "transparent" values, they materialize only when `Load` is issued. This harms the type checking, which isn't able to properly assess the `Access` and `AccessIndex` semantics. It will be future-proof to have real pointers, such that `Load` expects one.
|
So far I've tried different approaches to this and haven't found one that would fit:
1. Just plain consider the non-`Handle` variables to be pointers. Main blocker is the type resolution for `Access*`: when on matrices or vectors, if behind pointers, it needs to generate the pointers to their components. So it would need a new "value" type that is a pointer to a vector or a scalar. We don't have this nesting ability in the typifier right now.
- I tried adding `Resolution::ValuePoiner(TypeInner)` variant to accomodate this, and unfortunately this starts to be too loose and complex now. The `get` can no longer return a `&TypeInner`, and there are more ways to represent the same thing.
2. Add `pointer: bool` to `struct Type` instead of a separate `TypeInner::Pointer`. This is a bit awkward because now each `TypeInner` may potentially need to be represented twice in the IR: once as a pointer, and once without a pointer.
- It feels to me that a "pointer" could be made sort of a "qualifier" for the type handle, so that you can use the same handle with a pointer in one place, and without a pointer in another. This path would require all the places that currently work with `Handle<Type>` to change, and increase their size, unfortunately...
3. Make value type dependencies strict, so that a `Vector` type has a base of a `Scalar`, and a `Matrix` is just a vector of vectors. This quickly runs into issues with the typifier, since in a lot of places (like image sampling) we just want to be able to construct vector types in place, and this approach requires us to deal with the scalar type first.
Another relevant observation: we never actually *need* a pointer into matrix/vector contents. For right-hand-side, we can simply enforce the IR to do `Load` at the boundary between struct/array and the scalar-like types. It's non-observable, and unlikely will manifest in any difference in the generated code.
For the left-hand-side, however, these are more like "references". We never need an actual pointer, we know it's going to be consumed by `Statement::Store`. This doesn't entirely help us yet, though.
|
2021-03-05T23:21:52Z
|
0.3
|
2021-03-06T16:01:17Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"convert_wgsl_texture_array",
"convert_wgsl_shadow",
"convert_wgsl_boids",
"convert_wgsl_skybox",
"convert_wgsl_collatz"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::cast",
"back::spv::writer::test_writer_generate_id",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_statement",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_expressions",
"proc::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_types",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::control_flow",
"invalid_float",
"function_without_identifier",
"invalid_scalar_width",
"invalid_integer",
"invalid_accessor",
"parse_glsl",
"convert_glsl_quad",
"convert_wgsl_empty",
"convert_wgsl_quad",
"convert_spv_shadow"
] |
[] |
[] |
gfx-rs/naga
| 528
|
gfx-rs__naga-528
|
[
"474"
] |
04b1f44396604b4038606b83014423e309bc215c
|
diff --git a/src/arena.rs b/src/arena.rs
--- a/src/arena.rs
+++ b/src/arena.rs
@@ -1,11 +1,11 @@
-use std::{cmp::Ordering, fmt, hash, marker::PhantomData, num::NonZeroU32};
+use std::{cmp::Ordering, fmt, hash, marker::PhantomData, num::NonZeroU32, ops};
/// An unique index in the arena array that a handle points to.
/// The "non-zero" part ensures that an `Option<Handle<T>>` has
/// the same size and representation as `Handle<T>`.
type Index = NonZeroU32;
-/// A strongly typed reference to a SPIR-V element.
+/// A strongly typed reference to an arena item.
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
#[cfg_attr(
diff --git a/src/arena.rs b/src/arena.rs
--- a/src/arena.rs
+++ b/src/arena.rs
@@ -75,6 +75,47 @@ impl<T> Handle<T> {
}
}
+/// A strongly typed range of handles.
+#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
+#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
+#[cfg_attr(
+ any(feature = "serialize", feature = "deserialize"),
+ serde(transparent)
+)]
+pub struct Range<T> {
+ inner: ops::Range<u32>,
+ #[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(skip))]
+ marker: PhantomData<T>,
+}
+
+impl<T> Clone for Range<T> {
+ fn clone(&self) -> Self {
+ Range {
+ inner: self.inner.clone(),
+ marker: self.marker,
+ }
+ }
+}
+impl<T> fmt::Debug for Range<T> {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ write!(formatter, "{}..{}", self.inner.start, self.inner.end)
+ }
+}
+impl<T> Iterator for Range<T> {
+ type Item = Handle<T>;
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.inner.start < self.inner.end {
+ self.inner.start += 1;
+ Some(Handle {
+ index: NonZeroU32::new(self.inner.start).unwrap(),
+ marker: self.marker,
+ })
+ } else {
+ None
+ }
+ }
+}
+
/// An arena holding some kind of component (e.g., type, constant,
/// instruction, etc.) that can be referenced.
///
diff --git a/src/arena.rs b/src/arena.rs
--- a/src/arena.rs
+++ b/src/arena.rs
@@ -141,8 +182,6 @@ impl<T> Arena<T> {
}
/// Adds a new value to the arena, returning a typed handle.
- ///
- /// The value is not linked to any SPIR-V module.
pub fn append(&mut self, value: T) -> Handle<T> {
let position = self.data.len() + 1;
let index = unsafe { Index::new_unchecked(position as u32) };
diff --git a/src/arena.rs b/src/arena.rs
--- a/src/arena.rs
+++ b/src/arena.rs
@@ -187,13 +226,27 @@ impl<T> Arena<T> {
pub fn get_mut(&mut self, handle: Handle<T>) -> &mut T {
self.data.get_mut(handle.index.get() as usize - 1).unwrap()
}
+
+ /// Get the range of handles from a particular number of elements to the end.
+ pub fn range_from(&self, old_length: usize) -> Range<T> {
+ Range {
+ inner: old_length as u32..self.data.len() as u32,
+ marker: PhantomData,
+ }
+ }
}
-impl<T> std::ops::Index<Handle<T>> for Arena<T> {
+impl<T> ops::Index<Handle<T>> for Arena<T> {
type Output = T;
fn index(&self, handle: Handle<T>) -> &T {
- let index = handle.index.get() - 1;
- &self.data[index as usize]
+ &self.data[handle.index()]
+ }
+}
+
+impl<T> ops::Index<Range<T>> for Arena<T> {
+ type Output = [T];
+ fn index(&self, range: Range<T>) -> &[T] {
+ &self.data[range.inner.start as usize..range.inner.end as usize]
}
}
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -44,7 +44,10 @@
pub use features::Features;
use crate::{
- proc::{analyzer::Analysis, NameKey, Namer, ResolveContext, Typifier, TypifyError},
+ proc::{
+ analyzer::{Analysis, FunctionInfo},
+ EntryPointIndex, NameKey, Namer, ResolveContext, Typifier, TypifyError,
+ },
Arena, ArraySize, BinaryOperator, Binding, BuiltIn, Bytes, ConservativeDepth, Constant,
ConstantInner, DerivativeAxis, Expression, FastHashMap, Function, GlobalVariable, Handle,
ImageClass, Interpolation, LocalVariable, Module, RelationalFunction, ScalarKind, ScalarValue,
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -169,13 +172,15 @@ enum FunctionType {
/// A regular function and it's handle
Function(Handle<Function>),
/// A entry point and it's index
- EntryPoint(crate::proc::EntryPointIndex),
+ EntryPoint(EntryPointIndex),
}
/// Helper structure that stores data needed when writing the function
struct FunctionCtx<'a, 'b> {
/// The current function being written
func: FunctionType,
+ /// Analysis about the function
+ info: &'a FunctionInfo,
/// The expression arena of the current function being written
expressions: &'a Arena<Expression>,
/// A typifier that has already resolved all expressions in the function being written
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -283,7 +288,7 @@ pub struct Writer<'a, W> {
/// The selected entry point
entry_point: &'a crate::EntryPoint,
/// The index of the selected entry point
- entry_point_idx: crate::proc::EntryPointIndex,
+ entry_point_idx: EntryPointIndex,
/// Used to generate a unique number for blocks
block_id: IdGenerator,
/// Set of expressions that have associated temporary variables
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -489,8 +494,10 @@ impl<'a, W: Write> Writer<'a, W> {
// We also `clone` to satisfy the borrow checker
let name = self.names[&NameKey::Function(handle)].clone();
+ let fun_info = &self.analysis[handle];
+
// Write the function
- self.write_function(FunctionType::Function(handle), function, name)?;
+ self.write_function(FunctionType::Function(handle), function, fun_info, name)?;
writeln!(self.out)?;
}
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -498,6 +505,7 @@ impl<'a, W: Write> Writer<'a, W> {
self.write_function(
FunctionType::EntryPoint(self.entry_point_idx),
&self.entry_point.function,
+ ep_info,
"main",
)?;
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -751,6 +759,7 @@ impl<'a, W: Write> Writer<'a, W> {
&mut self,
ty: FunctionType,
func: &Function,
+ info: &FunctionInfo,
name: N,
) -> BackendResult {
// Create a new typifier and resolve all types for the current function
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -770,6 +779,7 @@ impl<'a, W: Write> Writer<'a, W> {
// Create a function context for the function being written
let ctx = FunctionCtx {
func: ty,
+ info,
expressions: &func.expressions,
typifier: &typifier,
};
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -980,6 +990,30 @@ impl<'a, W: Write> Writer<'a, W> {
write!(self.out, "{}", INDENT.repeat(indent))?;
match *sta {
+ // This is where we can generate intermediate constants for some expression types.
+ Statement::Emit(ref range) => {
+ let mut indented = true;
+ for handle in range.clone() {
+ if let Ok(ty_handle) = ctx.typifier.get_handle(handle) {
+ let min_ref_count = ctx.expressions[handle].bake_ref_count();
+ if min_ref_count <= ctx.info[handle].ref_count {
+ if !indented {
+ write!(self.out, "{}", INDENT.repeat(indent))?;
+ }
+ let name = format!("_expr{}", handle.index());
+ self.write_type(ty_handle)?;
+ write!(self.out, " {} = ", name)?;
+ self.write_expr(handle, ctx)?;
+ writeln!(self.out, ";")?;
+ self.cached_expressions.insert(handle, name);
+ indented = false;
+ }
+ }
+ }
+ if indented {
+ writeln!(self.out, ";")?;
+ }
+ }
// Blocks are simple we just need to write the block statements between braces
// We could also just print the statements but this is more readable and maps more
// closely to the IR
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1160,7 +1194,7 @@ impl<'a, W: Write> Writer<'a, W> {
let name = format!("_expr{}", expr.index());
let ty = self.module.functions[function].return_type.unwrap();
self.write_type(ty)?;
- write!(self.out, "{} = ", name)?;
+ write!(self.out, " {} = ", name)?;
self.cached_expressions.insert(expr, name);
}
write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?;
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1177,6 +1211,10 @@ impl<'a, W: Write> Writer<'a, W> {
/// # Notes
/// Doesn't add any newlines or leading/trailing spaces
fn write_expr(&mut self, expr: Handle<Expression>, ctx: &FunctionCtx<'_, '_>) -> BackendResult {
+ if let Some(name) = self.cached_expressions.get(&expr) {
+ write!(self.out, "{}", name)?;
+ return Ok(());
+ }
match ctx.expressions[expr] {
// `Access` is applied to arrays, vectors and matrices and is written as indexing
Expression::Access { base, index } => {
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1703,10 +1741,7 @@ impl<'a, W: Write> Writer<'a, W> {
self.write_expr(expr, ctx)?;
write!(self.out, ")")?
}
- Expression::Call(_function) => {
- let name = &self.cached_expressions[&expr];
- write!(self.out, "{}", name)?;
- }
+ Expression::Call(_function) => unreachable!(),
// `ArrayLength` is written as `expr.length()` and we convert it to a uint
Expression::ArrayLength(expr) => {
write!(self.out, "uint(")?;
diff --git a/src/back/mod.rs b/src/back/mod.rs
--- a/src/back/mod.rs
+++ b/src/back/mod.rs
@@ -6,3 +6,19 @@ pub mod glsl;
pub mod msl;
#[cfg(feature = "spv-out")]
pub mod spv;
+
+impl crate::Expression {
+ /// Returns the ref count, upon reaching which this expression
+ /// should be considered for baking.
+ #[allow(dead_code)]
+ fn bake_ref_count(&self) -> usize {
+ match *self {
+ // accesses are never cached, only loads are
+ crate::Expression::Access { .. } | crate::Expression::AccessIndex { .. } => !0,
+ // image operations look better when isolated
+ crate::Expression::ImageSample { .. } | crate::Expression::ImageLoad { .. } => 1,
+ // cache expressions that are referenced multiple times
+ _ => 2,
+ }
+ }
+}
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -3,7 +3,7 @@ use crate::{
arena::Handle,
proc::{
analyzer::{Analysis, FunctionInfo, GlobalUse},
- EntryPointIndex, Interface, NameKey, Namer, ResolveContext, Typifier, Visitor,
+ EntryPointIndex, NameKey, Namer, ResolveContext, Typifier,
},
FastHashMap,
};
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -11,7 +11,7 @@ use bit_set::BitSet;
use std::{
fmt::{Display, Error as FmtError, Formatter},
io::Write,
- iter, mem,
+ iter,
};
const NAMESPACE: &str = "metal";
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -71,10 +71,8 @@ pub struct Writer<W> {
out: W,
names: FastHashMap<NameKey, String>,
named_expressions: BitSet,
- visit_mask: BitSet,
typifier: Typifier,
namer: Namer,
- temp_bake_handles: Vec<Handle<crate::Expression>>,
}
fn scalar_kind_string(kind: crate::ScalarKind) -> &'static str {
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -122,39 +120,6 @@ impl crate::StorageClass {
}
}
-struct BakeExpressionVisitor<'a> {
- named_expressions: &'a mut BitSet,
- bake_handles: &'a mut Vec<Handle<crate::Expression>>,
- fun_info: &'a FunctionInfo,
- exclude: Option<Handle<crate::Expression>>,
-}
-impl Visitor for BakeExpressionVisitor<'_> {
- fn visit_expr(&mut self, handle: Handle<crate::Expression>, expr: &crate::Expression) {
- use crate::Expression as E;
- // filter out the expressions that don't need to bake
- let min_ref_count = match *expr {
- // The following expressions can be inlined nicely.
- E::AccessIndex { .. }
- | E::Constant(_)
- | E::FunctionArgument(_)
- | E::GlobalVariable(_)
- | E::LocalVariable(_) => !0,
- // Image sampling and function calling are nice to isolate
- // into separate statements even when done only once.
- E::ImageSample { .. } | E::ImageLoad { .. } | E::Call { .. } => 1,
- // Bake only expressions referenced more than once.
- _ => 2,
- };
-
- let modifier = if self.exclude == Some(handle) { 1 } else { 0 };
- if self.fun_info[handle].ref_count - modifier >= min_ref_count
- && self.named_expressions.insert(handle.index())
- {
- self.bake_handles.push(handle);
- }
- }
-}
-
enum FunctionOrigin {
Handle(Handle<crate::Function>),
EntryPoint(EntryPointIndex),
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -180,10 +145,8 @@ impl<W: Write> Writer<W> {
out,
names: FastHashMap::default(),
named_expressions: BitSet::new(),
- visit_mask: BitSet::new(),
typifier: Typifier::new(),
namer: Namer::default(),
- temp_bake_handles: Vec::new(),
}
}
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -693,49 +656,6 @@ impl<W: Write> Writer<W> {
Ok(())
}
- // Write down any required intermediate results
- fn prepare_expression(
- &mut self,
- level: Level,
- root_handle: Handle<crate::Expression>,
- context: &StatementContext,
- exclude_root: bool,
- ) -> Result<(), Error> {
- // set up the search
- self.visit_mask.clear();
- let mut interface = Interface {
- expressions: &context.expression.function.expressions,
- local_variables: &context.expression.function.local_variables,
- visitor: BakeExpressionVisitor {
- named_expressions: &mut self.named_expressions,
- bake_handles: &mut self.temp_bake_handles,
- fun_info: context.fun_info,
- exclude: if exclude_root {
- Some(root_handle)
- } else {
- None
- },
- },
- mask: &mut self.visit_mask,
- };
- // populate the bake handles
- interface.traverse_expr(root_handle);
- // bake
- let mut temp_bake_handles = mem::replace(&mut self.temp_bake_handles, Vec::new());
- for handle in temp_bake_handles.drain(..).rev() {
- write!(self.out, "{}", level)?;
- self.start_baking_expression(handle)?;
- // Make sure to temporarily unblock the expression before writing it down.
- self.named_expressions.remove(handle.index());
- self.put_expression(handle, &context.expression)?;
- self.named_expressions.insert(handle.index());
- writeln!(self.out, ";")?;
- }
-
- self.temp_bake_handles = temp_bake_handles;
- Ok(())
- }
-
fn put_block(
&mut self,
level: Level,
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -745,6 +665,19 @@ impl<W: Write> Writer<W> {
for statement in statements {
log::trace!("statement[{}] {:?}", level.0, statement);
match *statement {
+ crate::Statement::Emit(ref range) => {
+ for handle in range.clone() {
+ let min_ref_count =
+ context.expression.function.expressions[handle].bake_ref_count();
+ if min_ref_count <= context.fun_info[handle].ref_count {
+ write!(self.out, "{}", level)?;
+ self.start_baking_expression(handle)?;
+ self.put_expression(handle, &context.expression)?;
+ writeln!(self.out, ";")?;
+ self.named_expressions.insert(handle.index());
+ }
+ }
+ }
crate::Statement::Block(ref block) => {
if !block.is_empty() {
writeln!(self.out, "{}{{", level)?;
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -757,7 +690,6 @@ impl<W: Write> Writer<W> {
ref accept,
ref reject,
} => {
- self.prepare_expression(level.clone(), condition, context, false)?;
write!(self.out, "{}if (", level)?;
self.put_expression(condition, &context.expression)?;
writeln!(self.out, ") {{")?;
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -773,7 +705,6 @@ impl<W: Write> Writer<W> {
ref cases,
ref default,
} => {
- self.prepare_expression(level.clone(), selector, context, false)?;
write!(self.out, "{}switch(", level)?;
self.put_expression(selector, &context.expression)?;
writeln!(self.out, ") {{")?;
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -819,7 +750,6 @@ impl<W: Write> Writer<W> {
crate::Statement::Return {
value: Some(expr_handle),
} => {
- self.prepare_expression(level.clone(), expr_handle, context, true)?;
write!(self.out, "{}return ", level)?;
self.put_expression(expr_handle, &context.expression)?;
writeln!(self.out, ";")?;
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -836,7 +766,6 @@ impl<W: Write> Writer<W> {
writeln!(self.out, "{}discard_fragment();", level)?;
}
crate::Statement::Store { pointer, value } => {
- self.prepare_expression(level.clone(), value, context, true)?;
write!(self.out, "{}", level)?;
self.put_expression(pointer, &context.expression)?;
write!(self.out, " = ")?;
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -849,11 +778,6 @@ impl<W: Write> Writer<W> {
array_index,
value,
} => {
- self.prepare_expression(level.clone(), value, context, true)?;
- self.prepare_expression(level.clone(), coordinate, context, false)?;
- if let Some(expr) = array_index {
- self.prepare_expression(level.clone(), expr, context, false)?;
- }
write!(self.out, "{}", level)?;
self.put_expression(image, &context.expression)?;
write!(self.out, ".write(")?;
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -871,9 +795,6 @@ impl<W: Write> Writer<W> {
ref arguments,
result,
} => {
- for &arg in arguments {
- self.prepare_expression(level.clone(), arg, context, false)?;
- }
write!(self.out, "{}", level)?;
if let Some(expr) = result {
self.start_baking_expression(expr)?;
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -8,7 +8,7 @@ use crate::{
},
};
use spirv::Word;
-use std::collections::hash_map::Entry;
+use std::{collections::hash_map::Entry, ops};
use thiserror::Error;
const BITS_PER_BYTE: crate::Bytes = 8;
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -19,7 +19,7 @@ pub enum Error {
UnsupportedVersion(u8, u8),
#[error("one of the required capabilities {0:?} is missing")]
MissingCapabilities(Vec<spirv::Capability>),
- #[error("unimplemented {0:}")]
+ #[error("unimplemented {0}")]
FeatureNotImplemented(&'static str),
#[error(transparent)]
Resolve(#[from] TypifyError),
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -46,11 +46,6 @@ struct LocalVariable {
instruction: Instruction,
}
-enum RawExpression {
- Value(Word),
- Pointer(Word, spirv::StorageClass),
-}
-
#[derive(Default)]
struct Function {
signature: Option<Instruction>,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -181,6 +176,47 @@ struct LoopContext {
break_id: Option<Word>,
}
+#[derive(Default)]
+struct CachedExpressions {
+ ids: Vec<Word>,
+}
+impl CachedExpressions {
+ fn reset(&mut self, length: usize) {
+ self.ids.clear();
+ self.ids.resize(length, 0);
+ }
+}
+impl ops::Index<Handle<crate::Expression>> for CachedExpressions {
+ type Output = Word;
+ fn index(&self, h: Handle<crate::Expression>) -> &Word {
+ let id = &self.ids[h.index()];
+ if *id == 0 {
+ unreachable!("Expression {:?} is not cached!", h);
+ }
+ id
+ }
+}
+impl ops::IndexMut<Handle<crate::Expression>> for CachedExpressions {
+ fn index_mut(&mut self, h: Handle<crate::Expression>) -> &mut Word {
+ let id = &mut self.ids[h.index()];
+ if *id != 0 {
+ unreachable!("Expression {:?} is already cached!", h);
+ }
+ id
+ }
+}
+
+struct GlobalVariable {
+ /// Actual ID of the variable.
+ id: Word,
+ /// For `StorageClass::Handle` variables, this ID is recorded in the function
+ /// prelude block (and reset before every function) as `OpLoad` of the variable.
+ /// It is then used for all the global ops, such as `OpImageSample`.
+ handle_id: Word,
+ /// SPIR-V storage class.
+ class: spirv::StorageClass,
+}
+
pub struct Writer {
physical_layout: PhysicalLayout,
logical_layout: LogicalLayout,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -190,25 +226,23 @@ pub struct Writer {
annotations: Vec<Instruction>,
flags: WriterFlags,
void_type: u32,
+ //TODO: convert most of these into vectors, addressable by handle indices
lookup_type: crate::FastHashMap<LookupType, Word>,
lookup_function: crate::FastHashMap<Handle<crate::Function>, Word>,
lookup_function_type: crate::FastHashMap<LookupFunctionType, Word>,
lookup_function_call: crate::FastHashMap<Handle<crate::Expression>, Word>,
lookup_constant: crate::FastHashMap<Handle<crate::Constant>, Word>,
- lookup_global_variable:
- crate::FastHashMap<Handle<crate::GlobalVariable>, (Word, spirv::StorageClass)>,
+ global_variables: Vec<GlobalVariable>,
+ cached: CachedExpressions,
// TODO: this is a type property that depends on the global variable that uses it
// so it may require us to duplicate the type!
struct_type_handles: crate::FastHashMap<Handle<crate::Type>, crate::StorageAccess>,
gl450_ext_inst_id: Word,
layouter: Layouter,
typifier: Typifier,
+ temp_chain: Vec<Word>,
}
-// type alias, for success return of write_expression
-type ExpressionId = Word;
-type PointerExpressionId = (Word, spirv::StorageClass);
-
impl Writer {
pub fn new(options: &Options) -> Result<Self, Error> {
let (major, minor) = options.lang_version;
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -232,11 +266,13 @@ impl Writer {
lookup_function_type: crate::FastHashMap::default(),
lookup_function_call: crate::FastHashMap::default(),
lookup_constant: crate::FastHashMap::default(),
- lookup_global_variable: crate::FastHashMap::default(),
+ global_variables: Vec::new(),
+ cached: CachedExpressions::default(),
struct_type_handles: crate::FastHashMap::default(),
gl450_ext_inst_id,
layouter: Layouter::default(),
typifier: Typifier::new(),
+ temp_chain: Vec::new(),
})
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -292,22 +328,6 @@ impl Writer {
}
}
- fn get_global_variable_id(
- &mut self,
- ir_module: &crate::Module,
- handle: Handle<crate::GlobalVariable>,
- ) -> Result<(Word, spirv::StorageClass), Error> {
- Ok(match self.lookup_global_variable.entry(handle) {
- Entry::Occupied(e) => *e.get(),
- //Note: this intentionally frees `self` from borrowing
- Entry::Vacant(_) => {
- let (instruction, id, class) = self.write_global_variable(ir_module, handle)?;
- instruction.to_words(&mut self.logical_layout.declarations);
- (id, class)
- }
- })
- }
-
fn get_pointer_id(
&mut self,
arena: &Arena<crate::Type>,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -361,6 +381,7 @@ impl Writer {
fn write_function(
&mut self,
ir_function: &crate::Function,
+ info: &FunctionInfo,
ir_module: &crate::Module,
) -> Result<Word, Error> {
let mut function = Function::default();
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -438,7 +459,42 @@ impl Writer {
function_type,
));
+ let prelude_id = self.generate_id();
+ let mut prelude = Block::new(prelude_id);
+
+ // fill up the `GlobalVariable::handle_id`
+ for gv in self.global_variables.iter_mut() {
+ gv.handle_id = 0;
+ }
+ for (handle, var) in ir_module.global_variables.iter() {
+ // Handle globals are pre-emitted and should be loaded automatically.
+ if info[handle].is_empty() || var.class != crate::StorageClass::Handle {
+ continue;
+ }
+ let id = self.generate_id();
+ let result_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(var.ty))?;
+ let gv = &mut self.global_variables[handle.index()];
+ prelude
+ .body
+ .push(Instruction::load(result_type_id, id, gv.id, None));
+ gv.handle_id = id;
+ }
+ // fill up the pre-emitted expressions
+ self.cached.reset(ir_function.expressions.len());
+ for (handle, expr) in ir_function.expressions.iter() {
+ if expr.needs_pre_emit() {
+ self.cache_expression_value(
+ ir_module,
+ ir_function,
+ handle,
+ &mut prelude,
+ &mut function,
+ )?;
+ }
+ }
+
let main_id = self.generate_id();
+ function.consume(prelude, Instruction::branch(main_id));
self.write_block(
main_id,
&ir_function.body,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -464,18 +520,15 @@ impl Writer {
info: &FunctionInfo,
ir_module: &crate::Module,
) -> Result<Instruction, Error> {
- let function_id = self.write_function(&entry_point.function, ir_module)?;
+ let function_id = self.write_function(&entry_point.function, info, ir_module)?;
- let mut interface_ids = vec![];
+ let mut interface_ids = Vec::new();
for (handle, var) in ir_module.global_variables.iter() {
- let is_io = match var.class {
- crate::StorageClass::Input | crate::StorageClass::Output => {
- !info[handle].is_empty()
- }
- _ => false,
- };
- if is_io {
- let (id, _) = self.get_global_variable_id(ir_module, handle)?;
+ if info[handle].is_empty() {
+ continue;
+ }
+ if let crate::StorageClass::Input | crate::StorageClass::Output = var.class {
+ let id = self.global_variables[handle.index()].id;
interface_ids.push(id);
}
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -958,8 +1011,6 @@ impl Writer {
}
// TODO Initializer is optional and not (yet) included in the IR
-
- self.lookup_global_variable.insert(handle, (id, class));
Ok((instruction, id, class))
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1001,14 +1052,11 @@ impl Writer {
fn write_texture_coordinates(
&mut self,
ir_module: &crate::Module,
- ir_function: &crate::Function,
coordinates: Handle<crate::Expression>,
array_index: Option<Handle<crate::Expression>>,
block: &mut Block,
- function: &mut Function,
) -> Result<Word, Error> {
- let coordinate_id =
- self.write_expression(ir_module, ir_function, coordinates, block, function)?;
+ let coordinate_id = self.cached[coordinates];
Ok(if let Some(array_index) = array_index {
let coordinate_scalar_type_id = self.get_type_id(
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1050,8 +1098,7 @@ impl Writer {
let array_index_f32_id = self.generate_id();
constituent_ids[size as usize - 1] = array_index_f32_id;
- let array_index_u32_id =
- self.write_expression(ir_module, ir_function, array_index, block, function)?;
+ let array_index_u32_id = self.cached[array_index];
let cast_instruction = Instruction::unary(
spirv::Op::ConvertUToF,
coordinate_scalar_type_id,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1079,173 +1126,102 @@ impl Writer {
})
}
- /// Write an expression and return a value ID.
- fn write_expression<'a>(
- &mut self,
- ir_module: &'a crate::Module,
- ir_function: &crate::Function,
- handle: Handle<crate::Expression>,
- block: &mut Block,
- function: &mut Function,
- ) -> Result<ExpressionId, Error> {
- let (raw_expression, result_type_id) =
- self.write_expression_raw(ir_module, ir_function, handle, block, function)?;
- Ok(match raw_expression {
- RawExpression::Value(id) => id,
- RawExpression::Pointer(id, _) => {
- let load_id = self.generate_id();
- block
- .body
- .push(Instruction::load(result_type_id, load_id, id, None));
- load_id
- }
- })
- }
-
- /// Write an expression and return a pointer ID to the result.
- fn write_expression_pointer<'a>(
- &mut self,
- ir_module: &'a crate::Module,
- ir_function: &crate::Function,
- handle: Handle<crate::Expression>,
- block: &mut Block,
- function: &mut Function,
- ) -> Result<PointerExpressionId, Error> {
- let (raw_expression, _) =
- self.write_expression_raw(ir_module, ir_function, handle, block, function)?;
- Ok(match raw_expression {
- RawExpression::Value(_id) => unimplemented!(
- "Expression {:?} is not a pointer",
- ir_function.expressions[handle]
- ),
- RawExpression::Pointer(id, class) => (id, class),
- })
- }
-
- /// Write an expression, and the result may be either a pointer, or a value.
- fn write_expression_raw<'a>(
+ /// Cache an expression for a value.
+ fn cache_expression_value<'a>(
&mut self,
ir_module: &'a crate::Module,
ir_function: &crate::Function,
expr_handle: Handle<crate::Expression>,
block: &mut Block,
function: &mut Function,
- ) -> Result<(RawExpression, ExpressionId), Error> {
+ ) -> Result<(), Error> {
let result_lookup_ty = match self.typifier.get_handle(expr_handle) {
Ok(ty_handle) => LookupType::Handle(ty_handle),
Err(inner) => LookupType::Local(LocalType::from_inner(inner).unwrap()),
};
let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?;
- let raw_expr = match ir_function.expressions[expr_handle] {
+ let id = match ir_function.expressions[expr_handle] {
crate::Expression::Access { base, index } => {
- let id = self.generate_id();
- let (raw_base_expression, _) =
- self.write_expression_raw(ir_module, ir_function, base, block, function)?;
- let index_id =
- self.write_expression(ir_module, ir_function, index, block, function)?;
- let base_inner = self.typifier.get(base, &ir_module.types);
-
- match raw_base_expression {
- RawExpression::Value(base_id) => {
- if let crate::TypeInner::Array { .. } = *base_inner {
- return Err(Error::FeatureNotImplemented(
- "accessing index of a value array",
+ let base_is_var = match ir_function.expressions[base] {
+ crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => {
+ true
+ }
+ _ => self.cached.ids[base.index()] == 0,
+ };
+ if base_is_var {
+ 0
+ } else {
+ let index_id = self.cached[index];
+ match *self.typifier.get(base, &ir_module.types) {
+ crate::TypeInner::Vector { .. } => {
+ let id = self.generate_id();
+ let base_id = self.cached[base];
+ block.body.push(Instruction::vector_extract_dynamic(
+ result_type_id,
+ id,
+ base_id,
+ index_id,
));
+ id
+ }
+ //TODO: support `crate::TypeInner::Array { .. }` ?
+ ref other => {
+ log::error!("Unable to access {:?}", other);
+ return Err(Error::FeatureNotImplemented("access for type"));
}
-
- block.body.push(Instruction::vector_extract_dynamic(
- result_type_id,
- id,
- base_id,
- index_id,
- ));
-
- RawExpression::Value(id)
- }
- RawExpression::Pointer(base_id, class) => {
- let pointer_type_id = self.create_pointer_type(result_type_id, class);
-
- block.body.push(Instruction::access_chain(
- pointer_type_id,
- id,
- base_id,
- &[index_id],
- ));
-
- RawExpression::Pointer(id, class)
}
}
}
crate::Expression::AccessIndex { base, index } => {
- let id = self.generate_id();
- let (raw_base_expression, _) =
- self.write_expression_raw(ir_module, ir_function, base, block, function)?;
-
- match raw_base_expression {
- RawExpression::Value(base_id) => {
- block.body.push(Instruction::composite_extract(
- result_type_id,
- id,
- base_id,
- &[index],
- ));
-
- RawExpression::Value(id)
+ let base_is_var = match ir_function.expressions[base] {
+ crate::Expression::GlobalVariable(_) | crate::Expression::LocalVariable(_) => {
+ true
}
- RawExpression::Pointer(base_id, class) => {
- let pointer_type_id = self.create_pointer_type(result_type_id, class);
-
- let const_ty_id = self.get_type_id(
- &ir_module.types,
- LookupType::Local(LocalType::Scalar {
- kind: crate::ScalarKind::Sint,
- width: 4,
- }),
- )?;
- let const_id = self.create_constant(const_ty_id, &[index]);
-
- block.body.push(Instruction::access_chain(
- pointer_type_id,
- id,
- base_id,
- &[const_id],
- ));
-
- RawExpression::Pointer(id, class)
+ _ => self.cached.ids[base.index()] == 0,
+ };
+ if base_is_var {
+ 0
+ } else {
+ match *self.typifier.get(base, &ir_module.types) {
+ crate::TypeInner::Vector { .. }
+ | crate::TypeInner::Matrix { .. }
+ | crate::TypeInner::Array { .. }
+ | crate::TypeInner::Struct { .. } => {
+ let id = self.generate_id();
+ let base_id = self.cached[base];
+ block.body.push(Instruction::composite_extract(
+ result_type_id,
+ id,
+ base_id,
+ &[index],
+ ));
+ id
+ }
+ ref other => {
+ log::error!("Unable to access index of {:?}", other);
+ return Err(Error::FeatureNotImplemented("access index for type"));
+ }
}
}
}
- crate::Expression::GlobalVariable(handle) => {
- let (id, class) = self.get_global_variable_id(&ir_module, handle)?;
- RawExpression::Pointer(id, class)
- }
- crate::Expression::Constant(handle) => {
- let id = self.lookup_constant[&handle];
- RawExpression::Value(id)
- }
- crate::Expression::Compose { ty, ref components } => {
- let base_type_id = self.get_type_id(&ir_module.types, LookupType::Handle(ty))?;
-
+ crate::Expression::GlobalVariable(handle) => self.global_variables[handle.index()].id,
+ crate::Expression::Constant(handle) => self.lookup_constant[&handle],
+ crate::Expression::Compose {
+ ty: _,
+ ref components,
+ } => {
+ //TODO: avoid allocation
let mut constituent_ids = Vec::with_capacity(components.len());
- for component in components {
- let component_id = self.write_expression(
- ir_module,
- &ir_function,
- *component,
- block,
- function,
- )?;
+ for &component in components {
+ let component_id = self.cached[component];
constituent_ids.push(component_id);
}
-
- let id = self.write_composite_construct(base_type_id, &constituent_ids, block);
- RawExpression::Value(id)
+ self.write_composite_construct(result_type_id, &constituent_ids, block)
}
crate::Expression::Unary { op, expr } => {
let id = self.generate_id();
- let expr_id =
- self.write_expression(ir_module, ir_function, expr, block, function)?;
+ let expr_id = self.cached[expr];
let expr_ty_inner = self.typifier.get(expr, &ir_module.types);
let spirv_op = match op {
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1264,14 +1240,12 @@ impl Writer {
block
.body
.push(Instruction::unary(spirv_op, result_type_id, id, expr_id));
- RawExpression::Value(id)
+ id
}
crate::Expression::Binary { op, left, right } => {
let id = self.generate_id();
- let left_id =
- self.write_expression(ir_module, ir_function, left, block, function)?;
- let right_id =
- self.write_expression(ir_module, ir_function, right, block, function)?;
+ let left_id = self.cached[left];
+ let right_id = self.cached[right];
let left_ty_inner = self.typifier.get(left, &ir_module.types);
let right_ty_inner = self.typifier.get(right, &ir_module.types);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1394,7 +1368,7 @@ impl Writer {
if preserve_order { left_id } else { right_id },
if preserve_order { right_id } else { left_id },
));
- RawExpression::Value(id)
+ id
}
crate::Expression::Math {
fun,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1408,19 +1382,14 @@ impl Writer {
Custom(Instruction),
}
- let arg0_id =
- self.write_expression(ir_module, ir_function, arg, block, function)?;
+ let arg0_id = self.cached[arg];
let arg_scalar_kind = self.typifier.get(arg, &ir_module.types).scalar_kind();
let arg1_id = match arg1 {
- Some(id) => {
- self.write_expression(ir_module, ir_function, id, block, function)?
- }
+ Some(handle) => self.cached[handle],
None => 0,
};
let arg2_id = match arg2 {
- Some(id) => {
- self.write_expression(ir_module, ir_function, id, block, function)?
- }
+ Some(handle) => self.cached[handle],
None => 0,
};
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1536,27 +1505,34 @@ impl Writer {
),
MathOp::Custom(inst) => inst,
});
- RawExpression::Value(id)
+ id
}
- crate::Expression::LocalVariable(variable) => {
- let local_var = &function.variables[&variable];
- RawExpression::Pointer(local_var.id, spirv::StorageClass::Function)
+ crate::Expression::LocalVariable(variable) => function.variables[&variable].id,
+ crate::Expression::Load { pointer } => {
+ let (pointer_id, _) = self.write_expression_pointer(
+ ir_module,
+ ir_function,
+ pointer,
+ block,
+ function,
+ )?;
+
+ let id = self.generate_id();
+ block
+ .body
+ .push(Instruction::load(result_type_id, id, pointer_id, None));
+ id
}
crate::Expression::FunctionArgument(index) => {
- let id = function.parameters[index as usize].result_id.unwrap();
- RawExpression::Value(id)
- }
- crate::Expression::Call(_function) => {
- let id = self.lookup_function_call[&expr_handle];
- RawExpression::Value(id)
+ function.parameters[index as usize].result_id.unwrap()
}
+ crate::Expression::Call(_function) => self.lookup_function_call[&expr_handle],
crate::Expression::As {
expr,
kind,
convert,
} => {
- let expr_id =
- self.write_expression(ir_module, ir_function, expr, block, function)?;
+ let expr_id = self.cached[expr];
let expr_kind = self
.typifier
.get(expr, &ir_module.types)
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1576,8 +1552,7 @@ impl Writer {
let id = self.generate_id();
let instruction = Instruction::unary(op, result_type_id, id, expr_id);
block.body.push(instruction);
-
- RawExpression::Value(id)
+ id
}
crate::Expression::ImageLoad {
image,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1585,16 +1560,9 @@ impl Writer {
array_index,
index,
} => {
- let image_id =
- self.write_expression(ir_module, ir_function, image, block, function)?;
- let coordinate_id = self.write_texture_coordinates(
- ir_module,
- ir_function,
- coordinate,
- array_index,
- block,
- function,
- )?;
+ let image_id = self.get_expression_global(ir_function, image);
+ let coordinate_id =
+ self.write_texture_coordinates(ir_module, coordinate, array_index, block)?;
let id = self.generate_id();
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1608,21 +1576,20 @@ impl Writer {
};
if let Some(index) = index {
- let image_ops = match *image_ty {
+ let index_id = self.cached[index];
+ let image_ops = match *self.typifier.get(image, &ir_module.types) {
crate::TypeInner::Image {
class: crate::ImageClass::Sampled { multi: true, .. },
..
} => spirv::ImageOperands::SAMPLE,
_ => spirv::ImageOperands::LOD,
};
- let index_id =
- self.write_expression(ir_module, ir_function, index, block, function)?;
instruction.add_operand(image_ops.bits());
instruction.add_operand(index_id);
}
block.body.push(instruction);
- RawExpression::Value(id)
+ id
}
crate::Expression::ImageSample {
image,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1635,8 +1602,7 @@ impl Writer {
} => {
use super::instructions::SampleLod;
// image
- let image_id =
- self.write_expression(ir_module, ir_function, image, block, function)?;
+ let image_id = self.get_expression_global(ir_function, image);
let image_type = self.typifier.get_handle(image).unwrap();
// OpTypeSampledImage
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1645,16 +1611,9 @@ impl Writer {
LookupType::Local(LocalType::SampledImage { image_type }),
)?;
- let sampler_id =
- self.write_expression(ir_module, ir_function, sampler, block, function)?;
- let coordinate_id = self.write_texture_coordinates(
- ir_module,
- ir_function,
- coordinate,
- array_index,
- block,
- function,
- )?;
+ let sampler_id = self.get_expression_global(ir_function, sampler);
+ let coordinate_id =
+ self.write_texture_coordinates(ir_module, coordinate, array_index, block)?;
let sampled_image_id = self.generate_id();
block.body.push(Instruction::sampled_image(
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1665,14 +1624,7 @@ impl Writer {
));
let id = self.generate_id();
- let depth_id = match depth_ref {
- Some(handle) => {
- let expr_id =
- self.write_expression(ir_module, ir_function, handle, block, function)?;
- Some(expr_id)
- }
- None => None,
- };
+ let depth_id = depth_ref.map(|handle| self.cached[handle]);
let mut main_instruction = match level {
crate::SampleLevel::Zero => {
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1715,13 +1667,7 @@ impl Writer {
depth_id,
);
- let lod_id = self.write_expression(
- ir_module,
- ir_function,
- lod_handle,
- block,
- function,
- )?;
+ let lod_id = self.cached[lod_handle];
inst.add_operand(spirv::ImageOperands::LOD.bits());
inst.add_operand(lod_id);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1737,13 +1683,7 @@ impl Writer {
depth_id,
);
- let bias_id = self.write_expression(
- ir_module,
- ir_function,
- bias_handle,
- block,
- function,
- )?;
+ let bias_id = self.cached[bias_handle];
inst.add_operand(spirv::ImageOperands::BIAS.bits());
inst.add_operand(bias_id);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1759,10 +1699,8 @@ impl Writer {
depth_id,
);
- let x_id =
- self.write_expression(ir_module, ir_function, x, block, function)?;
- let y_id =
- self.write_expression(ir_module, ir_function, y, block, function)?;
+ let x_id = self.cached[x];
+ let y_id = self.cached[y];
inst.add_operand(spirv::ImageOperands::GRAD.bits());
inst.add_operand(x_id);
inst.add_operand(y_id);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1778,7 +1716,7 @@ impl Writer {
}
block.body.push(main_instruction);
- RawExpression::Value(id)
+ id
}
crate::Expression::Select {
condition,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1786,17 +1724,14 @@ impl Writer {
reject,
} => {
let id = self.generate_id();
- let condition_id =
- self.write_expression(ir_module, ir_function, condition, block, function)?;
- let accept_id =
- self.write_expression(ir_module, ir_function, accept, block, function)?;
- let reject_id =
- self.write_expression(ir_module, ir_function, reject, block, function)?;
+ let condition_id = self.cached[condition];
+ let accept_id = self.cached[accept];
+ let reject_id = self.cached[reject];
let instruction =
Instruction::select(result_type_id, id, condition_id, accept_id, reject_id);
block.body.push(instruction);
- RawExpression::Value(id)
+ id
}
ref other => {
log::error!("unimplemented {:?}", other);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1804,7 +1739,88 @@ impl Writer {
}
};
- Ok((raw_expr, result_type_id))
+ self.cached[expr_handle] = id;
+ Ok(())
+ }
+
+ /// Write a left-hand-side expression, returning an `id` of the pointer.
+ fn write_expression_pointer<'a>(
+ &mut self,
+ ir_module: &'a crate::Module,
+ ir_function: &crate::Function,
+ mut expr_handle: Handle<crate::Expression>,
+ block: &mut Block,
+ function: &mut Function,
+ ) -> Result<(Word, spirv::StorageClass), Error> {
+ let result_lookup_ty = match self.typifier.get_handle(expr_handle) {
+ Ok(ty_handle) => LookupType::Handle(ty_handle),
+ Err(inner) => LookupType::Local(LocalType::from_inner(inner).unwrap()),
+ };
+ let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?;
+ self.temp_chain.clear();
+ let (root_id, class) = loop {
+ expr_handle = match ir_function.expressions[expr_handle] {
+ crate::Expression::Access { base, index } => {
+ let index_id = self.cached[index];
+ self.temp_chain.push(index_id);
+ base
+ }
+ crate::Expression::AccessIndex { base, index } => {
+ let const_ty_id = self.get_type_id(
+ &ir_module.types,
+ LookupType::Local(LocalType::Scalar {
+ kind: crate::ScalarKind::Sint,
+ width: 4,
+ }),
+ )?;
+ let const_id = self.create_constant(const_ty_id, &[index]);
+ self.temp_chain.push(const_id);
+ base
+ }
+ crate::Expression::GlobalVariable(handle) => {
+ let gv = &self.global_variables[handle.index()];
+ break (gv.id, gv.class);
+ }
+ crate::Expression::LocalVariable(variable) => {
+ let local_var = &function.variables[&variable];
+ break (local_var.id, spirv::StorageClass::Function);
+ }
+ ref other => unimplemented!("Unexpected pointer expression {:?}", other),
+ }
+ };
+
+ let id = if self.temp_chain.is_empty() {
+ root_id
+ } else {
+ self.temp_chain.reverse();
+ let id = self.generate_id();
+ let pointer_type_id = self.create_pointer_type(result_type_id, class);
+ block.body.push(Instruction::access_chain(
+ pointer_type_id,
+ id,
+ root_id,
+ &self.temp_chain,
+ ));
+ id
+ };
+ Ok((id, class))
+ }
+
+ fn get_expression_global(
+ &self,
+ ir_function: &crate::Function,
+ expr_handle: Handle<crate::Expression>,
+ ) -> Word {
+ match ir_function.expressions[expr_handle] {
+ crate::Expression::GlobalVariable(handle) => {
+ let id = self.global_variables[handle.index()].handle_id;
+ if id == 0 {
+ unreachable!("Global variable {:?} doesn't have a handle ID", handle);
+ }
+ id
+ }
+ ref other => unreachable!("Unexpected global expression {:?}", other),
+ }
}
#[allow(clippy::too_many_arguments)]
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1825,6 +1841,17 @@ impl Writer {
unimplemented!("No statements are expected after block termination");
}
match *statement {
+ crate::Statement::Emit(ref range) => {
+ for handle in range.clone() {
+ self.cache_expression_value(
+ ir_module,
+ ir_function,
+ handle,
+ &mut block,
+ function,
+ )?;
+ }
+ }
crate::Statement::Block(ref block_statements) => {
let scope_id = self.generate_id();
function.consume(block, Instruction::branch(scope_id));
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1847,13 +1874,7 @@ impl Writer {
ref accept,
ref reject,
} => {
- let condition_id = self.write_expression(
- ir_module,
- ir_function,
- condition,
- &mut block,
- function,
- )?;
+ let condition_id = self.cached[condition];
let merge_id = self.generate_id();
block.body.push(Instruction::selection_merge(
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1911,13 +1932,7 @@ impl Writer {
ref cases,
ref default,
} => {
- let selector_id = self.write_expression(
- ir_module,
- ir_function,
- selector,
- &mut block,
- function,
- )?;
+ let selector_id = self.cached[selector];
let merge_id = self.generate_id();
block.body.push(Instruction::selection_merge(
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2028,8 +2043,7 @@ impl Writer {
Some(Instruction::branch(loop_context.continuing_id.unwrap()));
}
crate::Statement::Return { value: Some(value) } => {
- let id =
- self.write_expression(ir_module, ir_function, value, &mut block, function)?;
+ let id = self.cached[value];
block.termination = Some(Instruction::return_value(id));
}
crate::Statement::Return { value: None } => {
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2046,8 +2060,7 @@ impl Writer {
&mut block,
function,
)?;
- let value_id =
- self.write_expression(ir_module, ir_function, value, &mut block, function)?;
+ let value_id = self.cached[value];
block
.body
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2059,18 +2072,14 @@ impl Writer {
array_index,
value,
} => {
- let image_id =
- self.write_expression(ir_module, ir_function, image, &mut block, function)?;
+ let image_id = self.get_expression_global(ir_function, image);
let coordinate_id = self.write_texture_coordinates(
ir_module,
- ir_function,
coordinate,
array_index,
&mut block,
- function,
)?;
- let value_id =
- self.write_expression(ir_module, ir_function, value, &mut block, function)?;
+ let value_id = self.cached[value];
block
.body
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2085,19 +2094,14 @@ impl Writer {
//TODO: avoid heap allocation
let mut argument_ids = vec![];
- for argument in arguments {
- let arg_id = self.write_expression(
- ir_module,
- ir_function,
- *argument,
- &mut block,
- function,
- )?;
+ for &argument in arguments {
+ let arg_id = self.cached[argument];
argument_ids.push(arg_id);
}
let type_id = match result {
Some(expr) => {
+ self.cached[expr] = id;
self.lookup_function_call.insert(expr, id);
let ty_handle =
ir_module.functions[local_function].return_type.unwrap();
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2156,14 +2160,23 @@ impl Writer {
self.write_constant_type(id, &constant.inner, &ir_module.types)?;
}
- for (_, var) in ir_module.global_variables.iter() {
+ self.global_variables.clear();
+ for (handle, var) in ir_module.global_variables.iter() {
if let crate::TypeInner::Struct { .. } = ir_module.types[var.ty].inner {
self.struct_type_handles.insert(var.ty, var.storage_access);
}
+ let (instruction, id, class) = self.write_global_variable(ir_module, handle)?;
+ instruction.to_words(&mut self.logical_layout.declarations);
+ self.global_variables.push(GlobalVariable {
+ id,
+ handle_id: 0,
+ class,
+ });
}
for (handle, ir_function) in ir_module.functions.iter() {
- let id = self.write_function(ir_function, ir_module)?;
+ let info = &analysis[handle];
+ let id = self.write_function(ir_function, info, ir_module)?;
self.lookup_function.insert(handle, id);
}
diff --git a/src/front/mod.rs b/src/front/mod.rs
--- a/src/front/mod.rs
+++ b/src/front/mod.rs
@@ -6,3 +6,29 @@ pub mod glsl;
pub mod spv;
#[cfg(feature = "wgsl-in")]
pub mod wgsl;
+
+/// Helper class to emit expressions
+#[allow(dead_code)]
+#[derive(Default)]
+struct Emitter {
+ start_len: Option<usize>,
+}
+
+#[allow(dead_code)]
+impl Emitter {
+ fn start(&mut self, arena: &crate::Arena<crate::Expression>) {
+ if self.start_len.is_some() {
+ unreachable!("Emitting has already started!");
+ }
+ self.start_len = Some(arena.len());
+ }
+ #[must_use]
+ fn finish(&mut self, arena: &crate::Arena<crate::Expression>) -> Option<crate::Statement> {
+ let start_len = self.start_len.take().unwrap();
+ if start_len != arena.len() {
+ Some(crate::Statement::Emit(arena.range_from(start_len)))
+ } else {
+ None
+ }
+ }
+}
diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs
--- a/src/front/spv/image.rs
+++ b/src/front/spv/image.rs
@@ -18,6 +18,18 @@ bitflags::bitflags! {
}
}
+impl Arena<crate::Expression> {
+ fn get_global_var(
+ &self,
+ handle: Handle<crate::Expression>,
+ ) -> Result<Handle<crate::GlobalVariable>, Error> {
+ match self[handle] {
+ crate::Expression::GlobalVariable(handle) => Ok(handle),
+ ref other => Err(Error::InvalidGlobalVar(other.clone())),
+ }
+ }
+}
+
/// Return the texture coordinates separated from the array layer,
/// and/or divided by the projection term.
///
diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs
--- a/src/front/spv/image.rs
+++ b/src/front/spv/image.rs
@@ -203,7 +215,7 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
}
let image_lexp = self.lookup_expression.lookup(image_id)?;
- let image_var_handle = expressions[image_lexp.handle].as_global_var()?;
+ let image_var_handle = expressions.get_global_var(image_lexp.handle)?;
let image_var = &global_arena[image_var_handle];
let coord_lexp = self.lookup_expression.lookup(coordinate_id)?;
diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs
--- a/src/front/spv/image.rs
+++ b/src/front/spv/image.rs
@@ -274,7 +286,7 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
}
let image_lexp = self.lookup_expression.lookup(image_id)?;
- let image_var_handle = expressions[image_lexp.handle].as_global_var()?;
+ let image_var_handle = expressions.get_global_var(image_lexp.handle)?;
let image_var = &global_arena[image_var_handle];
let coord_lexp = self.lookup_expression.lookup(coordinate_id)?;
diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs
--- a/src/front/spv/image.rs
+++ b/src/front/spv/image.rs
@@ -354,8 +366,8 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
let coord_lexp = self.lookup_expression.lookup(coordinate_id)?;
let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle;
- let image_var_handle = expressions[si_lexp.image].as_global_var()?;
- let sampler_var_handle = expressions[si_lexp.sampler].as_global_var()?;
+ let image_var_handle = expressions.get_global_var(si_lexp.image)?;
+ let sampler_var_handle = expressions.get_global_var(si_lexp.sampler)?;
log::debug!(
"\t\t\tImage {:?} sampled with {:?}",
image_var_handle,
diff --git a/src/front/spv/image.rs b/src/front/spv/image.rs
--- a/src/front/spv/image.rs
+++ b/src/front/spv/image.rs
@@ -445,8 +457,8 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
let si_lexp = self.lookup_sampled_image.lookup(sampled_image_id)?;
let coord_lexp = self.lookup_expression.lookup(coordinate_id)?;
let coord_type_handle = self.lookup_type.lookup(coord_lexp.type_id)?.handle;
- let image_var_handle = expressions[si_lexp.image].as_global_var()?;
- let sampler_var_handle = expressions[si_lexp.sampler].as_global_var()?;
+ let image_var_handle = expressions.get_global_var(si_lexp.image)?;
+ let sampler_var_handle = expressions.get_global_var(si_lexp.sampler)?;
log::debug!(
"\t\t\tImage {:?} sampled with comparison {:?}",
image_var_handle,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -67,15 +67,6 @@ impl Instruction {
}
}
-impl crate::Expression {
- fn as_global_var(&self) -> Result<Handle<crate::GlobalVariable>, Error> {
- match *self {
- crate::Expression::GlobalVariable(handle) => Ok(handle),
- _ => Err(Error::InvalidGlobalVar(self.clone())),
- }
- }
-}
-
impl crate::TypeInner {
fn can_comparison_sample(&self) -> bool {
match *self {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -592,6 +583,8 @@ impl<I: Iterator<Item = u32>> Parser<I> {
) -> Result<ControlFlowNode, Error> {
let mut block = Vec::new();
let mut phis = Vec::new();
+ let mut emitter = super::Emitter::default();
+ emitter.start(expressions);
let mut merge = None;
let terminator = loop {
use spirv::Op;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -613,6 +606,8 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::Variable => {
inst.expect_at_least(4)?;
+ block.extend(emitter.finish(expressions));
+
let result_type_id = self.next()?;
let result_id = self.next()?;
let storage = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -629,6 +624,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
} else {
None
};
+
let name = self
.future_decor
.remove(&result_id)
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -641,6 +637,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
ty: self.lookup_type.lookup(result_type_id)?.handle,
init,
});
+
self.lookup_expression.insert(
result_id,
LookupExpression {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -649,9 +646,11 @@ impl<I: Iterator<Item = u32>> Parser<I> {
type_id: result_type_id,
},
);
+ emitter.start(expressions);
}
Op::Phi => {
inst.expect_at_least(3)?;
+ block.extend(emitter.finish(expressions));
let result_type_id = self.next()?;
let result_id = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -680,13 +679,16 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
phis.push(phi);
+ emitter.start(expressions);
}
Op::AccessChain => {
struct AccessExpression {
base_handle: Handle<crate::Expression>,
type_id: spirv::Word,
}
+
inst.expect_at_least(4)?;
+
let result_type_id = self.next()?;
let result_id = self.next()?;
let base_id = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -774,6 +776,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::VectorExtractDynamic => {
inst.expect(5)?;
+
let result_type_id = self.next()?;
let id = self.next()?;
let composite_id = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -822,6 +825,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::VectorInsertDynamic => {
inst.expect(6)?;
+
let result_type_id = self.next()?;
let id = self.next()?;
let composite_id = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -871,6 +875,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::CompositeExtract => {
inst.expect_at_least(4)?;
+
let result_type_id = self.next()?;
let result_id = self.next()?;
let base_id = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -911,6 +916,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::CompositeInsert => {
inst.expect_at_least(5)?;
+
let result_type_id = self.next()?;
let id = self.next()?;
let object_id = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -941,6 +947,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::CompositeConstruct => {
inst.expect_at_least(3)?;
+
let result_type_id = self.next()?;
let id = self.next()?;
let mut components = Vec::with_capacity(inst.wc as usize - 2);
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -964,6 +971,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::Load => {
inst.expect_at_least(4)?;
+
let result_type_id = self.next()?;
let result_id = self.next()?;
let pointer_id = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -971,17 +979,30 @@ impl<I: Iterator<Item = u32>> Parser<I> {
inst.expect(5)?;
let _memory_access = self.next()?;
}
- let base_expr = self.lookup_expression.lookup(pointer_id)?.clone();
+
+ let base_lexp = self.lookup_expression.lookup(pointer_id)?;
+ let type_lookup = self.lookup_type.lookup(base_lexp.type_id)?;
+ let handle = match type_arena[type_lookup.handle].inner {
+ crate::TypeInner::Image { .. } | crate::TypeInner::Sampler { .. } => {
+ base_lexp.handle
+ }
+ _ => expressions.append(crate::Expression::Load {
+ pointer: base_lexp.handle,
+ }),
+ };
+
self.lookup_expression.insert(
result_id,
LookupExpression {
- handle: base_expr.handle, // pass-through pointers
+ handle,
type_id: result_type_id,
},
);
}
Op::Store => {
inst.expect_at_least(3)?;
+ block.extend(emitter.finish(expressions));
+
let pointer_id = self.next()?;
let value_id = self.next()?;
if inst.wc != 3 {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -994,6 +1015,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
pointer: base_expr.handle,
value: value_expr.handle,
});
+ emitter.start(expressions);
}
// Arithmetic Instructions +, -, *, /, %
Op::SNegate | Op::FNegate => {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1030,6 +1052,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::Transpose => {
inst.expect(4)?;
+
let result_type_id = self.next()?;
let result_id = self.next()?;
let matrix_id = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1050,6 +1073,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::Dot => {
inst.expect(5)?;
+
let result_type_id = self.next()?;
let result_id = self.next()?;
let left_id = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1260,6 +1284,8 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::FunctionCall => {
inst.expect_at_least(4)?;
+ block.extend(emitter.finish(expressions));
+
let result_type_id = self.next()?;
let result_id = self.next()?;
let func_id = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1292,6 +1318,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
arguments,
result,
});
+ emitter.start(expressions);
}
Op::ExtInst => {
use crate::MathFunction as Mf;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1299,6 +1326,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
let base_wc = 5;
inst.expect_at_least(base_wc)?;
+
let result_type_id = self.next()?;
let result_id = self.next()?;
let set_id = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1464,7 +1492,6 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
Op::Switch => {
inst.expect_at_least(3)?;
-
let selector = self.next()?;
let default = self.next()?;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1532,6 +1559,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
};
+ block.extend(emitter.finish(expressions));
Ok(ControlFlowNode {
id: block_id,
ty: None,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1590,6 +1618,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
use crate::Statement as S;
for statement in statements.iter_mut() {
match *statement {
+ S::Emit(_) => {}
S::Block(ref mut block) => {
self.patch_function_call_statements(block)?;
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -24,6 +24,7 @@ use codespan_reporting::{
};
use std::{
io::{self, Write},
+ iter,
num::NonZeroU32,
ops::Range,
};
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -173,7 +174,11 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> {
}
}
- fn as_expression<'t>(&'t mut self, block: &'t mut crate::Block) -> ExpressionContext<'a, 't, '_>
+ fn as_expression<'t>(
+ &'t mut self,
+ block: &'t mut crate::Block,
+ emitter: &'t mut super::Emitter,
+ ) -> ExpressionContext<'a, 't, '_>
where
'temp: 't,
{
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -188,6 +193,7 @@ impl<'a, 'temp> StatementContext<'a, 'temp, '_> {
functions: self.functions,
arguments: self.arguments,
block,
+ emitter,
}
}
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -208,6 +214,7 @@ struct ExpressionContext<'input, 'temp, 'out> {
arguments: &'out [crate::FunctionArgument],
functions: &'out Arena<crate::Function>,
block: &'temp mut crate::Block,
+ emitter: &'temp mut super::Emitter,
}
impl<'a> ExpressionContext<'a, '_, '_> {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -223,6 +230,7 @@ impl<'a> ExpressionContext<'a, '_, '_> {
functions: self.functions,
arguments: self.arguments,
block: self.block,
+ emitter: self.emitter,
}
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -560,7 +568,7 @@ impl Parser {
None
};
let offset = if lexer.skip(Token::Separator(',')) {
- Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?)
+ Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?)
} else {
None
};
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -592,7 +600,7 @@ impl Parser {
lexer.expect(Token::Separator(','))?;
let level = self.parse_general_expression(lexer, ctx.reborrow())?;
let offset = if lexer.skip(Token::Separator(',')) {
- Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?)
+ Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?)
} else {
None
};
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -624,7 +632,7 @@ impl Parser {
lexer.expect(Token::Separator(','))?;
let bias = self.parse_general_expression(lexer, ctx.reborrow())?;
let offset = if lexer.skip(Token::Separator(',')) {
- Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?)
+ Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?)
} else {
None
};
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -658,7 +666,7 @@ impl Parser {
lexer.expect(Token::Separator(','))?;
let y = self.parse_general_expression(lexer, ctx.reborrow())?;
let offset = if lexer.skip(Token::Separator(',')) {
- Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?)
+ Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?)
} else {
None
};
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -690,7 +698,7 @@ impl Parser {
lexer.expect(Token::Separator(','))?;
let reference = self.parse_general_expression(lexer, ctx.reborrow())?;
let offset = if lexer.skip(Token::Separator(',')) {
- Some(self.parse_const_expression(lexer, None, ctx.types, ctx.constants)?)
+ Some(self.parse_const_expression(lexer, ctx.types, ctx.constants)?)
} else {
None
};
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -787,6 +795,7 @@ impl Parser {
let handle =
match self.parse_local_function_call(lexer, name, ctx.reborrow())? {
Some((function, arguments)) => {
+ ctx.block.extend(ctx.emitter.finish(ctx.expressions));
let result =
Some(ctx.expressions.append(crate::Expression::Call(function)));
ctx.block.push(crate::Statement::Call {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -794,6 +803,8 @@ impl Parser {
arguments,
result,
});
+ // restart the emitter
+ ctx.emitter.start(ctx.expressions);
result
}
None => None,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -805,15 +816,16 @@ impl Parser {
Ok(Some(ctx.expressions.append(expr)))
}
- fn parse_const_expression<'a>(
+ fn parse_const_expression_impl<'a>(
&mut self,
+ first_token_span: TokenSpan<'a>,
lexer: &mut Lexer<'a>,
register_name: Option<&'a str>,
type_arena: &mut Arena<crate::Type>,
const_arena: &mut Arena<crate::Constant>,
) -> Result<Handle<crate::Constant>, Error<'a>> {
self.scopes.push(Scope::ConstantExpr);
- let inner = match lexer.next() {
+ let inner = match first_token_span {
(Token::Word("true"), _) => crate::ConstantInner::Scalar {
width: 1,
value: crate::ScalarValue::Bool(true),
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -848,8 +860,7 @@ impl Parser {
if !components.is_empty() {
lexer.expect(Token::Separator(','))?;
}
- let component =
- self.parse_const_expression(lexer, None, type_arena, const_arena)?;
+ let component = self.parse_const_expression(lexer, type_arena, const_arena)?;
components.push(component);
}
crate::ConstantInner::Composite {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -878,6 +889,15 @@ impl Parser {
Ok(handle)
}
+ fn parse_const_expression<'a>(
+ &mut self,
+ lexer: &mut Lexer<'a>,
+ type_arena: &mut Arena<crate::Type>,
+ const_arena: &mut Arena<crate::Constant>,
+ ) -> Result<Handle<crate::Constant>, Error<'a>> {
+ self.parse_const_expression_impl(lexer.next(), lexer, None, type_arena, const_arena)
+ }
+
fn parse_primary_expression<'a>(
&mut self,
lexer: &mut Lexer<'a>,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -890,36 +910,18 @@ impl Parser {
lexer.expect(Token::Paren(')'))?;
expr
}
- (Token::Word("true"), _) => {
- let expr = ctx.constants.fetch_or_append(crate::Constant {
- name: None,
- specialization: None,
- inner: crate::ConstantInner::Scalar {
- width: 1,
- value: crate::ScalarValue::Bool(true),
- },
- });
- ctx.expressions.append(crate::Expression::Constant(expr))
- }
- (Token::Word("false"), _) => {
- let expr = ctx.constants.fetch_or_append(crate::Constant {
- name: None,
- specialization: None,
- inner: crate::ConstantInner::Scalar {
- width: 1,
- value: crate::ScalarValue::Bool(false),
- },
- });
- ctx.expressions.append(crate::Expression::Constant(expr))
- }
- (Token::Number { value, ty, width }, _) => {
- let inner = Self::get_constant_inner(value, ty, width)?;
- let expr = ctx.constants.fetch_or_append(crate::Constant {
- name: None,
- specialization: None,
- inner,
- });
- ctx.expressions.append(crate::Expression::Constant(expr))
+ token @ (Token::Word("true"), _)
+ | token @ (Token::Word("false"), _)
+ | token @ (Token::Number { .. }, _) => {
+ let const_handle =
+ self.parse_const_expression_impl(token, lexer, None, ctx.types, ctx.constants)?;
+ // pause the emitter while generating this expression, since it's pre-emitted
+ ctx.block.extend(ctx.emitter.finish(ctx.expressions));
+ let expr = ctx
+ .expressions
+ .append(crate::Expression::Constant(const_handle));
+ ctx.emitter.start(ctx.expressions);
+ expr
}
(Token::Word(word), _) => {
if let Some(&expr) = ctx.lookup_ident.get(word) {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -983,13 +985,27 @@ impl Parser {
lexer: &mut Lexer<'a>,
mut ctx: ExpressionContext<'a, '_, '_>,
mut handle: Handle<crate::Expression>,
+ allow_deref: bool,
) -> Result<Handle<crate::Expression>, Error<'a>> {
+ let mut needs_deref = match ctx.expressions[handle] {
+ crate::Expression::LocalVariable(_) | crate::Expression::GlobalVariable(_) => {
+ allow_deref
+ }
+ _ => false,
+ };
loop {
- match lexer.peek().0 {
+ // insert the E::Load when we reach a value
+ if needs_deref && ctx.resolve_type(handle)?.scalar_kind().is_some() {
+ let expression = crate::Expression::Load { pointer: handle };
+ handle = ctx.expressions.append(expression);
+ needs_deref = false;
+ }
+
+ let expression = match lexer.peek().0 {
Token::Separator('.') => {
let _ = lexer.next();
let name = lexer.next_ident()?;
- let expression = match *ctx.resolve_type(handle)? {
+ match *ctx.resolve_type(handle)? {
crate::TypeInner::Struct { ref members, .. } => {
let index = members
.iter()
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1016,8 +1032,8 @@ impl Parser {
}
}
crate::TypeInner::Matrix {
- rows,
columns,
+ rows,
width,
} => match Composition::make(handle, columns, name, ctx.expressions)? {
Composition::Multi(columns, components) => {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1036,21 +1052,29 @@ impl Parser {
Composition::Single(expr) => expr,
},
_ => return Err(Error::BadAccessor(name)),
- };
- handle = ctx.expressions.append(expression);
+ }
}
Token::Paren('[') => {
let _ = lexer.next();
let index = self.parse_general_expression(lexer, ctx.reborrow())?;
lexer.expect(Token::Paren(']'))?;
- let expr = crate::Expression::Access {
+ crate::Expression::Access {
base: handle,
index,
- };
- handle = ctx.expressions.append(expr);
+ }
}
- _ => return Ok(handle),
- }
+ _ => {
+ // after we reached for the value, load it
+ return Ok(if needs_deref {
+ let expression = crate::Expression::Load { pointer: handle };
+ ctx.expressions.append(expression)
+ } else {
+ handle
+ });
+ }
+ };
+
+ handle = ctx.expressions.append(expression);
}
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1092,7 +1116,7 @@ impl Parser {
}
};
- let post_handle = self.parse_postfix(lexer, ctx, handle)?;
+ let post_handle = self.parse_postfix(lexer, ctx, handle, true)?;
self.scopes.pop();
Ok(post_handle)
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1270,7 +1294,7 @@ impl Parser {
let (ty, access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?;
let init = if lexer.skip(Token::Operation('=')) {
- let handle = self.parse_const_expression(lexer, None, type_arena, const_arena)?;
+ let handle = self.parse_const_expression(lexer, type_arena, const_arena)?;
Some(handle)
} else {
None
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1475,7 +1499,7 @@ impl Parser {
let (base, _access) = self.parse_type_decl(lexer, None, type_arena, const_arena)?;
let size = if lexer.skip(Token::Separator(',')) {
let const_handle =
- self.parse_const_expression(lexer, None, type_arena, const_arena)?;
+ self.parse_const_expression(lexer, type_arena, const_arena)?;
crate::ArraySize::Constant(const_handle)
} else {
crate::ArraySize::Dynamic
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1707,12 +1731,13 @@ impl Parser {
lexer: &mut Lexer<'a>,
ident: &'a str,
mut context: ExpressionContext<'a, '_, 'out>,
- ) -> Result<crate::Statement, Error<'a>> {
- Ok(match context.lookup_ident.get(ident) {
+ ) -> Result<(), Error<'a>> {
+ context.emitter.start(context.expressions);
+ let stmt = match context.lookup_ident.get(ident) {
Some(&expr) => {
- let left = self.parse_postfix(lexer, context.reborrow(), expr)?;
+ let left = self.parse_postfix(lexer, context.reborrow(), expr, false)?;
lexer.expect(Token::Operation('='))?;
- let value = self.parse_general_expression(lexer, context)?;
+ let value = self.parse_general_expression(lexer, context.reborrow())?;
crate::Statement::Store {
pointer: left,
value,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1720,7 +1745,7 @@ impl Parser {
}
None => {
let (function, arguments) = self
- .parse_local_function_call(lexer, ident, context)?
+ .parse_local_function_call(lexer, ident, context.reborrow())?
.ok_or(Error::UnknownLocalFunction(ident))?;
crate::Statement::Call {
function,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1728,7 +1753,12 @@ impl Parser {
result: None,
}
}
- })
+ };
+ context
+ .block
+ .extend(context.emitter.finish(context.expressions));
+ context.block.push(stmt);
+ Ok(())
}
fn parse_statement<'a, 'out>(
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1760,13 +1790,17 @@ impl Parser {
};
self.scopes.push(Scope::Statement);
+ let mut emitter = super::Emitter::default();
match word {
"const" => {
+ emitter.start(context.expressions);
let (name, _ty, _access) =
self.parse_variable_ident_decl(lexer, context.types, context.constants)?;
lexer.expect(Token::Operation('='))?;
- let expr_id = self.parse_general_expression(lexer, context.as_expression(block))?;
+ let expr_id = self
+ .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?;
lexer.expect(Token::Separator(';'))?;
+ block.extend(emitter.finish(context.expressions));
context.lookup_ident.insert(name, expr_id);
}
"var" => {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1780,8 +1814,12 @@ impl Parser {
self.parse_variable_ident_decl(lexer, context.types, context.constants)?;
let init = if lexer.skip(Token::Operation('=')) {
- let value =
- self.parse_general_expression(lexer, context.as_expression(block))?;
+ emitter.start(context.expressions);
+ let value = self.parse_general_expression(
+ lexer,
+ context.as_expression(block, &mut emitter),
+ )?;
+ block.extend(emitter.finish(context.expressions));
match context.expressions[value] {
crate::Expression::Constant(handle) if is_uniform_control_flow => {
Init::Constant(handle)
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1816,7 +1854,13 @@ impl Parser {
}
"return" => {
let value = if lexer.peek().0 != Token::Separator(';') {
- Some(self.parse_general_expression(lexer, context.as_expression(block))?)
+ emitter.start(context.expressions);
+ let handle = self.parse_general_expression(
+ lexer,
+ context.as_expression(block, &mut emitter),
+ )?;
+ block.extend(emitter.finish(context.expressions));
+ Some(handle)
} else {
None
};
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1824,20 +1868,27 @@ impl Parser {
block.push(crate::Statement::Return { value });
}
"if" => {
+ emitter.start(context.expressions);
lexer.expect(Token::Paren('('))?;
- let condition =
- self.parse_general_expression(lexer, context.as_expression(block))?;
+ let condition = self
+ .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?;
lexer.expect(Token::Paren(')'))?;
+ block.extend(emitter.finish(context.expressions));
let accept = self.parse_block(lexer, context.reborrow(), false)?;
let mut elsif_stack = Vec::new();
while lexer.skip(Token::Word("elseif")) {
+ let mut sub_emitter = super::Emitter::default();
+ sub_emitter.start(context.expressions);
lexer.expect(Token::Paren('('))?;
- let other_condition =
- self.parse_general_expression(lexer, context.as_expression(block))?;
+ let other_condition = self.parse_general_expression(
+ lexer,
+ context.as_expression(block, &mut sub_emitter),
+ )?;
lexer.expect(Token::Paren(')'))?;
+ let other_emit = sub_emitter.finish(context.expressions);
let other_block = self.parse_block(lexer, context.reborrow(), false)?;
- elsif_stack.push((other_condition, other_block));
+ elsif_stack.push((other_condition, other_emit, other_block));
}
let mut reject = if lexer.skip(Token::Word("else")) {
self.parse_block(lexer, context.reborrow(), false)?
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1846,12 +1897,15 @@ impl Parser {
};
// reverse-fold the else-if blocks
//Note: we may consider uplifting this to the IR
- for (other_cond, other_block) in elsif_stack.drain(..).rev() {
- reject = vec![crate::Statement::If {
- condition: other_cond,
- accept: other_block,
- reject,
- }];
+ for (other_cond, other_emit, other_block) in elsif_stack.drain(..).rev() {
+ reject = other_emit
+ .into_iter()
+ .chain(iter::once(crate::Statement::If {
+ condition: other_cond,
+ accept: other_block,
+ reject,
+ }))
+ .collect();
}
block.push(crate::Statement::If {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1861,10 +1915,12 @@ impl Parser {
});
}
"switch" => {
+ emitter.start(context.expressions);
lexer.expect(Token::Paren('('))?;
- let selector =
- self.parse_general_expression(lexer, context.as_expression(block))?;
+ let selector = self
+ .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?;
lexer.expect(Token::Paren(')'))?;
+ block.extend(emitter.finish(context.expressions));
lexer.expect(Token::Paren('{'))?;
let mut cases = Vec::new();
let mut default = Vec::new();
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1969,70 +2025,71 @@ impl Parser {
}
};
- let condition = if lexer.skip(Token::Separator(';')) {
- None
- } else {
- let condition =
- Some(self.parse_general_expression(lexer, context.as_expression(block))?);
+ let mut body = Vec::new();
+ if !lexer.skip(Token::Separator(';')) {
+ emitter.start(context.expressions);
+ let condition = self.parse_general_expression(
+ lexer,
+ context.as_expression(&mut body, &mut emitter),
+ )?;
lexer.expect(Token::Separator(';'))?;
- condition
+ body.extend(emitter.finish(context.expressions));
+ body.push(crate::Statement::If {
+ condition,
+ accept: Vec::new(),
+ reject: vec![crate::Statement::Break],
+ });
};
- let continuing = if let Token::Word(ident) = lexer.peek().0 {
+ let mut continuing = Vec::new();
+ if let Token::Word(ident) = lexer.peek().0 {
// manually parse the next statement here instead of calling parse_statement
// because the statement is not terminated with a semicolon
let _ = lexer.next();
- Some(self.parse_statement_restricted(
+ self.parse_statement_restricted(
lexer,
ident,
- context.as_expression(block),
- )?)
- } else {
- None
- };
+ context.as_expression(&mut continuing, &mut emitter),
+ )?;
+ }
lexer.expect(Token::Paren(')'))?;
lexer.expect(Token::Paren('{'))?;
- let mut body = Vec::new();
- if let Some(condition) = condition {
- body.push(crate::Statement::If {
- condition,
- accept: Vec::new(),
- reject: [crate::Statement::Break].to_vec(),
- });
- }
while !lexer.skip(Token::Paren('}')) {
self.parse_statement(lexer, context.reborrow(), &mut body, false)?;
}
- block.push(crate::Statement::Loop {
- body,
- continuing: continuing.into_iter().collect(),
- });
+ block.push(crate::Statement::Loop { body, continuing });
}
"break" => block.push(crate::Statement::Break),
"continue" => block.push(crate::Statement::Continue),
"discard" => block.push(crate::Statement::Kill),
"textureStore" => {
+ emitter.start(context.expressions);
lexer.expect(Token::Paren('('))?;
let image_name = lexer.next_ident()?;
let image = context.lookup_ident.lookup(image_name)?;
lexer.expect(Token::Separator(','))?;
- let coordinate =
- self.parse_general_expression(lexer, context.as_expression(block))?;
- let arrayed = match *context.as_expression(block).resolve_type(image)? {
+ let mut expr_context = context.as_expression(block, &mut emitter);
+ let arrayed = match *expr_context.resolve_type(image)? {
crate::TypeInner::Image { arrayed, .. } => arrayed,
_ => return Err(Error::BadTexture(image_name)),
};
+ let coordinate = self.parse_general_expression(lexer, expr_context)?;
let array_index = if arrayed {
lexer.expect(Token::Separator(','))?;
- Some(self.parse_general_expression(lexer, context.as_expression(block))?)
+ Some(self.parse_general_expression(
+ lexer,
+ context.as_expression(block, &mut emitter),
+ )?)
} else {
None
};
lexer.expect(Token::Separator(','))?;
- let value = self.parse_general_expression(lexer, context.as_expression(block))?;
+ let value = self
+ .parse_general_expression(lexer, context.as_expression(block, &mut emitter))?;
lexer.expect(Token::Paren(')'))?;
+ block.extend(emitter.finish(context.expressions));
block.push(crate::Statement::ImageStore {
image,
coordinate,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2042,10 +2099,12 @@ impl Parser {
}
// assignment or a function call
ident => {
- let stmt =
- self.parse_statement_restricted(lexer, ident, context.as_expression(block))?;
+ self.parse_statement_restricted(
+ lexer,
+ ident,
+ context.as_expression(block, &mut emitter),
+ )?;
lexer.expect(Token::Separator(';'))?;
- block.push(stmt);
}
}
self.scopes.pop();
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2291,7 +2350,9 @@ impl Parser {
&mut module.constants,
)?;
lexer.expect(Token::Operation('='))?;
- let const_handle = self.parse_const_expression(
+ let first_token_span = lexer.next();
+ let const_handle = self.parse_const_expression_impl(
+ first_token_span,
lexer,
Some(name),
&mut module.types,
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,9 +1,25 @@
-//! Universal shader translator.
-//!
-//! The central structure of the crate is [`Module`].
-//!
-//! To improve performance and reduce memory usage, most structures are stored
-//! in an [`Arena`], and can be retrieved using the corresponding [`Handle`].
+/*! Universal shader translator.
+
+The central structure of the crate is [`Module`].
+
+To improve performance and reduce memory usage, most structures are stored
+in an [`Arena`], and can be retrieved using the corresponding [`Handle`].
+
+Functions are described in terms of statement trees. A statement may have
+branching control flow, and it may be mutating. Statements refer to expressions.
+
+Expressions form a DAG, without any side effects. Expressions need to be
+emitted in order to take effect. This happens in one of the following ways:
+ 1. Constants and function arguments are implicitly emitted at function start.
+ This corresponds to `expression.needs_pre_emit()` condition.
+ 2. Local and global variables are implicitly emitted. However, in order to use parts
+ of them in right-hand-side expressions, the `Expression::Load` must be explicitly emitted,
+ with an exception of `StorageClass::Handle` global variables.
+ 3. Result of `Statement::Call` is automatically emitted.
+ 4. `Statement::Emit` range is explicitly emitted.
+
+!*/
+
#![warn(
trivial_casts,
trivial_numeric_casts,
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -24,7 +40,7 @@ pub mod back;
pub mod front;
pub mod proc;
-pub use crate::arena::{Arena, Handle};
+pub use crate::arena::{Arena, Handle, Range};
use std::{
collections::{HashMap, HashSet},
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -752,6 +768,8 @@ pub struct SwitchCase {
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
pub enum Statement {
+ /// Emit a range of expressions, visible to all statements that follow in this block.
+ Emit(Range<Expression>),
/// A block containing more statements, to be executed sequentially.
Block(Block),
/// Conditionally executes one of two blocks, based on the value of the condition.
diff --git a/src/proc/analyzer.rs b/src/proc/analyzer.rs
--- a/src/proc/analyzer.rs
+++ b/src/proc/analyzer.rs
@@ -372,7 +372,7 @@ impl FunctionInfo {
let mut block_flags = ControlFlags::empty();
for statement in statements {
let flags = match *statement {
- S::Break | S::Continue => ControlFlags::empty(),
+ S::Emit(_) | S::Break | S::Continue => ControlFlags::empty(),
S::Kill => ControlFlags::MAY_EXIT,
S::Block(ref b) => self.process_block(b, other_functions, is_uniform)?,
S::If {
diff --git a/src/proc/interface.rs /dev/null
--- a/src/proc/interface.rs
+++ /dev/null
@@ -1,231 +0,0 @@
-use crate::arena::{Arena, Handle};
-use bit_set::BitSet;
-
-pub struct Interface<'a, T> {
- pub visitor: T,
- pub expressions: &'a Arena<crate::Expression>,
- pub local_variables: &'a Arena<crate::LocalVariable>,
- pub mask: &'a mut BitSet,
-}
-
-pub trait Visitor {
- fn visit_expr(&mut self, _: Handle<crate::Expression>, _: &crate::Expression) {}
- fn visit_lhs_expr(&mut self, _: Handle<crate::Expression>, _: &crate::Expression) {}
- fn visit_fun(&mut self, _: Handle<crate::Function>) {}
-}
-
-impl<'a, T: Visitor> Interface<'a, T> {
- pub fn traverse_expr(&mut self, handle: Handle<crate::Expression>) {
- use crate::Expression as E;
-
- if !self.mask.insert(handle.index()) {
- return;
- }
- let expr = &self.expressions[handle];
-
- self.visitor.visit_expr(handle, expr);
-
- match *expr {
- E::Access { base, index } => {
- self.traverse_expr(base);
- self.traverse_expr(index);
- }
- E::AccessIndex { base, .. } => {
- self.traverse_expr(base);
- }
- E::Constant(_) => {}
- E::Compose { ref components, .. } => {
- for &comp in components {
- self.traverse_expr(comp);
- }
- }
- E::FunctionArgument(_) | E::GlobalVariable(_) | E::LocalVariable(_) => {}
- E::Load { pointer } => {
- self.traverse_expr(pointer);
- }
- E::ImageSample {
- image,
- sampler,
- coordinate,
- array_index,
- offset: _,
- level,
- depth_ref,
- } => {
- self.traverse_expr(image);
- self.traverse_expr(sampler);
- self.traverse_expr(coordinate);
- if let Some(layer) = array_index {
- self.traverse_expr(layer);
- }
- match level {
- crate::SampleLevel::Auto | crate::SampleLevel::Zero => (),
- crate::SampleLevel::Exact(h) | crate::SampleLevel::Bias(h) => {
- self.traverse_expr(h);
- }
- crate::SampleLevel::Gradient { x, y } => {
- self.traverse_expr(x);
- self.traverse_expr(y);
- }
- }
- if let Some(dref) = depth_ref {
- self.traverse_expr(dref);
- }
- }
- E::ImageLoad {
- image,
- coordinate,
- array_index,
- index,
- } => {
- self.traverse_expr(image);
- self.traverse_expr(coordinate);
- if let Some(layer) = array_index {
- self.traverse_expr(layer);
- }
- if let Some(index) = index {
- self.traverse_expr(index);
- }
- }
- E::ImageQuery { image, query } => {
- self.traverse_expr(image);
- match query {
- crate::ImageQuery::Size { level: Some(expr) } => self.traverse_expr(expr),
- crate::ImageQuery::Size { .. }
- | crate::ImageQuery::NumLevels
- | crate::ImageQuery::NumLayers
- | crate::ImageQuery::NumSamples => (),
- }
- }
- E::Unary { expr, .. } => {
- self.traverse_expr(expr);
- }
- E::Binary { left, right, .. } => {
- self.traverse_expr(left);
- self.traverse_expr(right);
- }
- E::Select {
- condition,
- accept,
- reject,
- } => {
- self.traverse_expr(condition);
- self.traverse_expr(accept);
- self.traverse_expr(reject);
- }
- E::Derivative { expr, .. } => {
- self.traverse_expr(expr);
- }
- E::Relational { argument, .. } => {
- self.traverse_expr(argument);
- }
- E::Math {
- arg, arg1, arg2, ..
- } => {
- self.traverse_expr(arg);
- if let Some(arg) = arg1 {
- self.traverse_expr(arg);
- }
- if let Some(arg) = arg2 {
- self.traverse_expr(arg);
- }
- }
- E::As { expr, .. } => {
- self.traverse_expr(expr);
- }
- E::Call(function) => {
- self.visitor.visit_fun(function);
- }
- E::ArrayLength(expr) => {
- self.traverse_expr(expr);
- }
- }
- }
-
- pub fn traverse(&mut self, block: &[crate::Statement]) {
- for statement in block {
- use crate::Statement as S;
- match *statement {
- S::Break | S::Continue | S::Kill => (),
- S::Block(ref b) => {
- self.traverse(b);
- }
- S::If {
- condition,
- ref accept,
- ref reject,
- } => {
- self.traverse_expr(condition);
- self.traverse(accept);
- self.traverse(reject);
- }
- S::Switch {
- selector,
- ref cases,
- ref default,
- } => {
- self.traverse_expr(selector);
- for case in cases.iter() {
- self.traverse(&case.body);
- }
- self.traverse(default);
- }
- S::Loop {
- ref body,
- ref continuing,
- } => {
- self.traverse(body);
- self.traverse(continuing);
- }
- S::Return { value } => {
- if let Some(expr) = value {
- self.traverse_expr(expr);
- }
- }
- S::Store { pointer, value } => {
- let mut left = pointer;
- loop {
- match self.expressions[left] {
- crate::Expression::Access { base, index } => {
- self.traverse_expr(index);
- left = base;
- }
- crate::Expression::AccessIndex { base, .. } => {
- left = base;
- }
- _ => break,
- }
- }
- self.visitor.visit_lhs_expr(left, &self.expressions[left]);
- self.traverse_expr(value);
- }
- S::ImageStore {
- image,
- coordinate,
- array_index,
- value,
- } => {
- self.visitor.visit_lhs_expr(image, &self.expressions[image]);
- self.traverse_expr(coordinate);
- if let Some(expr) = array_index {
- self.traverse_expr(expr);
- }
- self.traverse_expr(value);
- }
- S::Call {
- function,
- ref arguments,
- result,
- } => {
- for &argument in arguments {
- self.traverse_expr(argument);
- }
- self.visitor.visit_fun(function);
- if let Some(expr) = result {
- self.traverse_expr(expr);
- }
- }
- }
- }
- }
-}
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -1,14 +1,12 @@
//! Module processing functionality.
pub mod analyzer;
-mod interface;
mod layouter;
mod namer;
mod terminator;
mod typifier;
mod validator;
-pub use interface::{Interface, Visitor};
pub use layouter::{Alignment, Layouter};
pub use namer::{EntryPointIndex, NameKey, Namer};
pub use terminator::ensure_block_returns;
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -138,3 +136,16 @@ impl super::MathFunction {
}
}
}
+
+impl crate::Expression {
+ /// Returns true if the expression is considered emitted at the start of a function.
+ pub fn needs_pre_emit(&self) -> bool {
+ match *self {
+ Self::Constant(_)
+ | Self::FunctionArgument(_)
+ | Self::GlobalVariable(_)
+ | Self::LocalVariable(_) => true,
+ _ => false,
+ }
+ }
+}
diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs
--- a/src/proc/terminator.rs
+++ b/src/proc/terminator.rs
@@ -5,11 +5,12 @@
/// to the end, because it may be either redundant or invalid,
/// e.g. when the user already has returns in if/else branches.
pub fn ensure_block_returns(block: &mut crate::Block) {
+ use crate::Statement as S;
match block.last_mut() {
- Some(&mut crate::Statement::Block(ref mut b)) => {
+ Some(&mut S::Block(ref mut b)) => {
ensure_block_returns(b);
}
- Some(&mut crate::Statement::If {
+ Some(&mut S::If {
condition: _,
ref mut accept,
ref mut reject,
diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs
--- a/src/proc/terminator.rs
+++ b/src/proc/terminator.rs
@@ -17,7 +18,7 @@ pub fn ensure_block_returns(block: &mut crate::Block) {
ensure_block_returns(accept);
ensure_block_returns(reject);
}
- Some(&mut crate::Statement::Switch {
+ Some(&mut S::Switch {
selector: _,
ref mut cases,
ref mut default,
diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs
--- a/src/proc/terminator.rs
+++ b/src/proc/terminator.rs
@@ -29,14 +30,15 @@ pub fn ensure_block_returns(block: &mut crate::Block) {
}
ensure_block_returns(default);
}
- Some(&mut crate::Statement::Break)
- | Some(&mut crate::Statement::Continue)
- | Some(&mut crate::Statement::Return { .. })
- | Some(&mut crate::Statement::Kill) => (),
- Some(&mut crate::Statement::Loop { .. })
- | Some(&mut crate::Statement::Store { .. })
- | Some(&mut crate::Statement::ImageStore { .. })
- | Some(&mut crate::Statement::Call { .. })
- | None => block.push(crate::Statement::Return { value: None }),
+ Some(&mut S::Emit(_))
+ | Some(&mut S::Break)
+ | Some(&mut S::Continue)
+ | Some(&mut S::Return { .. })
+ | Some(&mut S::Kill) => (),
+ Some(&mut S::Loop { .. })
+ | Some(&mut S::Store { .. })
+ | Some(&mut S::ImageStore { .. })
+ | Some(&mut S::Call { .. })
+ | None => block.push(S::Return { value: None }),
}
}
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -96,6 +96,18 @@ impl Typifier {
}
}
+ pub fn try_get<'a>(
+ &'a self,
+ expr_handle: Handle<crate::Expression>,
+ types: &'a Arena<crate::Type>,
+ ) -> Option<&'a crate::TypeInner> {
+ let resolution = self.resolutions.get(expr_handle.index())?;
+ Some(match *resolution {
+ Resolution::Handle(ty_handle) => &types[ty_handle].inner,
+ Resolution::Value(ref inner) => inner,
+ })
+ }
+
pub fn get_handle(
&self,
expr_handle: Handle<crate::Expression>,
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -106,6 +118,7 @@ impl Typifier {
}
}
+ //TODO: resolve `*Variable` and `Access*` expressions to `Pointer` type.
fn resolve_impl(
&self,
expr: &crate::Expression,
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -189,7 +202,8 @@ impl Typifier {
}
crate::Expression::GlobalVariable(h) => Resolution::Handle(ctx.global_vars[h].ty),
crate::Expression::LocalVariable(h) => Resolution::Handle(ctx.local_vars[h].ty),
- crate::Expression::Load { .. } => unimplemented!(),
+ // we treat Load as a transparent operation for the type system
+ crate::Expression::Load { pointer } => self.resolutions[pointer.index()].clone(),
crate::Expression::ImageSample { image, .. }
| crate::Expression::ImageLoad { image, .. } => match *self.get(image, types) {
crate::TypeInner::Image { class, .. } => Resolution::Value(match class {
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -74,6 +74,8 @@ pub struct Validator {
location_out_mask: BitSet,
bind_group_masks: Vec<BitSet>,
select_cases: FastHashSet<i32>,
+ valid_expression_list: Vec<Handle<crate::Expression>>,
+ valid_expression_set: BitSet,
}
#[derive(Clone, Debug, Error)]
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -134,10 +136,28 @@ pub enum LocalVariableError {
InitializerType,
}
+#[derive(Clone, Debug, Error)]
+pub enum ExpressionError {
+ #[error("Is invalid")]
+ Invalid,
+ #[error("Used by a statement before it was introduced into the scope by any of the dominating blocks")]
+ NotInScope,
+}
+
#[derive(Clone, Debug, Error)]
pub enum CallError {
#[error("Bad function")]
Function,
+ #[error("Argument {index} expression is invalid")]
+ Argument {
+ index: usize,
+ #[source]
+ error: ExpressionError,
+ },
+ #[error("Result expression {0:?} has already been introduced earlier")]
+ ResultAlreadyInScope(Handle<crate::Expression>),
+ #[error("Result value is invalid")]
+ ResultValue(#[source] ExpressionError),
#[error("Requires {required} arguments, but {seen} are provided")]
ArgumentCount { required: usize, seen: usize },
#[error("Argument {index} value {seen_expression:?} doesn't match the type {required:?}")]
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -146,8 +166,8 @@ pub enum CallError {
required: Handle<crate::Type>,
seen_expression: Handle<crate::Expression>,
},
- #[error("Return value {seen_expression:?} does not match the type {required:?}")]
- ReturnType {
+ #[error("Result value {seen_expression:?} does not match the type {required:?}")]
+ ResultType {
required: Option<Handle<crate::Type>>,
seen_expression: Option<Handle<crate::Expression>>,
},
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -157,6 +177,14 @@ pub enum CallError {
pub enum FunctionError {
#[error(transparent)]
Resolve(#[from] TypifyError),
+ #[error("Expression {handle:?} is invalid")]
+ Expression {
+ handle: Handle<crate::Expression>,
+ #[source]
+ error: ExpressionError,
+ },
+ #[error("Expression {0:?} can't be introduced - it's already in scope")]
+ ExpressionAlreadyInScope(Handle<crate::Expression>),
#[error("Local variable {handle:?} '{name}' is invalid")]
LocalVariable {
handle: Handle<crate::LocalVariable>,
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -180,10 +208,12 @@ pub enum FunctionError {
InvalidSwitchType(Handle<crate::Expression>),
#[error("Multiple `switch` cases for {0} are present")]
ConflictingSwitchCase(i32),
+ #[error("The pointer {0:?} doesn't relate to a valid destination for a store")]
+ InvalidStorePointer(Handle<crate::Expression>),
#[error("The value {0:?} can not be stored")]
InvalidStoreValue(Handle<crate::Expression>),
#[error("Store of {value:?} into {pointer:?} doesn't have matching types")]
- InvalidStore {
+ InvalidStoreTypes {
pointer: Handle<crate::Expression>,
value: Handle<crate::Expression>,
},
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -418,6 +448,8 @@ impl Validator {
location_out_mask: BitSet::new(),
bind_group_masks: Vec::new(),
select_cases: FastHashSet::default(),
+ valid_expression_list: Vec::new(),
+ valid_expression_set: BitSet::new(),
}
}
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -679,7 +711,7 @@ impl Validator {
}
fn validate_call(
- &self,
+ &mut self,
function: Handle<crate::Function>,
arguments: &[Handle<crate::Expression>],
result: Option<Handle<crate::Expression>>,
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -696,7 +728,9 @@ impl Validator {
});
}
for (index, (arg, &expr)) in fun.arguments.iter().zip(arguments).enumerate() {
- let ty = self.typifier.get(expr, context.types);
+ let ty = self
+ .resolve_type_impl(expr, context.types)
+ .map_err(|error| CallError::Argument { index, error })?;
if ty != &context.types[arg.ty].inner {
return Err(CallError::ArgumentType {
index,
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -705,7 +739,19 @@ impl Validator {
});
}
}
- let result_ty = result.map(|expr| self.typifier.get(expr, context.types));
+
+ if let Some(expr) = result {
+ if self.valid_expression_set.insert(expr.index()) {
+ self.valid_expression_list.push(expr);
+ } else {
+ return Err(CallError::ResultAlreadyInScope(expr));
+ }
+ }
+
+ let result_ty = result
+ .map(|expr| self.resolve_type_impl(expr, context.types))
+ .transpose()
+ .map_err(CallError::ResultValue)?;
let expected_ty = fun.return_type.map(|ty| &context.types[ty].inner);
if result_ty != expected_ty {
log::error!(
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -713,7 +759,7 @@ impl Validator {
result_ty,
expected_ty
);
- return Err(CallError::ReturnType {
+ return Err(CallError::ResultType {
required: fun.return_type,
seen_expression: result,
});
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -721,26 +767,56 @@ impl Validator {
Ok(())
}
- fn validate_block(
+ fn resolve_type_impl<'a>(
+ &'a self,
+ handle: Handle<crate::Expression>,
+ types: &'a Arena<crate::Type>,
+ ) -> Result<&'a crate::TypeInner, ExpressionError> {
+ if !self.valid_expression_set.contains(handle.index()) {
+ return Err(ExpressionError::NotInScope);
+ }
+ self.typifier
+ .try_get(handle, types)
+ .ok_or(ExpressionError::Invalid)
+ }
+
+ fn resolve_type<'a>(
+ &'a self,
+ handle: Handle<crate::Expression>,
+ types: &'a Arena<crate::Type>,
+ ) -> Result<&'a crate::TypeInner, FunctionError> {
+ self.resolve_type_impl(handle, types)
+ .map_err(|error| FunctionError::Expression { handle, error })
+ }
+
+ fn validate_block_impl(
&mut self,
statements: &[crate::Statement],
context: &BlockContext,
) -> Result<(), FunctionError> {
use crate::{Statement as S, TypeInner as Ti};
- //TODO: handle the cases of totally invalid expression handles
let mut finished = false;
for statement in statements {
if finished {
return Err(FunctionError::InstructionsAfterReturn);
}
match *statement {
+ S::Emit(ref range) => {
+ for handle in range.clone() {
+ if self.valid_expression_set.insert(handle.index()) {
+ self.valid_expression_list.push(handle);
+ } else {
+ return Err(FunctionError::ExpressionAlreadyInScope(handle));
+ }
+ }
+ }
S::Block(ref block) => self.validate_block(block, context)?,
S::If {
condition,
ref accept,
ref reject,
} => {
- match *self.typifier.get(condition, context.types) {
+ match *self.resolve_type(condition, context.types)? {
Ti::Scalar {
kind: crate::ScalarKind::Bool,
width: _,
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -755,7 +831,7 @@ impl Validator {
ref cases,
ref default,
} => {
- match *self.typifier.get(selector, context.types) {
+ match *self.resolve_type(selector, context.types)? {
Ti::Scalar {
kind: crate::ScalarKind::Sint,
width: _,
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -777,11 +853,17 @@ impl Validator {
ref body,
ref continuing,
} => {
- self.validate_block(
+ // special handling for block scoping is needed here,
+ // because the continuing{} block inherits the scope
+ let base_expression_count = self.valid_expression_list.len();
+ self.validate_block_impl(
body,
&context.with_flags(BlockFlags::CAN_JUMP | BlockFlags::IN_LOOP),
)?;
- self.validate_block(continuing, &context.with_flags(BlockFlags::empty()))?;
+ self.validate_block_impl(continuing, &context.with_flags(BlockFlags::empty()))?;
+ for handle in self.valid_expression_list.drain(base_expression_count..) {
+ self.valid_expression_set.remove(handle.index());
+ }
}
S::Break | S::Continue => {
if !context.flags.contains(BlockFlags::IN_LOOP) {
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -793,7 +875,9 @@ impl Validator {
if !context.flags.contains(BlockFlags::CAN_JUMP) {
return Err(FunctionError::InvalidReturnSpot);
}
- let value_ty = value.map(|expr| self.typifier.get(expr, context.types));
+ let value_ty = value
+ .map(|expr| self.resolve_type(expr, context.types))
+ .transpose()?;
let expected_ty = context.return_type.map(|ty| &context.types[ty].inner);
if value_ty != expected_ty {
log::error!(
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -809,17 +893,33 @@ impl Validator {
finished = true;
}
S::Store { pointer, value } => {
- let value_ty = self.typifier.get(value, context.types);
+ let mut current = pointer;
+ loop {
+ self.typifier.try_get(current, context.types).ok_or(
+ FunctionError::Expression {
+ handle: current,
+ error: ExpressionError::Invalid,
+ },
+ )?;
+ match context.expressions[current] {
+ crate::Expression::Access { base, .. }
+ | crate::Expression::AccessIndex { base, .. } => current = base,
+ crate::Expression::LocalVariable(_)
+ | crate::Expression::GlobalVariable(_) => break,
+ _ => return Err(FunctionError::InvalidStorePointer(current)),
+ }
+ }
+
+ let value_ty = self.resolve_type(value, context.types)?;
match *value_ty {
Ti::Image { .. } | Ti::Sampler { .. } => {
return Err(FunctionError::InvalidStoreValue(value));
}
_ => {}
}
- if self.typifier.get(pointer, context.types) != value_ty {
- return Err(FunctionError::InvalidStore { pointer, value });
+ if self.typifier.try_get(pointer, context.types) != Some(value_ty) {
+ return Err(FunctionError::InvalidStoreTypes { pointer, value });
}
- //TODO: validate that the `pointer` reaches a variable through a sequence of accessors
}
S::ImageStore {
image,
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -862,6 +962,19 @@ impl Validator {
Ok(())
}
+ fn validate_block(
+ &mut self,
+ statements: &[crate::Statement],
+ context: &BlockContext,
+ ) -> Result<(), FunctionError> {
+ let base_expression_count = self.valid_expression_list.len();
+ self.validate_block_impl(statements, context)?;
+ for handle in self.valid_expression_list.drain(base_expression_count..) {
+ self.valid_expression_set.remove(handle.index());
+ }
+ Ok(())
+ }
+
fn validate_function(
&mut self,
fun: &crate::Function,
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -896,6 +1009,13 @@ impl Validator {
}
}
+ self.valid_expression_set.clear();
+ for (handle, expr) in fun.expressions.iter() {
+ if expr.needs_pre_emit() {
+ self.valid_expression_set.insert(handle.index());
+ }
+ }
+
self.validate_block(
&fun.body,
&BlockContext {
|
diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap
--- a/tests/out/boids.spvasm.snap
+++ b/tests/out/boids.spvasm.snap
@@ -5,64 +5,64 @@ expression: dis
; SPIR-V
; Version: 1.0
; Generator: rspirv
-; Bound: 286
+; Bound: 233
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
-OpEntryPoint GLCompute %29 "main" %36
-OpExecutionMode %29 LocalSize 64 1 1
+OpEntryPoint GLCompute %41 "main" %25
+OpExecutionMode %41 LocalSize 64 1 1
OpSource GLSL 450
OpName %3 "NUM_PARTICLES"
-OpName %15 "vPos"
-OpName %18 "vVel"
-OpName %19 "cMass"
-OpName %20 "cVel"
-OpName %21 "colVel"
-OpName %22 "cMassCount"
-OpName %24 "cVelCount"
-OpName %25 "pos"
-OpName %26 "vel"
-OpName %27 "i"
-OpName %29 "main"
-OpName %36 "gl_GlobalInvocationID"
-OpName %44 "Particle"
-OpMemberName %44 0 "pos"
-OpMemberName %44 1 "vel"
-OpName %48 "Particles"
-OpMemberName %48 0 "particles"
-OpName %49 "particlesSrc"
-OpName %118 "SimParams"
-OpMemberName %118 0 "deltaT"
-OpMemberName %118 1 "rule1Distance"
-OpMemberName %118 2 "rule2Distance"
-OpMemberName %118 3 "rule3Distance"
-OpMemberName %118 4 "rule1Scale"
-OpMemberName %118 5 "rule2Scale"
-OpMemberName %118 6 "rule3Scale"
-OpName %119 "params"
-OpName %262 "particlesDst"
-OpName %29 "main"
-OpDecorate %36 BuiltIn GlobalInvocationId
-OpMemberDecorate %44 0 Offset 0
-OpMemberDecorate %44 1 Offset 8
-OpDecorate %46 ArrayStride 16
-OpDecorate %48 BufferBlock
-OpMemberDecorate %48 0 Offset 0
-OpDecorate %49 NonWritable
-OpDecorate %49 DescriptorSet 0
-OpDecorate %49 Binding 1
-OpDecorate %118 Block
-OpMemberDecorate %118 0 Offset 0
-OpMemberDecorate %118 1 Offset 4
-OpMemberDecorate %118 2 Offset 8
-OpMemberDecorate %118 3 Offset 12
-OpMemberDecorate %118 4 Offset 16
-OpMemberDecorate %118 5 Offset 20
-OpMemberDecorate %118 6 Offset 24
-OpDecorate %119 DescriptorSet 0
-OpDecorate %119 Binding 0
-OpDecorate %262 DescriptorSet 0
-OpDecorate %262 Binding 2
+OpName %16 "SimParams"
+OpMemberName %16 0 "deltaT"
+OpMemberName %16 1 "rule1Distance"
+OpMemberName %16 2 "rule2Distance"
+OpMemberName %16 3 "rule3Distance"
+OpMemberName %16 4 "rule1Scale"
+OpMemberName %16 5 "rule2Scale"
+OpMemberName %16 6 "rule3Scale"
+OpName %15 "params"
+OpName %19 "Particles"
+OpMemberName %19 0 "particles"
+OpName %21 "Particle"
+OpMemberName %21 0 "pos"
+OpMemberName %21 1 "vel"
+OpName %18 "particlesSrc"
+OpName %24 "particlesDst"
+OpName %25 "gl_GlobalInvocationID"
+OpName %28 "vPos"
+OpName %30 "vVel"
+OpName %31 "cMass"
+OpName %32 "cVel"
+OpName %33 "colVel"
+OpName %34 "cMassCount"
+OpName %36 "cVelCount"
+OpName %37 "pos"
+OpName %38 "vel"
+OpName %39 "i"
+OpName %41 "main"
+OpName %41 "main"
+OpDecorate %16 Block
+OpMemberDecorate %16 0 Offset 0
+OpMemberDecorate %16 1 Offset 4
+OpMemberDecorate %16 2 Offset 8
+OpMemberDecorate %16 3 Offset 12
+OpMemberDecorate %16 4 Offset 16
+OpMemberDecorate %16 5 Offset 20
+OpMemberDecorate %16 6 Offset 24
+OpDecorate %15 DescriptorSet 0
+OpDecorate %15 Binding 0
+OpDecorate %19 BufferBlock
+OpMemberDecorate %19 0 Offset 0
+OpDecorate %20 ArrayStride 16
+OpMemberDecorate %21 0 Offset 0
+OpMemberDecorate %21 1 Offset 8
+OpDecorate %18 NonWritable
+OpDecorate %18 DescriptorSet 0
+OpDecorate %18 Binding 1
+OpDecorate %24 DescriptorSet 0
+OpDecorate %24 Binding 2
+OpDecorate %25 BuiltIn GlobalInvocationId
%2 = OpTypeVoid
%4 = OpTypeInt 32 1
%3 = OpConstant %4 1500
diff --git a/tests/out/boids.spvasm.snap b/tests/out/boids.spvasm.snap
--- a/tests/out/boids.spvasm.snap
+++ b/tests/out/boids.spvasm.snap
@@ -76,341 +76,289 @@ OpDecorate %262 Binding 2
%12 = OpConstant %6 1.0
%13 = OpConstant %6 0.1
%14 = OpConstant %6 -1.0
-%16 = OpTypeVector %6 2
-%17 = OpTypePointer Function %16
-%23 = OpTypePointer Function %4
-%28 = OpTypePointer Function %9
-%30 = OpTypeFunction %2
-%32 = OpTypeBool
-%35 = OpTypeVector %9 3
-%37 = OpTypePointer Input %35
-%36 = OpVariable %37 Input
-%38 = OpTypePointer Input %9
-%39 = OpConstant %4 0
-%44 = OpTypeStruct %16 %16
-%46 = OpTypeRuntimeArray %44
-%48 = OpTypeStruct %46
-%50 = OpTypePointer Uniform %48
-%49 = OpVariable %50 Uniform
-%51 = OpTypePointer Uniform %46
+%16 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6
+%17 = OpTypePointer Uniform %16
+%15 = OpVariable %17 Uniform
+%22 = OpTypeVector %6 2
+%21 = OpTypeStruct %22 %22
+%20 = OpTypeRuntimeArray %21
+%19 = OpTypeStruct %20
+%23 = OpTypePointer Uniform %19
+%18 = OpVariable %23 Uniform
+%24 = OpVariable %23 Uniform
+%26 = OpTypeVector %9 3
+%27 = OpTypePointer Input %26
+%25 = OpVariable %27 Input
+%29 = OpTypePointer Function %22
+%35 = OpTypePointer Function %4
+%40 = OpTypePointer Function %9
+%42 = OpTypeFunction %2
+%47 = OpTypeBool
+%51 = OpConstant %4 0
%52 = OpConstant %4 0
-%54 = OpTypePointer Input %9
-%55 = OpConstant %4 0
-%57 = OpTypePointer Uniform %44
-%58 = OpTypePointer Uniform %16
-%59 = OpConstant %4 0
-%64 = OpTypePointer Uniform %46
-%65 = OpConstant %4 0
-%67 = OpTypePointer Input %9
-%68 = OpConstant %4 0
-%70 = OpTypePointer Uniform %44
-%71 = OpTypePointer Uniform %16
-%72 = OpConstant %4 1
-%88 = OpTypePointer Input %9
-%89 = OpConstant %4 0
-%96 = OpTypePointer Uniform %46
-%97 = OpConstant %4 0
-%99 = OpTypePointer Uniform %44
-%100 = OpTypePointer Uniform %16
-%101 = OpConstant %4 0
-%106 = OpTypePointer Uniform %46
-%107 = OpConstant %4 0
-%109 = OpTypePointer Uniform %44
-%110 = OpTypePointer Uniform %16
-%111 = OpConstant %4 1
-%118 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6
-%120 = OpTypePointer Uniform %118
-%119 = OpVariable %120 Uniform
-%121 = OpTypePointer Uniform %6
-%122 = OpConstant %4 1
-%136 = OpTypePointer Uniform %6
-%137 = OpConstant %4 2
-%151 = OpTypePointer Uniform %6
-%152 = OpConstant %4 3
-%190 = OpTypePointer Uniform %6
-%191 = OpConstant %4 4
-%196 = OpTypePointer Uniform %6
-%197 = OpConstant %4 5
-%202 = OpTypePointer Uniform %6
-%203 = OpConstant %4 6
-%216 = OpTypePointer Uniform %6
-%217 = OpConstant %4 0
-%221 = OpTypePointer Function %6
-%222 = OpConstant %4 0
-%227 = OpTypePointer Function %6
-%228 = OpConstant %4 0
-%231 = OpTypePointer Function %6
-%232 = OpConstant %4 0
-%237 = OpTypePointer Function %6
-%238 = OpConstant %4 0
-%241 = OpTypePointer Function %6
-%242 = OpConstant %4 1
-%247 = OpTypePointer Function %6
-%248 = OpConstant %4 1
-%251 = OpTypePointer Function %6
-%252 = OpConstant %4 1
-%257 = OpTypePointer Function %6
-%258 = OpConstant %4 1
-%262 = OpVariable %50 Uniform
-%263 = OpTypePointer Uniform %46
-%264 = OpConstant %4 0
-%266 = OpTypePointer Input %9
-%267 = OpConstant %4 0
-%269 = OpTypePointer Uniform %44
-%270 = OpTypePointer Uniform %16
-%271 = OpConstant %4 0
-%276 = OpTypePointer Uniform %46
-%277 = OpConstant %4 0
-%279 = OpTypePointer Input %9
-%280 = OpConstant %4 0
-%282 = OpTypePointer Uniform %44
-%283 = OpTypePointer Uniform %16
-%284 = OpConstant %4 1
-%29 = OpFunction %2 None %30
-%31 = OpLabel
-%27 = OpVariable %28 Function %8
-%24 = OpVariable %23 Function %7
-%20 = OpVariable %17 Function
-%15 = OpVariable %17 Function
-%25 = OpVariable %17 Function
-%21 = OpVariable %17 Function
-%18 = OpVariable %17 Function
-%26 = OpVariable %17 Function
-%22 = OpVariable %23 Function %7
-%19 = OpVariable %17 Function
-%34 = OpAccessChain %38 %36 %39
-%40 = OpLoad %9 %34
-%33 = OpUGreaterThanEqual %32 %40 %3
-OpSelectionMerge %41 None
-OpBranchConditional %33 %42 %41
-%42 = OpLabel
+%54 = OpTypePointer Uniform %22
+%56 = OpConstant %4 1
+%57 = OpConstant %4 0
+%59 = OpTypePointer Uniform %22
+%77 = OpConstant %4 0
+%78 = OpConstant %4 0
+%80 = OpTypePointer Uniform %22
+%83 = OpConstant %4 1
+%84 = OpConstant %4 0
+%86 = OpTypePointer Uniform %22
+%91 = OpConstant %4 1
+%93 = OpTypePointer Uniform %6
+%106 = OpConstant %4 2
+%108 = OpTypePointer Uniform %6
+%121 = OpConstant %4 3
+%123 = OpTypePointer Uniform %6
+%157 = OpConstant %4 4
+%159 = OpTypePointer Uniform %6
+%164 = OpConstant %4 5
+%166 = OpTypePointer Uniform %6
+%171 = OpConstant %4 6
+%173 = OpTypePointer Uniform %6
+%185 = OpConstant %4 0
+%187 = OpTypePointer Uniform %6
+%196 = OpConstant %4 0
+%198 = OpTypePointer Function %6
+%204 = OpConstant %4 0
+%206 = OpTypePointer Function %6
+%212 = OpConstant %4 1
+%214 = OpTypePointer Function %6
+%220 = OpConstant %4 1
+%222 = OpTypePointer Function %6
+%224 = OpConstant %4 0
+%225 = OpConstant %4 0
+%227 = OpTypePointer Uniform %22
+%229 = OpConstant %4 1
+%230 = OpConstant %4 0
+%232 = OpTypePointer Uniform %22
+%41 = OpFunction %2 None %42
+%43 = OpLabel
+%39 = OpVariable %40 Function %8
+%36 = OpVariable %35 Function %7
+%32 = OpVariable %29 Function
+%28 = OpVariable %29 Function
+%37 = OpVariable %29 Function
+%33 = OpVariable %29 Function
+%30 = OpVariable %29 Function
+%38 = OpVariable %29 Function
+%34 = OpVariable %35 Function %7
+%31 = OpVariable %29 Function
+OpBranch %44
+%44 = OpLabel
+%45 = OpLoad %26 %25
+%46 = OpCompositeExtract %9 %45 0
+%48 = OpUGreaterThanEqual %47 %46 %3
+OpSelectionMerge %49 None
+OpBranchConditional %48 %50 %49
+%50 = OpLabel
OpReturn
-%41 = OpLabel
-%47 = OpAccessChain %51 %49 %52
-%53 = OpAccessChain %54 %36 %55
-%56 = OpLoad %9 %53
-%45 = OpAccessChain %57 %47 %56
-%43 = OpAccessChain %58 %45 %59
-%60 = OpLoad %16 %43
-OpStore %15 %60
-%63 = OpAccessChain %64 %49 %65
-%66 = OpAccessChain %67 %36 %68
-%69 = OpLoad %9 %66
-%62 = OpAccessChain %70 %63 %69
-%61 = OpAccessChain %71 %62 %72
-%73 = OpLoad %16 %61
-OpStore %18 %73
-%74 = OpCompositeConstruct %16 %5 %5
-OpStore %19 %74
-%75 = OpCompositeConstruct %16 %5 %5
-OpStore %20 %75
-%76 = OpCompositeConstruct %16 %5 %5
-OpStore %21 %76
-OpBranch %77
-%77 = OpLabel
-OpLoopMerge %78 %80 None
-OpBranch %79
-%79 = OpLabel
-%82 = OpLoad %9 %27
-%81 = OpUGreaterThanEqual %32 %82 %3
-OpSelectionMerge %83 None
-OpBranchConditional %81 %84 %83
-%84 = OpLabel
-OpBranch %78
-%83 = OpLabel
-%86 = OpLoad %9 %27
-%87 = OpAccessChain %88 %36 %89
-%90 = OpLoad %9 %87
-%85 = OpIEqual %32 %86 %90
-OpSelectionMerge %91 None
-OpBranchConditional %85 %92 %91
-%92 = OpLabel
-OpBranch %80
-%91 = OpLabel
-%95 = OpAccessChain %96 %49 %97
-%98 = OpLoad %9 %27
-%94 = OpAccessChain %99 %95 %98
-%93 = OpAccessChain %100 %94 %101
-%102 = OpLoad %16 %93
-OpStore %25 %102
-%105 = OpAccessChain %106 %49 %107
-%108 = OpLoad %9 %27
-%104 = OpAccessChain %109 %105 %108
-%103 = OpAccessChain %110 %104 %111
-%112 = OpLoad %16 %103
-OpStore %26 %112
-%114 = OpLoad %16 %25
-%115 = OpLoad %16 %15
-%116 = OpExtInst %6 %1 Distance %114 %115
-%117 = OpAccessChain %121 %119 %122
-%123 = OpLoad %6 %117
-%113 = OpFOrdLessThan %32 %116 %123
-OpSelectionMerge %124 None
-OpBranchConditional %113 %125 %124
-%125 = OpLabel
-%127 = OpLoad %16 %19
-%128 = OpLoad %16 %25
-%126 = OpFAdd %16 %127 %128
-OpStore %19 %126
-%130 = OpLoad %4 %22
-%129 = OpIAdd %4 %130 %10
-OpStore %22 %129
-OpBranch %124
-%124 = OpLabel
-%132 = OpLoad %16 %25
-%133 = OpLoad %16 %15
-%134 = OpExtInst %6 %1 Distance %132 %133
-%135 = OpAccessChain %136 %119 %137
-%138 = OpLoad %6 %135
-%131 = OpFOrdLessThan %32 %134 %138
-OpSelectionMerge %139 None
-OpBranchConditional %131 %140 %139
-%140 = OpLabel
-%142 = OpLoad %16 %21
-%144 = OpLoad %16 %25
-%145 = OpLoad %16 %15
-%143 = OpFSub %16 %144 %145
-%141 = OpFSub %16 %142 %143
-OpStore %21 %141
-OpBranch %139
-%139 = OpLabel
-%147 = OpLoad %16 %25
-%148 = OpLoad %16 %15
-%149 = OpExtInst %6 %1 Distance %147 %148
-%150 = OpAccessChain %151 %119 %152
-%153 = OpLoad %6 %150
-%146 = OpFOrdLessThan %32 %149 %153
-OpSelectionMerge %154 None
-OpBranchConditional %146 %155 %154
-%155 = OpLabel
-%157 = OpLoad %16 %20
-%158 = OpLoad %16 %26
-%156 = OpFAdd %16 %157 %158
-OpStore %20 %156
-%160 = OpLoad %4 %24
-%159 = OpIAdd %4 %160 %10
-OpStore %24 %159
-OpBranch %154
-%154 = OpLabel
-OpBranch %80
-%80 = OpLabel
-%162 = OpLoad %9 %27
-%161 = OpIAdd %9 %162 %11
-OpStore %27 %161
-OpBranch %77
-%78 = OpLabel
-%164 = OpLoad %4 %22
-%163 = OpSGreaterThan %32 %164 %7
-OpSelectionMerge %165 None
-OpBranchConditional %163 %166 %165
-%166 = OpLabel
-%169 = OpLoad %16 %19
-%171 = OpLoad %4 %22
-%172 = OpConvertSToF %6 %171
-%170 = OpFDiv %6 %12 %172
-%168 = OpVectorTimesScalar %16 %169 %170
-%173 = OpLoad %16 %15
-%167 = OpFSub %16 %168 %173
-OpStore %19 %167
-OpBranch %165
-%165 = OpLabel
-%175 = OpLoad %4 %24
-%174 = OpSGreaterThan %32 %175 %7
-OpSelectionMerge %176 None
-OpBranchConditional %174 %177 %176
-%177 = OpLabel
-%179 = OpLoad %16 %20
-%181 = OpLoad %4 %24
-%182 = OpConvertSToF %6 %181
-%180 = OpFDiv %6 %12 %182
-%178 = OpVectorTimesScalar %16 %179 %180
-OpStore %20 %178
-OpBranch %176
-%176 = OpLabel
-%186 = OpLoad %16 %18
-%188 = OpLoad %16 %19
-%189 = OpAccessChain %190 %119 %191
-%192 = OpLoad %6 %189
-%187 = OpVectorTimesScalar %16 %188 %192
-%185 = OpFAdd %16 %186 %187
-%194 = OpLoad %16 %21
-%195 = OpAccessChain %196 %119 %197
-%198 = OpLoad %6 %195
-%193 = OpVectorTimesScalar %16 %194 %198
-%184 = OpFAdd %16 %185 %193
-%200 = OpLoad %16 %20
-%201 = OpAccessChain %202 %119 %203
-%204 = OpLoad %6 %201
-%199 = OpVectorTimesScalar %16 %200 %204
-%183 = OpFAdd %16 %184 %199
-OpStore %18 %183
-%206 = OpLoad %16 %18
-%207 = OpExtInst %16 %1 Normalize %206
-%208 = OpLoad %16 %18
-%209 = OpExtInst %6 %1 Length %208
-%210 = OpExtInst %6 %1 FClamp %209 %5 %13
-%205 = OpVectorTimesScalar %16 %207 %210
-OpStore %18 %205
-%212 = OpLoad %16 %15
-%214 = OpLoad %16 %18
-%215 = OpAccessChain %216 %119 %217
-%218 = OpLoad %6 %215
-%213 = OpVectorTimesScalar %16 %214 %218
-%211 = OpFAdd %16 %212 %213
-OpStore %15 %211
-%220 = OpAccessChain %221 %15 %222
-%223 = OpLoad %6 %220
-%219 = OpFOrdLessThan %32 %223 %14
-OpSelectionMerge %224 None
-OpBranchConditional %219 %225 %224
-%225 = OpLabel
-%226 = OpAccessChain %227 %15 %228
-OpStore %226 %12
-OpBranch %224
-%224 = OpLabel
-%230 = OpAccessChain %231 %15 %232
-%233 = OpLoad %6 %230
-%229 = OpFOrdGreaterThan %32 %233 %12
-OpSelectionMerge %234 None
-OpBranchConditional %229 %235 %234
-%235 = OpLabel
-%236 = OpAccessChain %237 %15 %238
-OpStore %236 %14
-OpBranch %234
-%234 = OpLabel
-%240 = OpAccessChain %241 %15 %242
-%243 = OpLoad %6 %240
-%239 = OpFOrdLessThan %32 %243 %14
-OpSelectionMerge %244 None
-OpBranchConditional %239 %245 %244
-%245 = OpLabel
-%246 = OpAccessChain %247 %15 %248
-OpStore %246 %12
-OpBranch %244
-%244 = OpLabel
-%250 = OpAccessChain %251 %15 %252
-%253 = OpLoad %6 %250
-%249 = OpFOrdGreaterThan %32 %253 %12
-OpSelectionMerge %254 None
-OpBranchConditional %249 %255 %254
-%255 = OpLabel
-%256 = OpAccessChain %257 %15 %258
-OpStore %256 %14
-OpBranch %254
-%254 = OpLabel
-%261 = OpAccessChain %263 %262 %264
-%265 = OpAccessChain %266 %36 %267
-%268 = OpLoad %9 %265
-%260 = OpAccessChain %269 %261 %268
-%259 = OpAccessChain %270 %260 %271
-%272 = OpLoad %16 %15
-OpStore %259 %272
-%275 = OpAccessChain %276 %262 %277
-%278 = OpAccessChain %279 %36 %280
-%281 = OpLoad %9 %278
-%274 = OpAccessChain %282 %275 %281
-%273 = OpAccessChain %283 %274 %284
-%285 = OpLoad %16 %18
-OpStore %273 %285
+%49 = OpLabel
+%53 = OpAccessChain %54 %18 %52 %46 %51
+%55 = OpLoad %22 %53
+OpStore %28 %55
+%58 = OpAccessChain %59 %18 %57 %46 %56
+%60 = OpLoad %22 %58
+OpStore %30 %60
+%61 = OpCompositeConstruct %22 %5 %5
+OpStore %31 %61
+%62 = OpCompositeConstruct %22 %5 %5
+OpStore %32 %62
+%63 = OpCompositeConstruct %22 %5 %5
+OpStore %33 %63
+OpBranch %64
+%64 = OpLabel
+OpLoopMerge %65 %67 None
+OpBranch %66
+%66 = OpLabel
+%68 = OpLoad %9 %39
+%69 = OpUGreaterThanEqual %47 %68 %3
+OpSelectionMerge %70 None
+OpBranchConditional %69 %71 %70
+%71 = OpLabel
+OpBranch %65
+%70 = OpLabel
+%72 = OpLoad %9 %39
+%73 = OpIEqual %47 %72 %46
+OpSelectionMerge %74 None
+OpBranchConditional %73 %75 %74
+%75 = OpLabel
+OpBranch %67
+%74 = OpLabel
+%76 = OpLoad %9 %39
+%79 = OpAccessChain %80 %18 %78 %76 %77
+%81 = OpLoad %22 %79
+OpStore %37 %81
+%82 = OpLoad %9 %39
+%85 = OpAccessChain %86 %18 %84 %82 %83
+%87 = OpLoad %22 %85
+OpStore %38 %87
+%88 = OpLoad %22 %37
+%89 = OpLoad %22 %28
+%90 = OpExtInst %6 %1 Distance %88 %89
+%92 = OpAccessChain %93 %15 %91
+%94 = OpLoad %6 %92
+%95 = OpFOrdLessThan %47 %90 %94
+OpSelectionMerge %96 None
+OpBranchConditional %95 %97 %96
+%97 = OpLabel
+%98 = OpLoad %22 %31
+%99 = OpLoad %22 %37
+%100 = OpFAdd %22 %98 %99
+OpStore %31 %100
+%101 = OpLoad %4 %34
+%102 = OpIAdd %4 %101 %10
+OpStore %34 %102
+OpBranch %96
+%96 = OpLabel
+%103 = OpLoad %22 %37
+%104 = OpLoad %22 %28
+%105 = OpExtInst %6 %1 Distance %103 %104
+%107 = OpAccessChain %108 %15 %106
+%109 = OpLoad %6 %107
+%110 = OpFOrdLessThan %47 %105 %109
+OpSelectionMerge %111 None
+OpBranchConditional %110 %112 %111
+%112 = OpLabel
+%113 = OpLoad %22 %33
+%114 = OpLoad %22 %37
+%115 = OpLoad %22 %28
+%116 = OpFSub %22 %114 %115
+%117 = OpFSub %22 %113 %116
+OpStore %33 %117
+OpBranch %111
+%111 = OpLabel
+%118 = OpLoad %22 %37
+%119 = OpLoad %22 %28
+%120 = OpExtInst %6 %1 Distance %118 %119
+%122 = OpAccessChain %123 %15 %121
+%124 = OpLoad %6 %122
+%125 = OpFOrdLessThan %47 %120 %124
+OpSelectionMerge %126 None
+OpBranchConditional %125 %127 %126
+%127 = OpLabel
+%128 = OpLoad %22 %32
+%129 = OpLoad %22 %38
+%130 = OpFAdd %22 %128 %129
+OpStore %32 %130
+%131 = OpLoad %4 %36
+%132 = OpIAdd %4 %131 %10
+OpStore %36 %132
+OpBranch %126
+%126 = OpLabel
+OpBranch %67
+%67 = OpLabel
+%133 = OpLoad %9 %39
+%134 = OpIAdd %9 %133 %11
+OpStore %39 %134
+OpBranch %64
+%65 = OpLabel
+%135 = OpLoad %4 %34
+%136 = OpSGreaterThan %47 %135 %7
+OpSelectionMerge %137 None
+OpBranchConditional %136 %138 %137
+%138 = OpLabel
+%139 = OpLoad %22 %31
+%140 = OpLoad %4 %34
+%141 = OpConvertSToF %6 %140
+%142 = OpFDiv %6 %12 %141
+%143 = OpVectorTimesScalar %22 %139 %142
+%144 = OpLoad %22 %28
+%145 = OpFSub %22 %143 %144
+OpStore %31 %145
+OpBranch %137
+%137 = OpLabel
+%146 = OpLoad %4 %36
+%147 = OpSGreaterThan %47 %146 %7
+OpSelectionMerge %148 None
+OpBranchConditional %147 %149 %148
+%149 = OpLabel
+%150 = OpLoad %22 %32
+%151 = OpLoad %4 %36
+%152 = OpConvertSToF %6 %151
+%153 = OpFDiv %6 %12 %152
+%154 = OpVectorTimesScalar %22 %150 %153
+OpStore %32 %154
+OpBranch %148
+%148 = OpLabel
+%155 = OpLoad %22 %30
+%156 = OpLoad %22 %31
+%158 = OpAccessChain %159 %15 %157
+%160 = OpLoad %6 %158
+%161 = OpVectorTimesScalar %22 %156 %160
+%162 = OpFAdd %22 %155 %161
+%163 = OpLoad %22 %33
+%165 = OpAccessChain %166 %15 %164
+%167 = OpLoad %6 %165
+%168 = OpVectorTimesScalar %22 %163 %167
+%169 = OpFAdd %22 %162 %168
+%170 = OpLoad %22 %32
+%172 = OpAccessChain %173 %15 %171
+%174 = OpLoad %6 %172
+%175 = OpVectorTimesScalar %22 %170 %174
+%176 = OpFAdd %22 %169 %175
+OpStore %30 %176
+%177 = OpLoad %22 %30
+%178 = OpExtInst %22 %1 Normalize %177
+%179 = OpLoad %22 %30
+%180 = OpExtInst %6 %1 Length %179
+%181 = OpExtInst %6 %1 FClamp %180 %5 %13
+%182 = OpVectorTimesScalar %22 %178 %181
+OpStore %30 %182
+%183 = OpLoad %22 %28
+%184 = OpLoad %22 %30
+%186 = OpAccessChain %187 %15 %185
+%188 = OpLoad %6 %186
+%189 = OpVectorTimesScalar %22 %184 %188
+%190 = OpFAdd %22 %183 %189
+OpStore %28 %190
+%191 = OpLoad %22 %28
+%192 = OpCompositeExtract %6 %191 0
+%193 = OpFOrdLessThan %47 %192 %14
+OpSelectionMerge %194 None
+OpBranchConditional %193 %195 %194
+%195 = OpLabel
+%197 = OpAccessChain %198 %28 %196
+OpStore %197 %12
+OpBranch %194
+%194 = OpLabel
+%199 = OpLoad %22 %28
+%200 = OpCompositeExtract %6 %199 0
+%201 = OpFOrdGreaterThan %47 %200 %12
+OpSelectionMerge %202 None
+OpBranchConditional %201 %203 %202
+%203 = OpLabel
+%205 = OpAccessChain %206 %28 %204
+OpStore %205 %14
+OpBranch %202
+%202 = OpLabel
+%207 = OpLoad %22 %28
+%208 = OpCompositeExtract %6 %207 1
+%209 = OpFOrdLessThan %47 %208 %14
+OpSelectionMerge %210 None
+OpBranchConditional %209 %211 %210
+%211 = OpLabel
+%213 = OpAccessChain %214 %28 %212
+OpStore %213 %12
+OpBranch %210
+%210 = OpLabel
+%215 = OpLoad %22 %28
+%216 = OpCompositeExtract %6 %215 1
+%217 = OpFOrdGreaterThan %47 %216 %12
+OpSelectionMerge %218 None
+OpBranchConditional %217 %219 %218
+%219 = OpLabel
+%221 = OpAccessChain %222 %28 %220
+OpStore %221 %14
+OpBranch %218
+%218 = OpLabel
+%223 = OpLoad %22 %28
+%226 = OpAccessChain %227 %24 %225 %46 %224
+OpStore %226 %223
+%228 = OpLoad %22 %30
+%231 = OpAccessChain %232 %24 %230 %46 %229
+OpStore %231 %228
OpReturn
OpFunctionEnd
diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap
--- a/tests/out/collatz.info.ron.snap
+++ b/tests/out/collatz.info.ron.snap
@@ -60,6 +60,13 @@ expression: output
ref_count: 3,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 0,
diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap
--- a/tests/out/collatz.info.ron.snap
+++ b/tests/out/collatz.info.ron.snap
@@ -74,6 +81,13 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 0,
diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap
--- a/tests/out/collatz.info.ron.snap
+++ b/tests/out/collatz.info.ron.snap
@@ -102,6 +116,13 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 0,
diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap
--- a/tests/out/collatz.info.ron.snap
+++ b/tests/out/collatz.info.ron.snap
@@ -130,6 +151,13 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 0,
diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap
--- a/tests/out/collatz.info.ron.snap
+++ b/tests/out/collatz.info.ron.snap
@@ -144,6 +172,13 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 0,
diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap
--- a/tests/out/collatz.info.ron.snap
+++ b/tests/out/collatz.info.ron.snap
@@ -158,6 +193,13 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
],
),
],
diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap
--- a/tests/out/collatz.info.ron.snap
+++ b/tests/out/collatz.info.ron.snap
@@ -202,7 +244,14 @@ expression: output
bits: 1,
),
ref_count: 1,
- assignable_global: Some(1),
+ assignable_global: None,
+ ),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
),
(
control_flags: (
diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap
--- a/tests/out/collatz.info.ron.snap
+++ b/tests/out/collatz.info.ron.snap
@@ -223,7 +272,14 @@ expression: output
bits: 1,
),
ref_count: 1,
- assignable_global: Some(1),
+ assignable_global: None,
+ ),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
),
(
control_flags: (
diff --git a/tests/out/collatz.info.ron.snap b/tests/out/collatz.info.ron.snap
--- a/tests/out/collatz.info.ron.snap
+++ b/tests/out/collatz.info.ron.snap
@@ -232,6 +288,13 @@ expression: output
ref_count: 1,
assignable_global: Some(2),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 5,
diff --git a/tests/out/collatz.msl.snap b/tests/out/collatz.msl.snap
--- a/tests/out/collatz.msl.snap
+++ b/tests/out/collatz.msl.snap
@@ -43,8 +43,8 @@ kernel void main1(
type global_id [[thread_position_in_grid]],
device PrimeIndices& v_indices [[buffer(0)]]
) {
- type1 _expr8 = collatz_iterations(v_indices.data[global_id.x]);
- v_indices.data[global_id.x] = _expr8;
+ type1 _expr11 = collatz_iterations(v_indices.data[global_id.x]);
+ v_indices.data[global_id.x] = _expr11;
return ;
}
diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap
--- a/tests/out/collatz.ron.snap
+++ b/tests/out/collatz.ron.snap
@@ -131,47 +131,65 @@ expression: output
LocalVariable(1),
Constant(1),
LocalVariable(2),
+ Load(
+ pointer: 4,
+ ),
Constant(2),
Binary(
op: LessEqual,
- left: 4,
- right: 7,
+ left: 7,
+ right: 8,
+ ),
+ Load(
+ pointer: 4,
),
Constant(3),
Binary(
op: Modulo,
- left: 4,
- right: 9,
+ left: 10,
+ right: 11,
),
Constant(1),
Binary(
op: Equal,
- left: 10,
- right: 11,
+ left: 12,
+ right: 13,
+ ),
+ Load(
+ pointer: 4,
),
Constant(3),
Binary(
op: Divide,
- left: 4,
- right: 13,
+ left: 15,
+ right: 16,
),
Constant(4),
+ Load(
+ pointer: 4,
+ ),
Binary(
op: Multiply,
- left: 15,
- right: 4,
+ left: 18,
+ right: 19,
),
Constant(2),
Binary(
op: Add,
- left: 16,
- right: 17,
+ left: 20,
+ right: 21,
+ ),
+ Load(
+ pointer: 6,
),
Constant(2),
Binary(
op: Add,
- left: 6,
- right: 19,
+ left: 23,
+ right: 24,
+ ),
+ Load(
+ pointer: 6,
),
],
body: [
diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap
--- a/tests/out/collatz.ron.snap
+++ b/tests/out/collatz.ron.snap
@@ -181,37 +199,85 @@ expression: output
),
Loop(
body: [
+ Emit((
+ start: 6,
+ end: 7,
+ )),
+ Emit((
+ start: 8,
+ end: 9,
+ )),
If(
- condition: 8,
+ condition: 9,
accept: [
Break,
],
reject: [],
),
+ Emit((
+ start: 9,
+ end: 10,
+ )),
+ Emit((
+ start: 11,
+ end: 12,
+ )),
+ Emit((
+ start: 13,
+ end: 14,
+ )),
If(
- condition: 12,
+ condition: 14,
accept: [
+ Emit((
+ start: 14,
+ end: 15,
+ )),
+ Emit((
+ start: 16,
+ end: 17,
+ )),
Store(
pointer: 4,
- value: 14,
+ value: 17,
),
],
reject: [
+ Emit((
+ start: 18,
+ end: 20,
+ )),
+ Emit((
+ start: 21,
+ end: 22,
+ )),
Store(
pointer: 4,
- value: 18,
+ value: 22,
),
],
),
+ Emit((
+ start: 22,
+ end: 23,
+ )),
+ Emit((
+ start: 24,
+ end: 25,
+ )),
Store(
pointer: 6,
- value: 20,
+ value: 25,
),
],
continuing: [],
),
+ Emit((
+ start: 25,
+ end: 26,
+ )),
Return(
- value: Some(6),
+ value: Some(26),
),
],
),
diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap
--- a/tests/out/collatz.ron.snap
+++ b/tests/out/collatz.ron.snap
@@ -232,39 +298,52 @@ expression: output
base: 2,
index: 0,
),
+ Load(
+ pointer: 1,
+ ),
AccessIndex(
- base: 1,
+ base: 4,
index: 0,
),
Access(
base: 3,
- index: 4,
+ index: 5,
),
AccessIndex(
base: 2,
index: 0,
),
+ Load(
+ pointer: 1,
+ ),
AccessIndex(
- base: 1,
+ base: 8,
index: 0,
),
Access(
- base: 6,
- index: 7,
+ base: 7,
+ index: 9,
+ ),
+ Load(
+ pointer: 10,
),
Call(1),
],
body: [
+ Emit((
+ start: 2,
+ end: 11,
+ )),
Call(
function: 1,
arguments: [
- 8,
+ 11,
],
- result: Some(9),
+ result: Some(12),
),
Store(
- pointer: 5,
- value: 9,
+ pointer: 6,
+ value: 12,
),
Return(
value: None,
diff --git a/tests/out/collatz.spvasm.snap b/tests/out/collatz.spvasm.snap
--- a/tests/out/collatz.spvasm.snap
+++ b/tests/out/collatz.spvasm.snap
@@ -5,113 +5,109 @@ expression: dis
; SPIR-V
; Version: 1.0
; Generator: rspirv
-; Bound: 69
+; Bound: 63
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
-OpEntryPoint GLCompute %38 "main" %53
-OpExecutionMode %38 LocalSize 1 1 1
+OpEntryPoint GLCompute %46 "main" %8
+OpExecutionMode %46 LocalSize 1 1 1
OpSource GLSL 450
-OpName %8 "n"
-OpName %10 "i"
-OpName %12 "collatz_iterations"
-OpName %38 "main"
-OpName %45 "PrimeIndices"
-OpMemberName %45 0 "data"
-OpName %46 "v_indices"
-OpName %53 "global_id"
-OpName %38 "main"
-OpDecorate %43 ArrayStride 4
-OpDecorate %45 BufferBlock
-OpMemberDecorate %45 0 Offset 0
-OpDecorate %46 DescriptorSet 0
-OpDecorate %46 Binding 0
-OpDecorate %53 BuiltIn GlobalInvocationId
+OpName %8 "global_id"
+OpName %12 "PrimeIndices"
+OpMemberName %12 0 "data"
+OpName %11 "v_indices"
+OpName %15 "n"
+OpName %17 "i"
+OpName %19 "collatz_iterations"
+OpName %46 "main"
+OpName %46 "main"
+OpDecorate %8 BuiltIn GlobalInvocationId
+OpDecorate %12 BufferBlock
+OpMemberDecorate %12 0 Offset 0
+OpDecorate %13 ArrayStride 4
+OpDecorate %11 DescriptorSet 0
+OpDecorate %11 Binding 0
%2 = OpTypeVoid
%4 = OpTypeInt 32 0
%3 = OpConstant %4 0
%5 = OpConstant %4 1
%6 = OpConstant %4 2
%7 = OpConstant %4 3
-%9 = OpTypePointer Function %4
-%13 = OpTypeFunction %4 %4
-%19 = OpTypeBool
-%39 = OpTypeFunction %2
-%43 = OpTypeRuntimeArray %4
-%45 = OpTypeStruct %43
-%47 = OpTypePointer Uniform %45
-%46 = OpVariable %47 Uniform
-%48 = OpTypePointer Uniform %43
-%49 = OpTypeInt 32 1
-%50 = OpConstant %49 0
-%52 = OpTypeVector %4 3
-%54 = OpTypePointer Input %52
-%53 = OpVariable %54 Input
-%55 = OpTypePointer Input %4
-%56 = OpConstant %49 0
-%58 = OpTypePointer Uniform %4
-%62 = OpTypePointer Uniform %43
-%63 = OpConstant %49 0
-%65 = OpTypePointer Input %4
-%66 = OpConstant %49 0
-%68 = OpTypePointer Uniform %4
-%12 = OpFunction %4 None %13
-%11 = OpFunctionParameter %4
-%14 = OpLabel
-%8 = OpVariable %9 Function
-%10 = OpVariable %9 Function %3
-OpStore %8 %11
-OpBranch %15
-%15 = OpLabel
-OpLoopMerge %16 %18 None
-OpBranch %17
-%17 = OpLabel
-%21 = OpLoad %4 %8
-%20 = OpULessThanEqual %19 %21 %5
-OpSelectionMerge %22 None
-OpBranchConditional %20 %23 %22
-%23 = OpLabel
-OpBranch %16
+%9 = OpTypeVector %4 3
+%10 = OpTypePointer Input %9
+%8 = OpVariable %10 Input
+%13 = OpTypeRuntimeArray %4
+%12 = OpTypeStruct %13
+%14 = OpTypePointer Uniform %12
+%11 = OpVariable %14 Uniform
+%16 = OpTypePointer Function %4
+%20 = OpTypeFunction %4 %4
+%28 = OpTypeBool
+%47 = OpTypeFunction %2
+%54 = OpTypeInt 32 1
+%55 = OpConstant %54 0
+%57 = OpTypePointer Uniform %4
+%60 = OpConstant %54 0
+%62 = OpTypePointer Uniform %4
+%19 = OpFunction %4 None %20
+%18 = OpFunctionParameter %4
+%21 = OpLabel
+%15 = OpVariable %16 Function
+%17 = OpVariable %16 Function %3
+OpBranch %22
%22 = OpLabel
-%26 = OpLoad %4 %8
-%25 = OpUMod %4 %26 %6
-%24 = OpIEqual %19 %25 %3
-OpSelectionMerge %27 None
-OpBranchConditional %24 %28 %29
-%28 = OpLabel
-%31 = OpLoad %4 %8
-%30 = OpUDiv %4 %31 %6
-OpStore %8 %30
-OpBranch %27
-%29 = OpLabel
-%34 = OpLoad %4 %8
-%33 = OpIMul %4 %7 %34
-%32 = OpIAdd %4 %33 %5
-OpStore %8 %32
-OpBranch %27
-%27 = OpLabel
-%36 = OpLoad %4 %10
-%35 = OpIAdd %4 %36 %5
-OpStore %10 %35
-OpBranch %18
-%18 = OpLabel
-OpBranch %15
-%16 = OpLabel
-%37 = OpLoad %4 %10
-OpReturnValue %37
+OpStore %15 %18
+OpBranch %23
+%23 = OpLabel
+OpLoopMerge %24 %26 None
+OpBranch %25
+%25 = OpLabel
+%27 = OpLoad %4 %15
+%29 = OpULessThanEqual %28 %27 %5
+OpSelectionMerge %30 None
+OpBranchConditional %29 %31 %30
+%31 = OpLabel
+OpBranch %24
+%30 = OpLabel
+%32 = OpLoad %4 %15
+%33 = OpUMod %4 %32 %6
+%34 = OpIEqual %28 %33 %3
+OpSelectionMerge %35 None
+OpBranchConditional %34 %36 %37
+%36 = OpLabel
+%38 = OpLoad %4 %15
+%39 = OpUDiv %4 %38 %6
+OpStore %15 %39
+OpBranch %35
+%37 = OpLabel
+%40 = OpLoad %4 %15
+%41 = OpIMul %4 %7 %40
+%42 = OpIAdd %4 %41 %5
+OpStore %15 %42
+OpBranch %35
+%35 = OpLabel
+%43 = OpLoad %4 %17
+%44 = OpIAdd %4 %43 %5
+OpStore %17 %44
+OpBranch %26
+%26 = OpLabel
+OpBranch %23
+%24 = OpLabel
+%45 = OpLoad %4 %17
+OpReturnValue %45
OpFunctionEnd
-%38 = OpFunction %2 None %39
-%40 = OpLabel
-%44 = OpAccessChain %48 %46 %50
-%51 = OpAccessChain %55 %53 %56
-%57 = OpLoad %4 %51
-%42 = OpAccessChain %58 %44 %57
-%59 = OpLoad %4 %42
-%41 = OpFunctionCall %4 %12 %59
-%61 = OpAccessChain %62 %46 %63
-%64 = OpAccessChain %65 %53 %66
-%67 = OpLoad %4 %64
-%60 = OpAccessChain %68 %61 %67
-OpStore %60 %41
+%46 = OpFunction %2 None %47
+%48 = OpLabel
+OpBranch %49
+%49 = OpLabel
+%50 = OpLoad %9 %8
+%51 = OpCompositeExtract %4 %50 0
+%52 = OpLoad %9 %8
+%53 = OpCompositeExtract %4 %52 0
+%56 = OpAccessChain %57 %11 %55 %53
+%58 = OpLoad %4 %56
+%59 = OpFunctionCall %4 %19 %58
+%61 = OpAccessChain %62 %11 %60 %51
+OpStore %61 %59
OpReturn
OpFunctionEnd
diff --git a/tests/out/empty.spvasm.snap b/tests/out/empty.spvasm.snap
--- a/tests/out/empty.spvasm.snap
+++ b/tests/out/empty.spvasm.snap
@@ -5,7 +5,7 @@ expression: dis
; SPIR-V
; Version: 1.1
; Generator: rspirv
-; Bound: 6
+; Bound: 7
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
diff --git a/tests/out/empty.spvasm.snap b/tests/out/empty.spvasm.snap
--- a/tests/out/empty.spvasm.snap
+++ b/tests/out/empty.spvasm.snap
@@ -18,5 +18,7 @@ OpName %3 "main"
%4 = OpTypeFunction %2
%3 = OpFunction %2 None %4
%5 = OpLabel
+OpBranch %6
+%6 = OpLabel
OpReturn
OpFunctionEnd
diff --git a/tests/out/quad-Fragment.glsl.snap b/tests/out/quad-Fragment.glsl.snap
--- a/tests/out/quad-Fragment.glsl.snap
+++ b/tests/out/quad-Fragment.glsl.snap
@@ -13,6 +13,7 @@ uniform sampler2D _group_0_binding_0;
out vec4 _location_0;
void main() {
+ ;
_location_0 = texture(_group_0_binding_0, vec2(_location_0_vs));
return;
}
diff --git a/tests/out/quad-Vertex.glsl.snap b/tests/out/quad-Vertex.glsl.snap
--- a/tests/out/quad-Vertex.glsl.snap
+++ b/tests/out/quad-Vertex.glsl.snap
@@ -13,7 +13,10 @@ in vec2 _location_1;
out vec2 _location_0_vs;
void main() {
+ ;
_location_0_vs = _location_1;
+ ;
+ ;
gl_Position = vec4((1.2 * _location_0), 0.0, 1.0);
return;
}
diff --git a/tests/out/quad.msl.snap b/tests/out/quad.msl.snap
--- a/tests/out/quad.msl.snap
+++ b/tests/out/quad.msl.snap
@@ -51,7 +51,8 @@ fragment main2Output main2(
type4 u_sampler [[sampler(0)]]
) {
main2Output output;
- output.o_color = u_texture.sample(u_sampler, input.v_uv1);
+ metal::float4 _expr9 = u_texture.sample(u_sampler, input.v_uv1);
+ output.o_color = _expr9;
return output;
}
diff --git a/tests/out/quad.spvasm.snap b/tests/out/quad.spvasm.snap
--- a/tests/out/quad.spvasm.snap
+++ b/tests/out/quad.spvasm.snap
@@ -5,78 +5,82 @@ expression: dis
; SPIR-V
; Version: 1.0
; Generator: rspirv
-; Bound: 39
+; Bound: 41
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
-OpEntryPoint Vertex %7 "main" %20 %13 %11 %17
-OpEntryPoint Fragment %23 "main" %35 %25
-OpExecutionMode %23 OriginUpperLeft
+OpEntryPoint Vertex %24 "main" %7 %10 %11 %13
+OpEntryPoint Fragment %32 "main" %16 %23
+OpExecutionMode %32 OriginUpperLeft
OpSource GLSL 450
OpName %3 "c_scale"
-OpName %7 "main"
+OpName %7 "a_pos"
+OpName %10 "a_uv"
OpName %11 "v_uv"
-OpName %13 "a_uv"
-OpName %17 "o_position"
-OpName %20 "a_pos"
-OpName %7 "main"
-OpName %23 "main"
-OpName %25 "o_color"
-OpName %27 "u_texture"
-OpName %32 "u_sampler"
-OpName %35 "v_uv"
-OpName %23 "main"
+OpName %13 "o_position"
+OpName %16 "v_uv"
+OpName %17 "u_texture"
+OpName %20 "u_sampler"
+OpName %23 "o_color"
+OpName %24 "main"
+OpName %24 "main"
+OpName %32 "main"
+OpName %32 "main"
+OpDecorate %7 Location 0
+OpDecorate %10 Location 1
OpDecorate %11 Location 0
-OpDecorate %13 Location 1
-OpDecorate %17 BuiltIn Position
-OpDecorate %20 Location 0
-OpDecorate %25 Location 0
-OpDecorate %27 DescriptorSet 0
-OpDecorate %27 Binding 0
-OpDecorate %32 DescriptorSet 0
-OpDecorate %32 Binding 1
-OpDecorate %35 Location 0
+OpDecorate %13 BuiltIn Position
+OpDecorate %16 Location 0
+OpDecorate %17 DescriptorSet 0
+OpDecorate %17 Binding 0
+OpDecorate %20 DescriptorSet 0
+OpDecorate %20 Binding 1
+OpDecorate %23 Location 0
%2 = OpTypeVoid
%4 = OpTypeFloat 32
%3 = OpConstant %4 1.2
%5 = OpConstant %4 0.0
%6 = OpConstant %4 1.0
-%8 = OpTypeFunction %2
-%10 = OpTypeVector %4 2
-%12 = OpTypePointer Output %10
+%8 = OpTypeVector %4 2
+%9 = OpTypePointer Input %8
+%7 = OpVariable %9 Input
+%10 = OpVariable %9 Input
+%12 = OpTypePointer Output %8
%11 = OpVariable %12 Output
-%14 = OpTypePointer Input %10
-%13 = OpVariable %14 Input
-%16 = OpTypeVector %4 4
-%18 = OpTypePointer Output %16
-%17 = OpVariable %18 Output
-%20 = OpVariable %14 Input
-%25 = OpVariable %18 Output
-%26 = OpTypeImage %4 2D 0 0 0 1 Unknown
-%28 = OpTypePointer UniformConstant %26
-%27 = OpVariable %28 UniformConstant
-%30 = OpTypeSampledImage %26
-%31 = OpTypeSampler
-%33 = OpTypePointer UniformConstant %31
-%32 = OpVariable %33 UniformConstant
-%35 = OpVariable %14 Input
-%7 = OpFunction %2 None %8
-%9 = OpLabel
-%15 = OpLoad %10 %13
-OpStore %11 %15
-%21 = OpLoad %10 %20
-%19 = OpVectorTimesScalar %10 %21 %3
-%22 = OpCompositeConstruct %16 %19 %5 %6
-OpStore %17 %22
+%14 = OpTypeVector %4 4
+%15 = OpTypePointer Output %14
+%13 = OpVariable %15 Output
+%16 = OpVariable %9 Input
+%18 = OpTypeImage %4 2D 0 0 0 1 Unknown
+%19 = OpTypePointer UniformConstant %18
+%17 = OpVariable %19 UniformConstant
+%21 = OpTypeSampler
+%22 = OpTypePointer UniformConstant %21
+%20 = OpVariable %22 UniformConstant
+%23 = OpVariable %15 Output
+%25 = OpTypeFunction %2
+%38 = OpTypeSampledImage %18
+%24 = OpFunction %2 None %25
+%26 = OpLabel
+OpBranch %27
+%27 = OpLabel
+%28 = OpLoad %8 %10
+OpStore %11 %28
+%29 = OpLoad %8 %7
+%30 = OpVectorTimesScalar %8 %29 %3
+%31 = OpCompositeConstruct %14 %30 %5 %6
+OpStore %13 %31
OpReturn
OpFunctionEnd
-%23 = OpFunction %2 None %8
-%24 = OpLabel
-%29 = OpLoad %26 %27
-%34 = OpLoad %31 %32
-%36 = OpLoad %10 %35
-%37 = OpSampledImage %30 %29 %34
-%38 = OpImageSampleImplicitLod %16 %37 %36
-OpStore %25 %38
+%32 = OpFunction %2 None %25
+%33 = OpLabel
+%34 = OpLoad %18 %17
+%35 = OpLoad %21 %20
+OpBranch %36
+%36 = OpLabel
+%37 = OpLoad %8 %16
+%39 = OpSampledImage %38 %34 %35
+%40 = OpImageSampleImplicitLod %14 %39 %37
+OpStore %23 %40
OpReturn
OpFunctionEnd
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1,7 +1,6 @@
---
source: tests/snapshots.rs
expression: output
-
---
(
functions: [
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -882,6 +881,13 @@ expression: output
ref_count: 11,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 0,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -903,6 +909,27 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 0,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 1,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -917,6 +944,13 @@ expression: output
ref_count: 1,
assignable_global: Some(4),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 1,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -938,6 +972,20 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 5,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -952,6 +1000,13 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 0,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -959,6 +1014,13 @@ expression: output
ref_count: 1,
assignable_global: Some(4),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 1,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -980,6 +1042,13 @@ expression: output
ref_count: 1,
assignable_global: Some(4),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 0,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -987,6 +1056,13 @@ expression: output
ref_count: 1,
assignable_global: Some(4),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 1,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1008,6 +1084,13 @@ expression: output
ref_count: 1,
assignable_global: Some(4),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 0,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1015,6 +1098,13 @@ expression: output
ref_count: 1,
assignable_global: Some(4),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 1,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1043,6 +1133,13 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 1,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1050,6 +1147,13 @@ expression: output
ref_count: 1,
assignable_global: Some(5),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 1,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1057,6 +1161,13 @@ expression: output
ref_count: 1,
assignable_global: Some(5),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 1,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1099,6 +1210,13 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 5,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1113,6 +1231,13 @@ expression: output
ref_count: 1,
assignable_global: Some(4),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 1,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1134,6 +1259,13 @@ expression: output
ref_count: 1,
assignable_global: Some(4),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 0,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1141,6 +1273,13 @@ expression: output
ref_count: 1,
assignable_global: Some(4),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 1,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1162,6 +1301,13 @@ expression: output
ref_count: 1,
assignable_global: Some(4),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 0,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1169,6 +1315,13 @@ expression: output
ref_count: 1,
assignable_global: Some(4),
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 1,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1197,6 +1350,13 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
(
control_flags: (
bits: 5,
diff --git a/tests/out/shadow.info.ron.snap b/tests/out/shadow.info.ron.snap
--- a/tests/out/shadow.info.ron.snap
+++ b/tests/out/shadow.info.ron.snap
@@ -1225,6 +1385,20 @@ expression: output
ref_count: 1,
assignable_global: None,
),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
+ (
+ control_flags: (
+ bits: 1,
+ ),
+ ref_count: 1,
+ assignable_global: None,
+ ),
],
),
},
diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap
--- a/tests/out/shadow.msl.snap
+++ b/tests/out/shadow.msl.snap
@@ -60,7 +60,8 @@ type7 fetch_shadow(
return const_1f;
}
float _expr15 = (const_1f / homogeneous_coords.w);
- return t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(const_0_50f, const_n0_50f)) * _expr15) + metal::float2(const_0_50f, const_0_50f)), static_cast<int>(light_id), (homogeneous_coords.z * _expr15));
+ float _expr28 = t_shadow.sample_compare(sampler_shadow, (((metal::float2(homogeneous_coords.x, homogeneous_coords.y) * metal::float2(const_0_50f, const_n0_50f)) * _expr15) + metal::float2(const_0_50f, const_0_50f)), static_cast<int>(light_id), (homogeneous_coords.z * _expr15));
+ return _expr28;
}
struct fs_mainInput {
diff --git a/tests/out/shadow.msl.snap b/tests/out/shadow.msl.snap
--- a/tests/out/shadow.msl.snap
+++ b/tests/out/shadow.msl.snap
@@ -91,9 +92,10 @@ fragment fs_mainOutput fs_main(
if ((i >= metal::min(u_globals.num_lights.x, c_max_lights))) {
break;
}
- Light _expr18 = s_lights.data[i];
- type7 _expr21 = fetch_shadow(i, (_expr18.proj * input.in_position_fs), t_shadow, sampler_shadow);
- color1 = (color1 + ((_expr21 * metal::max(const_0f, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(_expr18.pos.x, _expr18.pos.y, _expr18.pos.z) - metal::float3(input.in_position_fs.x, input.in_position_fs.y, input.in_position_fs.z)))))) * metal::float3(_expr18.color.x, _expr18.color.y, _expr18.color.z)));
+ Light _expr23 = s_lights.data[i];
+ type7 _expr28 = fetch_shadow(i, (_expr23.proj * input.in_position_fs), t_shadow, sampler_shadow);
+ type2 _expr34 = input.in_position_fs;
+ color1 = (color1 + ((_expr28 * metal::max(const_0f, metal::dot(metal::normalize(input.in_normal_fs), metal::normalize((metal::float3(_expr23.pos.x, _expr23.pos.y, _expr23.pos.z) - metal::float3(_expr34.x, _expr34.y, _expr34.z)))))) * metal::float3(_expr23.color.x, _expr23.color.y, _expr23.color.z)));
}
output.out_color_fs = metal::float4(color1, const_1f);
return output;
diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap
--- a/tests/out/shadow.ron.snap
+++ b/tests/out/shadow.ron.snap
@@ -779,6 +779,10 @@ expression: output
),
],
body: [
+ Emit((
+ start: 44,
+ end: 46,
+ )),
If(
condition: 46,
accept: [
diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap
--- a/tests/out/shadow.ron.snap
+++ b/tests/out/shadow.ron.snap
@@ -788,6 +792,10 @@ expression: output
],
reject: [],
),
+ Emit((
+ start: 46,
+ end: 71,
+ )),
Return(
value: Some(71),
),
diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap
--- a/tests/out/shadow.ron.snap
+++ b/tests/out/shadow.ron.snap
@@ -859,46 +867,70 @@ expression: output
Constant(5),
LocalVariable(1),
LocalVariable(2),
+ Load(
+ pointer: 44,
+ ),
AccessIndex(
base: 1,
index: 0,
),
Access(
- base: 45,
+ base: 46,
index: 37,
),
+ Load(
+ pointer: 47,
+ ),
Math(
fun: Min,
- arg: 46,
+ arg: 48,
arg1: Some(28),
arg2: None,
),
Binary(
op: GreaterEqual,
- left: 44,
- right: 47,
+ left: 45,
+ right: 49,
+ ),
+ Load(
+ pointer: 43,
+ ),
+ Load(
+ pointer: 44,
),
AccessIndex(
base: 6,
index: 0,
),
+ Load(
+ pointer: 44,
+ ),
Access(
- base: 49,
- index: 44,
+ base: 53,
+ index: 54,
),
AccessIndex(
- base: 50,
+ base: 55,
index: 0,
),
+ Load(
+ pointer: 56,
+ ),
+ Load(
+ pointer: 3,
+ ),
Binary(
op: Multiply,
- left: 51,
- right: 3,
+ left: 57,
+ right: 58,
),
Call(1),
+ Load(
+ pointer: 2,
+ ),
Math(
fun: Normalize,
- arg: 2,
+ arg: 61,
arg1: None,
arg2: None,
),
diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap
--- a/tests/out/shadow.ron.snap
+++ b/tests/out/shadow.ron.snap
@@ -906,181 +938,232 @@ expression: output
base: 6,
index: 0,
),
+ Load(
+ pointer: 44,
+ ),
Access(
- base: 55,
- index: 44,
+ base: 63,
+ index: 64,
),
AccessIndex(
- base: 56,
+ base: 65,
index: 1,
),
Access(
- base: 57,
+ base: 66,
index: 31,
),
+ Load(
+ pointer: 67,
+ ),
AccessIndex(
base: 6,
index: 0,
),
+ Load(
+ pointer: 44,
+ ),
Access(
- base: 59,
- index: 44,
+ base: 69,
+ index: 70,
),
AccessIndex(
- base: 60,
+ base: 71,
index: 1,
),
Access(
- base: 61,
+ base: 72,
index: 38,
),
+ Load(
+ pointer: 73,
+ ),
AccessIndex(
base: 6,
index: 0,
),
+ Load(
+ pointer: 44,
+ ),
Access(
- base: 63,
- index: 44,
+ base: 75,
+ index: 76,
),
AccessIndex(
- base: 64,
+ base: 77,
index: 1,
),
Access(
- base: 65,
+ base: 78,
index: 13,
),
+ Load(
+ pointer: 79,
+ ),
Compose(
ty: 2,
components: [
- 58,
- 62,
- 66,
+ 68,
+ 74,
+ 80,
],
),
Access(
base: 3,
index: 36,
),
+ Load(
+ pointer: 82,
+ ),
Access(
base: 3,
index: 12,
),
+ Load(
+ pointer: 84,
+ ),
Access(
base: 3,
index: 23,
),
+ Load(
+ pointer: 86,
+ ),
Compose(
ty: 2,
components: [
- 68,
- 69,
- 70,
+ 83,
+ 85,
+ 87,
],
),
Binary(
op: Subtract,
- left: 67,
- right: 71,
+ left: 81,
+ right: 88,
),
Math(
fun: Normalize,
- arg: 72,
+ arg: 89,
arg1: None,
arg2: None,
),
Math(
fun: Dot,
- arg: 54,
- arg1: Some(73),
+ arg: 62,
+ arg1: Some(90),
arg2: None,
),
Math(
fun: Max,
arg: 42,
- arg1: Some(74),
+ arg1: Some(91),
arg2: None,
),
Binary(
op: Multiply,
- left: 53,
- right: 75,
+ left: 60,
+ right: 92,
),
AccessIndex(
base: 6,
index: 0,
),
+ Load(
+ pointer: 44,
+ ),
Access(
- base: 77,
- index: 44,
+ base: 94,
+ index: 95,
),
AccessIndex(
- base: 78,
+ base: 96,
index: 2,
),
Access(
- base: 79,
+ base: 97,
index: 10,
),
+ Load(
+ pointer: 98,
+ ),
AccessIndex(
base: 6,
index: 0,
),
+ Load(
+ pointer: 44,
+ ),
Access(
- base: 81,
- index: 44,
+ base: 100,
+ index: 101,
),
AccessIndex(
- base: 82,
+ base: 102,
index: 2,
),
Access(
- base: 83,
+ base: 103,
index: 19,
),
+ Load(
+ pointer: 104,
+ ),
AccessIndex(
base: 6,
index: 0,
),
+ Load(
+ pointer: 44,
+ ),
Access(
- base: 85,
- index: 44,
+ base: 106,
+ index: 107,
),
AccessIndex(
- base: 86,
+ base: 108,
index: 2,
),
Access(
- base: 87,
+ base: 109,
index: 26,
),
+ Load(
+ pointer: 110,
+ ),
Compose(
ty: 2,
components: [
- 80,
- 84,
- 88,
+ 99,
+ 105,
+ 111,
],
),
Binary(
op: Multiply,
- left: 89,
- right: 76,
+ left: 112,
+ right: 93,
),
Binary(
op: Add,
- left: 43,
- right: 90,
+ left: 51,
+ right: 113,
+ ),
+ Load(
+ pointer: 44,
),
Binary(
op: Add,
- left: 44,
+ left: 115,
right: 27,
),
+ Load(
+ pointer: 43,
+ ),
Compose(
ty: 4,
components: [
- 43,
+ 117,
30,
],
),
diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap
--- a/tests/out/shadow.ron.snap
+++ b/tests/out/shadow.ron.snap
@@ -1088,36 +1171,56 @@ expression: output
body: [
Loop(
body: [
+ Emit((
+ start: 44,
+ end: 50,
+ )),
If(
- condition: 48,
+ condition: 50,
accept: [
Break,
],
reject: [],
),
+ Emit((
+ start: 50,
+ end: 59,
+ )),
Call(
function: 1,
arguments: [
- 44,
52,
+ 59,
],
- result: Some(53),
+ result: Some(60),
),
+ Emit((
+ start: 60,
+ end: 114,
+ )),
Store(
pointer: 43,
- value: 91,
+ value: 114,
),
],
continuing: [
+ Emit((
+ start: 114,
+ end: 116,
+ )),
Store(
pointer: 44,
- value: 92,
+ value: 116,
),
],
),
+ Emit((
+ start: 116,
+ end: 118,
+ )),
Store(
pointer: 7,
- value: 93,
+ value: 118,
),
Return(
value: None,
diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap
--- a/tests/out/shadow.spvasm.snap
+++ b/tests/out/shadow.spvasm.snap
@@ -5,57 +5,57 @@ expression: dis
; SPIR-V
; Version: 1.2
; Generator: rspirv
-; Bound: 219
+; Bound: 137
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
-OpEntryPoint Fragment %63 "fs_main" %112 %105 %215
-OpExecutionMode %63 OriginUpperLeft
+OpEntryPoint Fragment %78 "fs_main" %32 %34 %36
+OpExecutionMode %78 OriginUpperLeft
OpSource GLSL 450
OpName %9 "c_ambient"
OpName %11 "c_max_lights"
-OpName %18 "fetch_shadow"
-OpName %27 "t_shadow"
-OpName %32 "sampler_shadow"
-OpName %59 "color"
-OpName %61 "i"
-OpName %63 "fs_main"
-OpName %75 "Globals"
-OpMemberName %75 0 "num_lights"
-OpName %76 "u_globals"
-OpName %91 "Light"
-OpMemberName %91 0 "proj"
-OpMemberName %91 1 "pos"
-OpMemberName %91 2 "color"
-OpName %95 "Lights"
-OpMemberName %95 0 "data"
-OpName %96 "s_lights"
-OpName %105 "in_position_fs"
-OpName %112 "in_normal_fs"
-OpName %215 "out_color_fs"
-OpName %63 "fs_main"
-OpDecorate %27 DescriptorSet 0
-OpDecorate %27 Binding 2
-OpDecorate %32 DescriptorSet 0
-OpDecorate %32 Binding 3
-OpDecorate %75 Block
-OpMemberDecorate %75 0 Offset 0
-OpDecorate %76 DescriptorSet 0
-OpDecorate %76 Binding 0
-OpMemberDecorate %91 0 Offset 0
-OpMemberDecorate %91 0 ColMajor
-OpMemberDecorate %91 0 MatrixStride 16
-OpMemberDecorate %91 1 Offset 64
-OpMemberDecorate %91 2 Offset 80
-OpDecorate %93 ArrayStride 96
-OpDecorate %95 BufferBlock
-OpMemberDecorate %95 0 Offset 0
-OpDecorate %96 NonWritable
-OpDecorate %96 DescriptorSet 0
-OpDecorate %96 Binding 1
-OpDecorate %105 Location 1
-OpDecorate %112 Location 0
-OpDecorate %215 Location 0
+OpName %16 "Globals"
+OpMemberName %16 0 "num_lights"
+OpName %15 "u_globals"
+OpName %20 "Lights"
+OpMemberName %20 0 "data"
+OpName %22 "Light"
+OpMemberName %22 0 "proj"
+OpMemberName %22 1 "pos"
+OpMemberName %22 2 "color"
+OpName %19 "s_lights"
+OpName %26 "t_shadow"
+OpName %29 "sampler_shadow"
+OpName %32 "in_normal_fs"
+OpName %34 "in_position_fs"
+OpName %36 "out_color_fs"
+OpName %40 "fetch_shadow"
+OpName %74 "color"
+OpName %76 "i"
+OpName %78 "fs_main"
+OpName %78 "fs_main"
+OpDecorate %16 Block
+OpMemberDecorate %16 0 Offset 0
+OpDecorate %15 DescriptorSet 0
+OpDecorate %15 Binding 0
+OpDecorate %20 BufferBlock
+OpMemberDecorate %20 0 Offset 0
+OpDecorate %21 ArrayStride 96
+OpMemberDecorate %22 0 Offset 0
+OpMemberDecorate %22 0 ColMajor
+OpMemberDecorate %22 0 MatrixStride 16
+OpMemberDecorate %22 1 Offset 64
+OpMemberDecorate %22 2 Offset 80
+OpDecorate %19 NonWritable
+OpDecorate %19 DescriptorSet 0
+OpDecorate %19 Binding 1
+OpDecorate %26 DescriptorSet 0
+OpDecorate %26 Binding 2
+OpDecorate %29 DescriptorSet 0
+OpDecorate %29 Binding 3
+OpDecorate %32 Location 0
+OpDecorate %34 Location 1
+OpDecorate %36 Location 0
%2 = OpTypeVoid
%4 = OpTypeFloat 32
%3 = OpConstant %4 0.0
diff --git a/tests/out/shadow.spvasm.snap b/tests/out/shadow.spvasm.snap
--- a/tests/out/shadow.spvasm.snap
+++ b/tests/out/shadow.spvasm.snap
@@ -69,225 +69,145 @@ OpDecorate %215 Location 0
%11 = OpConstant %12 10
%13 = OpConstant %12 0
%14 = OpConstant %12 1
-%17 = OpTypeVector %4 4
-%19 = OpTypeFunction %4 %12 %17
-%21 = OpTypeBool
-%26 = OpTypeImage %4 2D 1 1 0 1 Unknown
-%28 = OpTypePointer UniformConstant %26
-%27 = OpVariable %28 UniformConstant
-%30 = OpTypeSampledImage %26
-%31 = OpTypeSampler
-%33 = OpTypePointer UniformConstant %31
-%32 = OpVariable %33 UniformConstant
-%35 = OpTypeVector %4 2
-%49 = OpTypeInt 32 1
-%58 = OpConstant %4 0.0
-%60 = OpTypePointer Function %10
-%62 = OpTypePointer Function %12
-%64 = OpTypeFunction %2
-%73 = OpTypeVector %12 4
-%75 = OpTypeStruct %73
-%77 = OpTypePointer Uniform %75
-%76 = OpVariable %77 Uniform
-%78 = OpTypePointer Uniform %73
-%79 = OpConstant %49 0
-%80 = OpTypePointer Uniform %12
-%81 = OpConstant %49 0
-%89 = OpTypeMatrix %17 4
-%91 = OpTypeStruct %89 %17 %17
-%93 = OpTypeRuntimeArray %91
-%95 = OpTypeStruct %93
-%97 = OpTypePointer Uniform %95
-%96 = OpVariable %97 Uniform
-%98 = OpTypePointer Uniform %93
-%99 = OpConstant %49 0
-%101 = OpTypePointer Uniform %91
-%102 = OpTypePointer Uniform %89
-%103 = OpConstant %49 0
-%106 = OpTypePointer Input %17
-%105 = OpVariable %106 Input
-%113 = OpTypePointer Input %10
-%112 = OpVariable %113 Input
-%121 = OpTypePointer Uniform %93
-%122 = OpConstant %49 0
-%124 = OpTypePointer Uniform %91
-%125 = OpTypePointer Uniform %17
-%126 = OpConstant %49 1
-%127 = OpTypePointer Uniform %4
-%128 = OpConstant %49 0
-%134 = OpTypePointer Uniform %93
-%135 = OpConstant %49 0
-%137 = OpTypePointer Uniform %91
-%138 = OpTypePointer Uniform %17
-%139 = OpConstant %49 1
-%140 = OpTypePointer Uniform %4
-%141 = OpConstant %49 1
-%147 = OpTypePointer Uniform %93
-%148 = OpConstant %49 0
-%150 = OpTypePointer Uniform %91
-%151 = OpTypePointer Uniform %17
-%152 = OpConstant %49 1
-%153 = OpTypePointer Uniform %4
-%154 = OpConstant %49 2
-%158 = OpTypePointer Input %4
-%159 = OpConstant %49 0
-%162 = OpTypePointer Input %4
-%163 = OpConstant %49 1
-%166 = OpTypePointer Input %4
-%167 = OpConstant %49 2
-%177 = OpTypePointer Uniform %93
-%178 = OpConstant %49 0
-%180 = OpTypePointer Uniform %91
-%181 = OpTypePointer Uniform %17
-%182 = OpConstant %49 2
-%183 = OpTypePointer Uniform %4
-%184 = OpConstant %49 0
-%190 = OpTypePointer Uniform %93
-%191 = OpConstant %49 0
-%193 = OpTypePointer Uniform %91
-%194 = OpTypePointer Uniform %17
-%195 = OpConstant %49 2
-%196 = OpTypePointer Uniform %4
-%197 = OpConstant %49 1
-%203 = OpTypePointer Uniform %93
-%204 = OpConstant %49 0
-%206 = OpTypePointer Uniform %91
-%207 = OpTypePointer Uniform %17
-%208 = OpConstant %49 2
-%209 = OpTypePointer Uniform %4
-%210 = OpConstant %49 2
-%216 = OpTypePointer Output %17
-%215 = OpVariable %216 Output
-%18 = OpFunction %4 None %19
-%15 = OpFunctionParameter %12
-%16 = OpFunctionParameter %17
-%20 = OpLabel
-%23 = OpCompositeExtract %4 %16 3
-%22 = OpFOrdLessThanEqual %21 %23 %3
-OpSelectionMerge %24 None
-OpBranchConditional %22 %25 %24
-%25 = OpLabel
+%17 = OpTypeVector %12 4
+%16 = OpTypeStruct %17
+%18 = OpTypePointer Uniform %16
+%15 = OpVariable %18 Uniform
+%24 = OpTypeVector %4 4
+%23 = OpTypeMatrix %24 4
+%22 = OpTypeStruct %23 %24 %24
+%21 = OpTypeRuntimeArray %22
+%20 = OpTypeStruct %21
+%25 = OpTypePointer Uniform %20
+%19 = OpVariable %25 Uniform
+%27 = OpTypeImage %4 2D 1 1 0 1 Unknown
+%28 = OpTypePointer UniformConstant %27
+%26 = OpVariable %28 UniformConstant
+%30 = OpTypeSampler
+%31 = OpTypePointer UniformConstant %30
+%29 = OpVariable %31 UniformConstant
+%33 = OpTypePointer Input %10
+%32 = OpVariable %33 Input
+%35 = OpTypePointer Input %24
+%34 = OpVariable %35 Input
+%37 = OpTypePointer Output %24
+%36 = OpVariable %37 Output
+%41 = OpTypeFunction %4 %12 %24
+%47 = OpTypeBool
+%51 = OpTypeVector %4 2
+%62 = OpTypeInt 32 1
+%66 = OpTypeSampledImage %27
+%73 = OpConstant %4 0.0
+%75 = OpTypePointer Function %10
+%77 = OpTypePointer Function %12
+%79 = OpTypeFunction %2
+%91 = OpConstant %62 0
+%93 = OpTypePointer Uniform %17
+%101 = OpConstant %62 0
+%103 = OpTypePointer Uniform %22
+%40 = OpFunction %4 None %41
+%38 = OpFunctionParameter %12
+%39 = OpFunctionParameter %24
+%42 = OpLabel
+%43 = OpLoad %27 %26
+%44 = OpLoad %30 %29
+OpBranch %45
+%45 = OpLabel
+%46 = OpCompositeExtract %4 %39 3
+%48 = OpFOrdLessThanEqual %47 %46 %3
+OpSelectionMerge %49 None
+OpBranchConditional %48 %50 %49
+%50 = OpLabel
OpReturnValue %5
-%24 = OpLabel
-%29 = OpLoad %26 %27
-%34 = OpLoad %31 %32
-%39 = OpCompositeExtract %4 %16 0
-%40 = OpCompositeExtract %4 %16 1
-%41 = OpCompositeConstruct %35 %39 %40
-%42 = OpCompositeConstruct %35 %6 %7
-%38 = OpFMul %35 %41 %42
-%44 = OpCompositeExtract %4 %16 3
-%43 = OpFDiv %4 %5 %44
-%37 = OpVectorTimesScalar %35 %38 %43
-%45 = OpCompositeConstruct %35 %6 %6
-%36 = OpFAdd %35 %37 %45
-%46 = OpCompositeExtract %4 %36 0
-%47 = OpCompositeExtract %4 %36 1
-%50 = OpBitcast %49 %15
-%48 = OpConvertUToF %4 %50
-%51 = OpCompositeConstruct %10 %46 %47 %48
-%52 = OpSampledImage %30 %29 %34
-%55 = OpCompositeExtract %4 %16 2
-%57 = OpCompositeExtract %4 %16 3
-%56 = OpFDiv %4 %5 %57
-%54 = OpFMul %4 %55 %56
-%53 = OpImageSampleDrefExplicitLod %4 %52 %51 %54 Lod %58
-OpReturnValue %53
+%49 = OpLabel
+%52 = OpCompositeConstruct %51 %6 %7
+%53 = OpCompositeExtract %4 %39 3
+%54 = OpFDiv %4 %5 %53
+%55 = OpCompositeExtract %4 %39 0
+%56 = OpCompositeExtract %4 %39 1
+%57 = OpCompositeConstruct %51 %55 %56
+%58 = OpFMul %51 %57 %52
+%59 = OpVectorTimesScalar %51 %58 %54
+%60 = OpCompositeConstruct %51 %6 %6
+%61 = OpFAdd %51 %59 %60
+%63 = OpBitcast %62 %38
+%64 = OpCompositeExtract %4 %39 2
+%65 = OpFMul %4 %64 %54
+%67 = OpCompositeExtract %4 %61 0
+%68 = OpCompositeExtract %4 %61 1
+%69 = OpConvertUToF %4 %63
+%70 = OpCompositeConstruct %10 %67 %68 %69
+%71 = OpSampledImage %66 %43 %44
+%72 = OpImageSampleDrefExplicitLod %4 %71 %70 %65 Lod %73
+OpReturnValue %72
OpFunctionEnd
-%63 = OpFunction %2 None %64
-%65 = OpLabel
-%59 = OpVariable %60 Function %9
-%61 = OpVariable %62 Function %13
-OpBranch %66
-%66 = OpLabel
-OpLoopMerge %67 %69 None
-OpBranch %68
-%68 = OpLabel
-%71 = OpLoad %12 %61
-%74 = OpAccessChain %78 %76 %79
-%72 = OpAccessChain %80 %74 %81
-%82 = OpLoad %12 %72
-%83 = OpExtInst %12 %1 UMin %82 %11
-%70 = OpUGreaterThanEqual %21 %71 %83
-OpSelectionMerge %84 None
-OpBranchConditional %70 %85 %84
-%85 = OpLabel
-OpBranch %67
-%84 = OpLabel
-%87 = OpLoad %12 %61
-%94 = OpAccessChain %98 %96 %99
-%100 = OpLoad %12 %61
-%92 = OpAccessChain %101 %94 %100
-%90 = OpAccessChain %102 %92 %103
-%104 = OpLoad %89 %90
-%107 = OpLoad %17 %105
-%88 = OpMatrixTimesVector %17 %104 %107
-%86 = OpFunctionCall %4 %18 %87 %88
-%109 = OpLoad %10 %59
-%114 = OpLoad %10 %112
-%115 = OpExtInst %10 %1 Normalize %114
-%120 = OpAccessChain %121 %96 %122
-%123 = OpLoad %12 %61
-%119 = OpAccessChain %124 %120 %123
-%118 = OpAccessChain %125 %119 %126
-%117 = OpAccessChain %127 %118 %128
-%129 = OpLoad %4 %117
-%133 = OpAccessChain %134 %96 %135
-%136 = OpLoad %12 %61
-%132 = OpAccessChain %137 %133 %136
-%131 = OpAccessChain %138 %132 %139
-%130 = OpAccessChain %140 %131 %141
-%142 = OpLoad %4 %130
-%146 = OpAccessChain %147 %96 %148
-%149 = OpLoad %12 %61
-%145 = OpAccessChain %150 %146 %149
-%144 = OpAccessChain %151 %145 %152
-%143 = OpAccessChain %153 %144 %154
-%155 = OpLoad %4 %143
-%156 = OpCompositeConstruct %10 %129 %142 %155
-%157 = OpAccessChain %158 %105 %159
-%160 = OpLoad %4 %157
-%161 = OpAccessChain %162 %105 %163
-%164 = OpLoad %4 %161
-%165 = OpAccessChain %166 %105 %167
-%168 = OpLoad %4 %165
-%169 = OpCompositeConstruct %10 %160 %164 %168
-%116 = OpFSub %10 %156 %169
-%170 = OpExtInst %10 %1 Normalize %116
-%171 = OpDot %4 %115 %170
-%172 = OpExtInst %4 %1 FMax %3 %171
-%111 = OpFMul %4 %86 %172
-%176 = OpAccessChain %177 %96 %178
-%179 = OpLoad %12 %61
-%175 = OpAccessChain %180 %176 %179
-%174 = OpAccessChain %181 %175 %182
-%173 = OpAccessChain %183 %174 %184
-%185 = OpLoad %4 %173
-%189 = OpAccessChain %190 %96 %191
-%192 = OpLoad %12 %61
-%188 = OpAccessChain %193 %189 %192
-%187 = OpAccessChain %194 %188 %195
-%186 = OpAccessChain %196 %187 %197
-%198 = OpLoad %4 %186
-%202 = OpAccessChain %203 %96 %204
-%205 = OpLoad %12 %61
-%201 = OpAccessChain %206 %202 %205
-%200 = OpAccessChain %207 %201 %208
-%199 = OpAccessChain %209 %200 %210
-%211 = OpLoad %4 %199
-%212 = OpCompositeConstruct %10 %185 %198 %211
-%110 = OpVectorTimesScalar %10 %212 %111
-%108 = OpFAdd %10 %109 %110
-OpStore %59 %108
-OpBranch %69
-%69 = OpLabel
-%214 = OpLoad %12 %61
-%213 = OpIAdd %12 %214 %14
-OpStore %61 %213
-OpBranch %66
-%67 = OpLabel
-%217 = OpLoad %10 %59
-%218 = OpCompositeConstruct %17 %217 %5
-OpStore %215 %218
+%78 = OpFunction %2 None %79
+%80 = OpLabel
+%74 = OpVariable %75 Function %9
+%76 = OpVariable %77 Function %13
+%81 = OpLoad %27 %26
+%82 = OpLoad %30 %29
+OpBranch %83
+%83 = OpLabel
+%84 = OpLoad %10 %32
+%85 = OpExtInst %10 %1 Normalize %84
+OpBranch %86
+%86 = OpLabel
+OpLoopMerge %87 %89 None
+OpBranch %88
+%88 = OpLabel
+%90 = OpLoad %12 %76
+%92 = OpAccessChain %93 %15 %91
+%94 = OpLoad %17 %92
+%95 = OpCompositeExtract %12 %94 0
+%96 = OpExtInst %12 %1 UMin %95 %11
+%97 = OpUGreaterThanEqual %47 %90 %96
+OpSelectionMerge %98 None
+OpBranchConditional %97 %99 %98
+%99 = OpLabel
+OpBranch %87
+%98 = OpLabel
+%100 = OpLoad %12 %76
+%102 = OpAccessChain %103 %19 %101 %100
+%104 = OpLoad %22 %102
+%105 = OpLoad %12 %76
+%106 = OpCompositeExtract %23 %104 0
+%107 = OpLoad %24 %34
+%108 = OpMatrixTimesVector %24 %106 %107
+%109 = OpFunctionCall %4 %40 %105 %108
+%110 = OpCompositeExtract %24 %104 1
+%111 = OpCompositeExtract %4 %110 0
+%112 = OpCompositeExtract %4 %110 1
+%113 = OpCompositeExtract %4 %110 2
+%114 = OpCompositeConstruct %10 %111 %112 %113
+%115 = OpLoad %24 %34
+%116 = OpCompositeExtract %4 %115 0
+%117 = OpCompositeExtract %4 %115 1
+%118 = OpCompositeExtract %4 %115 2
+%119 = OpCompositeConstruct %10 %116 %117 %118
+%120 = OpFSub %10 %114 %119
+%121 = OpExtInst %10 %1 Normalize %120
+%122 = OpDot %4 %85 %121
+%123 = OpExtInst %4 %1 FMax %3 %122
+%124 = OpLoad %10 %74
+%125 = OpFMul %4 %109 %123
+%126 = OpCompositeExtract %24 %104 2
+%127 = OpCompositeExtract %4 %126 0
+%128 = OpCompositeExtract %4 %126 1
+%129 = OpCompositeExtract %4 %126 2
+%130 = OpCompositeConstruct %10 %127 %128 %129
+%131 = OpVectorTimesScalar %10 %130 %125
+%132 = OpFAdd %10 %124 %131
+OpStore %74 %132
+OpBranch %89
+%89 = OpLabel
+%133 = OpLoad %12 %76
+%134 = OpIAdd %12 %133 %14
+OpStore %76 %134
+OpBranch %86
+%87 = OpLabel
+%135 = OpLoad %10 %74
+%136 = OpCompositeConstruct %24 %135 %5
+OpStore %36 %136
OpReturn
OpFunctionEnd
diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap
--- a/tests/out/skybox-Fragment.glsl.snap
+++ b/tests/out/skybox-Fragment.glsl.snap
@@ -18,6 +18,7 @@ in vec3 _location_0_vs;
out vec4 _location_0;
void main() {
+ ;
_location_0 = texture(_group_0_binding_1, vec3(_location_0_vs));
return;
}
diff --git a/tests/out/skybox-Vertex.glsl.snap b/tests/out/skybox-Vertex.glsl.snap
--- a/tests/out/skybox-Vertex.glsl.snap
+++ b/tests/out/skybox-Vertex.glsl.snap
@@ -22,11 +22,24 @@ void main() {
int tmp1_;
int tmp2_;
vec4 unprojected;
+ ;
+ ;
tmp1_ = (int(gl_VertexID) / 2);
+ ;
+ ;
tmp2_ = (int(gl_VertexID) & 1);
- unprojected = (_group_0_binding_0.proj_inv * vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0));
- _location_0_vs = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(unprojected[0], unprojected[1], unprojected[2]));
- gl_Position = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0);
+ ;
+ ;
+ ;
+ ;
+ ;
+ vec4 _expr28 = vec4(((float(tmp1_) * 4.0) - 1.0), ((float(tmp2_) * 4.0) - 1.0), 0.0, 1.0);
+ ;
+ ;
+ unprojected = (_group_0_binding_0.proj_inv * _expr28);
+ vec4 _expr56 = unprojected;
+ _location_0_vs = (transpose(mat3x3(vec3(_group_0_binding_0.view[0][0], _group_0_binding_0.view[0][1], _group_0_binding_0.view[0][2]), vec3(_group_0_binding_0.view[1][0], _group_0_binding_0.view[1][1], _group_0_binding_0.view[1][2]), vec3(_group_0_binding_0.view[2][0], _group_0_binding_0.view[2][1], _group_0_binding_0.view[2][2]))) * vec3(_expr56[0], _expr56[1], _expr56[2]));
+ gl_Position = _expr28;
return;
}
diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap
--- a/tests/out/skybox.msl.snap
+++ b/tests/out/skybox.msl.snap
@@ -20,9 +20,9 @@ struct Data {
typedef int type4;
-typedef metal::float3x3 type5;
+typedef float type5;
-typedef float type6;
+typedef metal::float3x3 type6;
typedef metal::texturecube<float, metal::access::sample> type7;
diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap
--- a/tests/out/skybox.msl.snap
+++ b/tests/out/skybox.msl.snap
@@ -52,10 +52,11 @@ vertex vs_mainOutput vs_main(
type unprojected;
tmp1_ = (static_cast<int>(in_vertex_index) / const_2i);
tmp2_ = (static_cast<int>(in_vertex_index) & const_1i);
- type _expr24 = metal::float4(((static_cast<float>(tmp1_) * const_4f) - const_1f), ((static_cast<float>(tmp2_) * const_4f) - const_1f), const_0f, const_1f);
- unprojected = (r_data.proj_inv * _expr24);
- output.out_uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(unprojected.x, unprojected.y, unprojected.z));
- output.out_position = _expr24;
+ type _expr28 = metal::float4(((static_cast<float>(tmp1_) * const_4f) - const_1f), ((static_cast<float>(tmp2_) * const_4f) - const_1f), const_0f, const_1f);
+ unprojected = (r_data.proj_inv * _expr28);
+ type _expr56 = unprojected;
+ output.out_uv = (metal::transpose(metal::float3x3(metal::float3(r_data.view[0].x, r_data.view[0].y, r_data.view[0].z), metal::float3(r_data.view[1].x, r_data.view[1].y, r_data.view[1].z), metal::float3(r_data.view[2].x, r_data.view[2].y, r_data.view[2].z))) * metal::float3(_expr56.x, _expr56.y, _expr56.z));
+ output.out_position = _expr28;
return output;
}
diff --git a/tests/out/skybox.msl.snap b/tests/out/skybox.msl.snap
--- a/tests/out/skybox.msl.snap
+++ b/tests/out/skybox.msl.snap
@@ -73,7 +74,8 @@ fragment fs_mainOutput fs_main(
type8 r_sampler [[sampler(1)]]
) {
fs_mainOutput output;
- output.out_color = r_texture.sample(r_sampler, input.in_uv);
+ metal::float4 _expr9 = r_texture.sample(r_sampler, input.in_uv);
+ output.out_color = _expr9;
return output;
}
diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap
--- a/tests/out/skybox.spvasm.snap
+++ b/tests/out/skybox.spvasm.snap
@@ -5,50 +5,50 @@ expression: dis
; SPIR-V
; Version: 1.0
; Generator: rspirv
-; Bound: 187
+; Bound: 106
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
-OpEntryPoint Vertex %16 "vs_main" %159 %47 %21
-OpEntryPoint Fragment %170 "fs_main" %182 %172
-OpExecutionMode %170 OriginUpperLeft
+OpEntryPoint Vertex %37 "vs_main" %10 %13 %16
+OpEntryPoint Fragment %97 "fs_main" %29 %31
+OpExecutionMode %97 OriginUpperLeft
OpSource GLSL 450
-OpName %10 "tmp1"
-OpName %12 "tmp2"
-OpName %13 "unprojected"
-OpName %16 "vs_main"
-OpName %21 "in_vertex_index"
-OpName %31 "Data"
-OpMemberName %31 0 "proj_inv"
-OpMemberName %31 1 "view"
-OpName %32 "r_data"
-OpName %47 "out_uv"
-OpName %159 "out_position"
-OpName %16 "vs_main"
-OpName %170 "fs_main"
-OpName %172 "out_color"
-OpName %174 "r_texture"
-OpName %179 "r_sampler"
-OpName %182 "in_uv"
-OpName %170 "fs_main"
-OpDecorate %21 BuiltIn VertexIndex
-OpDecorate %31 Block
-OpMemberDecorate %31 0 Offset 0
-OpMemberDecorate %31 0 ColMajor
-OpMemberDecorate %31 0 MatrixStride 16
-OpMemberDecorate %31 1 Offset 64
-OpMemberDecorate %31 1 ColMajor
-OpMemberDecorate %31 1 MatrixStride 16
-OpDecorate %32 DescriptorSet 0
-OpDecorate %32 Binding 0
-OpDecorate %47 Location 0
-OpDecorate %159 BuiltIn Position
-OpDecorate %172 Location 0
-OpDecorate %174 DescriptorSet 0
-OpDecorate %174 Binding 1
-OpDecorate %179 DescriptorSet 0
-OpDecorate %179 Binding 2
-OpDecorate %182 Location 0
+OpName %10 "out_position"
+OpName %13 "out_uv"
+OpName %16 "in_vertex_index"
+OpName %20 "Data"
+OpMemberName %20 0 "proj_inv"
+OpMemberName %20 1 "view"
+OpName %19 "r_data"
+OpName %23 "r_texture"
+OpName %26 "r_sampler"
+OpName %29 "in_uv"
+OpName %31 "out_color"
+OpName %32 "tmp1"
+OpName %34 "tmp2"
+OpName %35 "unprojected"
+OpName %37 "vs_main"
+OpName %37 "vs_main"
+OpName %97 "fs_main"
+OpName %97 "fs_main"
+OpDecorate %10 BuiltIn Position
+OpDecorate %13 Location 0
+OpDecorate %16 BuiltIn VertexIndex
+OpDecorate %20 Block
+OpMemberDecorate %20 0 Offset 0
+OpMemberDecorate %20 0 ColMajor
+OpMemberDecorate %20 0 MatrixStride 16
+OpMemberDecorate %20 1 Offset 64
+OpMemberDecorate %20 1 ColMajor
+OpMemberDecorate %20 1 MatrixStride 16
+OpDecorate %19 DescriptorSet 0
+OpDecorate %19 Binding 0
+OpDecorate %23 DescriptorSet 0
+OpDecorate %23 Binding 1
+OpDecorate %26 DescriptorSet 0
+OpDecorate %26 Binding 2
+OpDecorate %29 Location 0
+OpDecorate %31 Location 0
%2 = OpTypeVoid
%4 = OpTypeInt 32 1
%3 = OpConstant %4 2
diff --git a/tests/out/skybox.spvasm.snap b/tests/out/skybox.spvasm.snap
--- a/tests/out/skybox.spvasm.snap
+++ b/tests/out/skybox.spvasm.snap
@@ -57,190 +57,111 @@ OpDecorate %182 Location 0
%6 = OpConstant %7 4.0
%8 = OpConstant %7 1.0
%9 = OpConstant %7 0.0
-%11 = OpTypePointer Function %4
-%14 = OpTypeVector %7 4
-%15 = OpTypePointer Function %14
-%17 = OpTypeFunction %2
-%20 = OpTypeInt 32 0
-%22 = OpTypePointer Input %20
-%21 = OpVariable %22 Input
-%29 = OpTypeMatrix %14 4
-%31 = OpTypeStruct %29 %29
-%33 = OpTypePointer Uniform %31
-%32 = OpVariable %33 Uniform
-%34 = OpTypePointer Uniform %29
-%35 = OpConstant %4 0
-%46 = OpTypeVector %7 3
-%48 = OpTypePointer Output %46
-%47 = OpVariable %48 Output
-%50 = OpTypeMatrix %46 3
-%54 = OpTypePointer Uniform %29
-%55 = OpConstant %4 1
-%56 = OpTypePointer Uniform %14
-%57 = OpConstant %4 0
-%58 = OpTypePointer Uniform %7
-%59 = OpConstant %4 0
-%64 = OpTypePointer Uniform %29
+%11 = OpTypeVector %7 4
+%12 = OpTypePointer Output %11
+%10 = OpVariable %12 Output
+%14 = OpTypeVector %7 3
+%15 = OpTypePointer Output %14
+%13 = OpVariable %15 Output
+%17 = OpTypeInt 32 0
+%18 = OpTypePointer Input %17
+%16 = OpVariable %18 Input
+%21 = OpTypeMatrix %11 4
+%20 = OpTypeStruct %21 %21
+%22 = OpTypePointer Uniform %20
+%19 = OpVariable %22 Uniform
+%24 = OpTypeImage %7 Cube 0 0 0 1 Unknown
+%25 = OpTypePointer UniformConstant %24
+%23 = OpVariable %25 UniformConstant
+%27 = OpTypeSampler
+%28 = OpTypePointer UniformConstant %27
+%26 = OpVariable %28 UniformConstant
+%30 = OpTypePointer Input %14
+%29 = OpVariable %30 Input
+%31 = OpVariable %12 Output
+%33 = OpTypePointer Function %4
+%36 = OpTypePointer Function %11
+%38 = OpTypeFunction %2
+%56 = OpConstant %4 1
+%58 = OpTypePointer Uniform %21
%65 = OpConstant %4 1
-%66 = OpTypePointer Uniform %14
-%67 = OpConstant %4 0
-%68 = OpTypePointer Uniform %7
-%69 = OpConstant %4 1
-%74 = OpTypePointer Uniform %29
-%75 = OpConstant %4 1
-%76 = OpTypePointer Uniform %14
-%77 = OpConstant %4 0
-%78 = OpTypePointer Uniform %7
-%79 = OpConstant %4 2
-%85 = OpTypePointer Uniform %29
-%86 = OpConstant %4 1
-%87 = OpTypePointer Uniform %14
-%88 = OpConstant %4 1
-%89 = OpTypePointer Uniform %7
-%90 = OpConstant %4 0
-%95 = OpTypePointer Uniform %29
-%96 = OpConstant %4 1
-%97 = OpTypePointer Uniform %14
-%98 = OpConstant %4 1
-%99 = OpTypePointer Uniform %7
-%100 = OpConstant %4 1
-%105 = OpTypePointer Uniform %29
-%106 = OpConstant %4 1
-%107 = OpTypePointer Uniform %14
-%108 = OpConstant %4 1
-%109 = OpTypePointer Uniform %7
-%110 = OpConstant %4 2
-%116 = OpTypePointer Uniform %29
-%117 = OpConstant %4 1
-%118 = OpTypePointer Uniform %14
-%119 = OpConstant %4 2
-%120 = OpTypePointer Uniform %7
-%121 = OpConstant %4 0
-%126 = OpTypePointer Uniform %29
-%127 = OpConstant %4 1
-%128 = OpTypePointer Uniform %14
-%129 = OpConstant %4 2
-%130 = OpTypePointer Uniform %7
-%131 = OpConstant %4 1
-%136 = OpTypePointer Uniform %29
-%137 = OpConstant %4 1
-%138 = OpTypePointer Uniform %14
-%139 = OpConstant %4 2
-%140 = OpTypePointer Uniform %7
-%141 = OpConstant %4 2
-%147 = OpTypePointer Function %7
-%148 = OpConstant %4 0
-%151 = OpTypePointer Function %7
-%152 = OpConstant %4 1
-%155 = OpTypePointer Function %7
-%156 = OpConstant %4 2
-%160 = OpTypePointer Output %14
-%159 = OpVariable %160 Output
-%172 = OpVariable %160 Output
-%173 = OpTypeImage %7 Cube 0 0 0 1 Unknown
-%175 = OpTypePointer UniformConstant %173
-%174 = OpVariable %175 UniformConstant
-%177 = OpTypeSampledImage %173
-%178 = OpTypeSampler
-%180 = OpTypePointer UniformConstant %178
-%179 = OpVariable %180 UniformConstant
-%183 = OpTypePointer Input %46
-%182 = OpVariable %183 Input
-%16 = OpFunction %2 None %17
-%18 = OpLabel
-%10 = OpVariable %11 Function
-%12 = OpVariable %11 Function
-%13 = OpVariable %15 Function
-%23 = OpLoad %20 %21
-%24 = OpBitcast %4 %23
-%19 = OpSDiv %4 %24 %3
-OpStore %10 %19
-%26 = OpLoad %20 %21
-%27 = OpBitcast %4 %26
-%25 = OpBitwiseAnd %4 %27 %5
-OpStore %12 %25
-%30 = OpAccessChain %34 %32 %35
-%36 = OpLoad %29 %30
-%39 = OpLoad %4 %10
-%40 = OpConvertSToF %7 %39
-%38 = OpFMul %7 %40 %6
-%37 = OpFSub %7 %38 %8
-%43 = OpLoad %4 %12
-%44 = OpConvertSToF %7 %43
-%42 = OpFMul %7 %44 %6
-%41 = OpFSub %7 %42 %8
-%45 = OpCompositeConstruct %14 %37 %41 %9 %8
-%28 = OpMatrixTimesVector %14 %36 %45
-OpStore %13 %28
-%53 = OpAccessChain %54 %32 %55
-%52 = OpAccessChain %56 %53 %57
-%51 = OpAccessChain %58 %52 %59
-%60 = OpLoad %7 %51
-%63 = OpAccessChain %64 %32 %65
-%62 = OpAccessChain %66 %63 %67
-%61 = OpAccessChain %68 %62 %69
-%70 = OpLoad %7 %61
-%73 = OpAccessChain %74 %32 %75
-%72 = OpAccessChain %76 %73 %77
-%71 = OpAccessChain %78 %72 %79
-%80 = OpLoad %7 %71
-%81 = OpCompositeConstruct %46 %60 %70 %80
-%84 = OpAccessChain %85 %32 %86
-%83 = OpAccessChain %87 %84 %88
-%82 = OpAccessChain %89 %83 %90
-%91 = OpLoad %7 %82
-%94 = OpAccessChain %95 %32 %96
-%93 = OpAccessChain %97 %94 %98
-%92 = OpAccessChain %99 %93 %100
-%101 = OpLoad %7 %92
-%104 = OpAccessChain %105 %32 %106
-%103 = OpAccessChain %107 %104 %108
-%102 = OpAccessChain %109 %103 %110
-%111 = OpLoad %7 %102
-%112 = OpCompositeConstruct %46 %91 %101 %111
-%115 = OpAccessChain %116 %32 %117
-%114 = OpAccessChain %118 %115 %119
-%113 = OpAccessChain %120 %114 %121
-%122 = OpLoad %7 %113
-%125 = OpAccessChain %126 %32 %127
-%124 = OpAccessChain %128 %125 %129
-%123 = OpAccessChain %130 %124 %131
-%132 = OpLoad %7 %123
-%135 = OpAccessChain %136 %32 %137
-%134 = OpAccessChain %138 %135 %139
-%133 = OpAccessChain %140 %134 %141
-%142 = OpLoad %7 %133
-%143 = OpCompositeConstruct %46 %122 %132 %142
-%144 = OpCompositeConstruct %50 %81 %112 %143
-%145 = OpTranspose %50 %144
-%146 = OpAccessChain %147 %13 %148
-%149 = OpLoad %7 %146
-%150 = OpAccessChain %151 %13 %152
-%153 = OpLoad %7 %150
-%154 = OpAccessChain %155 %13 %156
-%157 = OpLoad %7 %154
-%158 = OpCompositeConstruct %46 %149 %153 %157
-%49 = OpMatrixTimesVector %46 %145 %158
-OpStore %47 %49
-%163 = OpLoad %4 %10
-%164 = OpConvertSToF %7 %163
-%162 = OpFMul %7 %164 %6
-%161 = OpFSub %7 %162 %8
-%167 = OpLoad %4 %12
-%168 = OpConvertSToF %7 %167
-%166 = OpFMul %7 %168 %6
-%165 = OpFSub %7 %166 %8
-%169 = OpCompositeConstruct %14 %161 %165 %9 %8
-OpStore %159 %169
+%67 = OpTypePointer Uniform %21
+%74 = OpConstant %4 1
+%76 = OpTypePointer Uniform %21
+%83 = OpTypeMatrix %14 3
+%86 = OpConstant %4 0
+%88 = OpTypePointer Uniform %21
+%103 = OpTypeSampledImage %24
+%37 = OpFunction %2 None %38
+%39 = OpLabel
+%32 = OpVariable %33 Function
+%34 = OpVariable %33 Function
+%35 = OpVariable %36 Function
+OpBranch %40
+%40 = OpLabel
+%41 = OpLoad %17 %16
+%42 = OpBitcast %4 %41
+%43 = OpSDiv %4 %42 %3
+OpStore %32 %43
+%44 = OpLoad %17 %16
+%45 = OpBitcast %4 %44
+%46 = OpBitwiseAnd %4 %45 %5
+OpStore %34 %46
+%47 = OpLoad %4 %32
+%48 = OpConvertSToF %7 %47
+%49 = OpFMul %7 %48 %6
+%50 = OpFSub %7 %49 %8
+%51 = OpLoad %4 %34
+%52 = OpConvertSToF %7 %51
+%53 = OpFMul %7 %52 %6
+%54 = OpFSub %7 %53 %8
+%55 = OpCompositeConstruct %11 %50 %54 %9 %8
+%57 = OpAccessChain %58 %19 %56
+%59 = OpLoad %21 %57
+%60 = OpCompositeExtract %11 %59 0
+%61 = OpCompositeExtract %7 %60 0
+%62 = OpCompositeExtract %7 %60 1
+%63 = OpCompositeExtract %7 %60 2
+%64 = OpCompositeConstruct %14 %61 %62 %63
+%66 = OpAccessChain %67 %19 %65
+%68 = OpLoad %21 %66
+%69 = OpCompositeExtract %11 %68 1
+%70 = OpCompositeExtract %7 %69 0
+%71 = OpCompositeExtract %7 %69 1
+%72 = OpCompositeExtract %7 %69 2
+%73 = OpCompositeConstruct %14 %70 %71 %72
+%75 = OpAccessChain %76 %19 %74
+%77 = OpLoad %21 %75
+%78 = OpCompositeExtract %11 %77 2
+%79 = OpCompositeExtract %7 %78 0
+%80 = OpCompositeExtract %7 %78 1
+%81 = OpCompositeExtract %7 %78 2
+%82 = OpCompositeConstruct %14 %79 %80 %81
+%84 = OpCompositeConstruct %83 %64 %73 %82
+%85 = OpTranspose %83 %84
+%87 = OpAccessChain %88 %19 %86
+%89 = OpLoad %21 %87
+%90 = OpMatrixTimesVector %11 %89 %55
+OpStore %35 %90
+%91 = OpLoad %11 %35
+%92 = OpCompositeExtract %7 %91 0
+%93 = OpCompositeExtract %7 %91 1
+%94 = OpCompositeExtract %7 %91 2
+%95 = OpCompositeConstruct %14 %92 %93 %94
+%96 = OpMatrixTimesVector %14 %85 %95
+OpStore %13 %96
+OpStore %10 %55
OpReturn
OpFunctionEnd
-%170 = OpFunction %2 None %17
-%171 = OpLabel
-%176 = OpLoad %173 %174
-%181 = OpLoad %178 %179
-%184 = OpLoad %46 %182
-%185 = OpSampledImage %177 %176 %181
-%186 = OpImageSampleImplicitLod %14 %185 %184
-OpStore %172 %186
+%97 = OpFunction %2 None %38
+%98 = OpLabel
+%99 = OpLoad %24 %23
+%100 = OpLoad %27 %26
+OpBranch %101
+%101 = OpLabel
+%102 = OpLoad %14 %29
+%104 = OpSampledImage %103 %99 %100
+%105 = OpImageSampleImplicitLod %11 %104 %102
+OpStore %31 %105
OpReturn
OpFunctionEnd
diff --git a/tests/out/texture-array.spvasm.snap b/tests/out/texture-array.spvasm.snap
--- a/tests/out/texture-array.spvasm.snap
+++ b/tests/out/texture-array.spvasm.snap
@@ -9,78 +9,79 @@ expression: dis
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
-OpEntryPoint Fragment %5 "main" %35 %23
-OpExecutionMode %5 OriginUpperLeft
+OpEntryPoint Fragment %23 "main" %5 %20
+OpExecutionMode %23 OriginUpperLeft
OpSource GLSL 450
-OpName %5 "main"
-OpName %12 "PushConstants"
-OpMemberName %12 0 "index"
-OpName %13 "pc"
-OpName %23 "color"
-OpName %26 "texture0"
-OpName %31 "sampler"
-OpName %35 "tex_coord"
-OpName %40 "texture1"
-OpName %5 "main"
-OpDecorate %12 Block
-OpMemberDecorate %12 0 Offset 0
-OpDecorate %23 Location 1
-OpDecorate %26 DescriptorSet 0
-OpDecorate %26 Binding 0
-OpDecorate %31 DescriptorSet 0
-OpDecorate %31 Binding 2
-OpDecorate %35 Location 0
-OpDecorate %40 DescriptorSet 0
-OpDecorate %40 Binding 1
+OpName %5 "tex_coord"
+OpName %9 "texture0"
+OpName %12 "texture1"
+OpName %13 "sampler"
+OpName %17 "PushConstants"
+OpMemberName %17 0 "index"
+OpName %16 "pc"
+OpName %20 "color"
+OpName %23 "main"
+OpName %23 "main"
+OpDecorate %5 Location 0
+OpDecorate %9 DescriptorSet 0
+OpDecorate %9 Binding 0
+OpDecorate %12 DescriptorSet 0
+OpDecorate %12 Binding 1
+OpDecorate %13 DescriptorSet 0
+OpDecorate %13 Binding 2
+OpDecorate %17 Block
+OpMemberDecorate %17 0 Offset 0
+OpDecorate %20 Location 1
%2 = OpTypeVoid
%4 = OpTypeInt 32 1
%3 = OpConstant %4 0
-%6 = OpTypeFunction %2
-%8 = OpTypeBool
-%10 = OpTypeInt 32 0
-%12 = OpTypeStruct %10
-%14 = OpTypePointer PushConstant %12
-%13 = OpVariable %14 PushConstant
-%15 = OpTypePointer PushConstant %10
-%16 = OpConstant %4 0
-%22 = OpTypeFloat 32
-%21 = OpTypeVector %22 4
-%24 = OpTypePointer Output %21
-%23 = OpVariable %24 Output
-%25 = OpTypeImage %22 2D 0 0 0 1 Unknown
-%27 = OpTypePointer UniformConstant %25
-%26 = OpVariable %27 UniformConstant
-%29 = OpTypeSampledImage %25
-%30 = OpTypeSampler
-%32 = OpTypePointer UniformConstant %30
-%31 = OpVariable %32 UniformConstant
-%34 = OpTypeVector %22 2
-%36 = OpTypePointer Input %34
-%35 = OpVariable %36 Input
-%40 = OpVariable %27 UniformConstant
-%5 = OpFunction %2 None %6
-%7 = OpLabel
-%11 = OpAccessChain %15 %13 %16
-%17 = OpLoad %10 %11
-%9 = OpIEqual %8 %17 %3
-OpSelectionMerge %18 None
-OpBranchConditional %9 %19 %20
-%19 = OpLabel
-%28 = OpLoad %25 %26
-%33 = OpLoad %30 %31
-%37 = OpLoad %34 %35
-%38 = OpSampledImage %29 %28 %33
-%39 = OpImageSampleImplicitLod %21 %38 %37
-OpStore %23 %39
+%7 = OpTypeFloat 32
+%6 = OpTypeVector %7 2
+%8 = OpTypePointer Input %6
+%5 = OpVariable %8 Input
+%10 = OpTypeImage %7 2D 0 0 0 1 Unknown
+%11 = OpTypePointer UniformConstant %10
+%9 = OpVariable %11 UniformConstant
+%12 = OpVariable %11 UniformConstant
+%14 = OpTypeSampler
+%15 = OpTypePointer UniformConstant %14
+%13 = OpVariable %15 UniformConstant
+%18 = OpTypeInt 32 0
+%17 = OpTypeStruct %18
+%19 = OpTypePointer PushConstant %17
+%16 = OpVariable %19 PushConstant
+%21 = OpTypeVector %7 4
+%22 = OpTypePointer Output %21
+%20 = OpVariable %22 Output
+%24 = OpTypeFunction %2
+%30 = OpConstant %4 0
+%32 = OpTypePointer PushConstant %18
+%34 = OpTypeBool
+%40 = OpTypeSampledImage %10
+%23 = OpFunction %2 None %24
+%25 = OpLabel
+%26 = OpLoad %10 %9
+%27 = OpLoad %10 %12
+%28 = OpLoad %14 %13
+OpBranch %29
+%29 = OpLabel
+%31 = OpAccessChain %32 %16 %30
+%33 = OpLoad %18 %31
+%35 = OpIEqual %34 %33 %3
+OpSelectionMerge %36 None
+OpBranchConditional %35 %37 %38
+%37 = OpLabel
+%39 = OpLoad %6 %5
+%41 = OpSampledImage %40 %26 %28
+%42 = OpImageSampleImplicitLod %21 %41 %39
+OpStore %20 %42
OpReturn
-%20 = OpLabel
-%41 = OpLoad %25 %40
-%42 = OpLoad %30 %31
-%43 = OpLoad %34 %35
-%44 = OpSampledImage %29 %41 %42
+%38 = OpLabel
+%43 = OpLoad %6 %5
+%44 = OpSampledImage %40 %27 %28
%45 = OpImageSampleImplicitLod %21 %44 %43
-OpStore %23 %45
+OpStore %20 %45
OpReturn
-%18 = OpLabel
+%36 = OpLabel
OpReturn
OpFunctionEnd
diff --git a/tests/parse.rs b/tests/parse.rs
--- a/tests/parse.rs
+++ b/tests/parse.rs
@@ -25,7 +25,8 @@ fn check_glsl(name: &str) {
) {
Ok(m) => match naga::proc::Validator::new().validate(&m) {
Ok(_analysis) => (),
- Err(e) => panic!("Unable to validate {}: {:?}", name, e),
+ //TODO: panic
+ Err(e) => log::error!("Unable to validate {}: {:?}", name, e),
},
Err(e) => panic!("Unable to parse {}: {:?}", name, e),
};
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -56,7 +56,7 @@ fn with_snapshot_settings<F: FnOnce() -> ()>(snapshot_assertion: F) {
settings.bind(|| snapshot_assertion());
}
-#[allow(unused_variables)]
+#[allow(dead_code, unused_variables)]
fn check_targets(module: &naga::Module, name: &str, targets: Targets) {
let params = match std::fs::read_to_string(format!("tests/in/{}{}", name, ".param.ron")) {
Ok(string) => ron::de::from_str(&string).expect("Couldn't find param file"),
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -276,7 +276,7 @@ fn convert_spv_shadow() {
fn convert_glsl(
name: &str,
entry_points: naga::FastHashMap<String, naga::ShaderStage>,
- targets: Targets,
+ _targets: Targets,
) {
let module = naga::front::glsl::parse_str(
&std::fs::read_to_string(format!("tests/in/{}{}", name, ".glsl"))
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -287,7 +287,8 @@ fn convert_glsl(
},
)
.unwrap();
- check_targets(&module, name, targets);
+ //TODO
+ //check_targets(&module, name, targets);
}
#[cfg(feature = "glsl-in")]
|
[glsl-out]: bake frequently used expressions
Uses the results of analysis to bake frequently used expressions and avoid exponential explosions when writing
|
Will need to be rebased on #472 when merged
|
2021-02-27T10:45:14Z
|
0.3
|
2021-03-03T21:57:33Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"convert_wgsl_texture_array",
"convert_wgsl_empty",
"convert_wgsl_shadow",
"convert_wgsl_quad",
"convert_wgsl_boids",
"convert_wgsl_skybox",
"convert_wgsl_collatz",
"convert_spv_shadow"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"arena::tests::fetch_or_append_unique",
"back::spv::writer::test_writer_generate_id",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::lex::tests::lex_tokens",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::spv::test::parse",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_statement",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_standard_fun",
"proc::analyzer::uniform_control_flow",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::control_flow",
"function_without_identifier",
"parse_glsl",
"convert_glsl_quad"
] |
[] |
[] |
gfx-rs/naga
| 429
|
gfx-rs__naga-429
|
[
"362"
] |
708751a8053019cb737ec256dd143f10c4370db9
|
diff --git a/src/front/glsl/ast.rs b/src/front/glsl/ast.rs
--- a/src/front/glsl/ast.rs
+++ b/src/front/glsl/ast.rs
@@ -245,3 +245,9 @@ pub enum StorageQualifier {
StorageClass(StorageClass),
Const,
}
+
+#[derive(Debug, Clone)]
+pub enum StructLayout {
+ Binding(Binding),
+ PushConstant,
+}
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -109,7 +109,7 @@ pomelo! {
%type declaration Option<VarDeclaration>;
%type init_declarator_list VarDeclaration;
%type single_declaration VarDeclaration;
- %type layout_qualifier Binding;
+ %type layout_qualifier StructLayout;
%type layout_qualifier_id_list Vec<(String, u32)>;
%type layout_qualifier_id (String, u32);
%type type_qualifier Vec<TypeQualifier>;
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -588,14 +588,16 @@ pomelo! {
layout_qualifier ::= Layout LeftParen layout_qualifier_id_list(l) RightParen {
if let Some(&(_, loc)) = l.iter().find(|&q| q.0.as_str() == "location") {
- Binding::Location(loc)
+ StructLayout::Binding(Binding::Location(loc))
} else if let Some(&(_, binding)) = l.iter().find(|&q| q.0.as_str() == "binding") {
let group = if let Some(&(_, set)) = l.iter().find(|&q| q.0.as_str() == "set") {
set
} else {
0
};
- Binding::Resource{ group, binding }
+ StructLayout::Binding(Binding::Resource{ group, binding })
+ } else if l.iter().any(|q| q.0.as_str() == "push_constant") {
+ StructLayout::PushConstant
} else {
return Err(ErrorKind::NotImplemented("unsupported layout qualifier(s)"));
}
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -630,7 +632,10 @@ pomelo! {
TypeQualifier::StorageQualifier(s)
}
single_type_qualifier ::= layout_qualifier(l) {
- TypeQualifier::Binding(l)
+ match l {
+ StructLayout::Binding(b) => TypeQualifier::Binding(b),
+ StructLayout::PushConstant => TypeQualifier::StorageQualifier(StorageQualifier::StorageClass(StorageClass::PushConstant)),
+ }
}
// single_type_qualifier ::= precision_qualifier;
single_type_qualifier ::= interpolation_qualifier(i) {
diff --git a/src/front/wgsl/conv.rs b/src/front/wgsl/conv.rs
--- a/src/front/wgsl/conv.rs
+++ b/src/front/wgsl/conv.rs
@@ -7,6 +7,7 @@ pub fn map_storage_class(word: &str) -> Result<crate::StorageClass, Error<'_>> {
"private" => Ok(crate::StorageClass::Private),
"uniform" => Ok(crate::StorageClass::Uniform),
"storage" => Ok(crate::StorageClass::Storage),
+ "push_constant" => Ok(crate::StorageClass::PushConstant),
_ => Err(Error::UnknownStorageClass(word)),
}
}
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -465,11 +465,7 @@ impl Validator {
(crate::StorageAccess::empty(), TypeFlags::empty())
}
crate::StorageClass::PushConstant => {
- //TODO
- return Err(GlobalVariableError::InvalidStorageAccess {
- allowed: crate::StorageAccess::empty(),
- seen: crate::StorageAccess::empty(),
- });
+ (crate::StorageAccess::LOAD, TypeFlags::HOST_SHARED)
}
};
|
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -188,3 +188,9 @@ fn convert_wgsl_collatz() {
fn convert_wgsl_shadow() {
convert_wgsl("shadow", Language::METAL | Language::SPIRV);
}
+
+#[cfg(feature = "wgsl-in")]
+#[test]
+fn convert_wgsl_texture_array() {
+ convert_wgsl("texture-array", Language::SPIRV);
+}
diff --git /dev/null b/tests/snapshots/in/texture-array.param.ron
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/in/texture-array.param.ron
@@ -0,0 +1,9 @@
+(
+ spv_flow_dump_prefix: "",
+ spv_capabilities: [ Shader ],
+ mtl_bindings: {
+ (stage: Fragment, group: 0, binding: 0): (texture: Some(0)),
+ (stage: Fragment, group: 0, binding: 1): (texture: Some(1)),
+ (stage: Fragment, group: 0, binding: 2): (sampler: Some(0)),
+ }
+)
diff --git /dev/null b/tests/snapshots/in/texture-array.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/in/texture-array.wgsl
@@ -0,0 +1,21 @@
+[[location(0)]] var<in> tex_coord: vec2<f32>;
+[[group(0), binding(0)]] var texture0: texture_2d<f32>;
+[[group(0), binding(1)]] var texture1: texture_2d<f32>;
+[[group(0), binding(2)]] var sampler: sampler;
+
+[[block]]
+struct PushConstants {
+ index: u32;
+};
+var<push_constant> pc: PushConstants;
+
+[[location(1)]] var<out> color: vec4<f32>;
+
+[[stage(fragment)]]
+fn main() {
+ if (pc.index == 0) {
+ color = textureSample(texture0, sampler, tex_coord);
+ } else {
+ color = textureSample(texture1, sampler, tex_coord);
+ }
+}
diff --git /dev/null b/tests/snapshots/snapshots__texture-array.spvasm.snap
new file mode 100644
--- /dev/null
+++ b/tests/snapshots/snapshots__texture-array.spvasm.snap
@@ -0,0 +1,75 @@
+---
+source: tests/snapshots.rs
+expression: dis
+---
+; SPIR-V
+; Version: 1.0
+; Generator: rspirv
+; Bound: 46
+OpCapability Shader
+%1 = OpExtInstImport "GLSL.std.450"
+OpMemoryModel Logical GLSL450
+OpEntryPoint Fragment %5 "main" %35 %23
+OpExecutionMode %5 OriginUpperLeft
+OpDecorate %12 Block
+OpMemberDecorate %12 0 Offset 0
+OpDecorate %23 Location 1
+OpDecorate %26 DescriptorSet 0
+OpDecorate %26 Binding 0
+OpDecorate %31 DescriptorSet 0
+OpDecorate %31 Binding 2
+OpDecorate %35 Location 0
+OpDecorate %40 DescriptorSet 0
+OpDecorate %40 Binding 1
+%0 = OpTypeVoid
+%4 = OpTypeInt 32 1
+%3 = OpConstant %4 0
+%6 = OpTypeFunction %0
+%8 = OpTypeBool
+%10 = OpTypeInt 32 0
+%12 = OpTypeStruct %10
+%14 = OpTypePointer PushConstant %12
+%13 = OpVariable %14 PushConstant
+%15 = OpTypePointer PushConstant %10
+%16 = OpConstant %4 0
+%22 = OpTypeFloat 32
+%21 = OpTypeVector %22 4
+%24 = OpTypePointer Output %21
+%23 = OpVariable %24 Output
+%25 = OpTypeImage %22 2D 0 0 0 1 Unknown
+%27 = OpTypePointer UniformConstant %25
+%26 = OpVariable %27 UniformConstant
+%29 = OpTypeSampledImage %25
+%30 = OpTypeSampler
+%32 = OpTypePointer UniformConstant %30
+%31 = OpVariable %32 UniformConstant
+%34 = OpTypeVector %22 2
+%36 = OpTypePointer Input %34
+%35 = OpVariable %36 Input
+%40 = OpVariable %27 UniformConstant
+%5 = OpFunction %0 None %6
+%7 = OpLabel
+%11 = OpAccessChain %15 %13 %16
+%17 = OpLoad %10 %11
+%9 = OpIEqual %8 %17 %3
+OpSelectionMerge %18 None
+OpBranchConditional %9 %19 %20
+%19 = OpLabel
+%28 = OpLoad %25 %26
+%33 = OpLoad %30 %31
+%37 = OpLoad %34 %35
+%38 = OpSampledImage %29 %28 %33
+%39 = OpImageSampleImplicitLod %21 %38 %37
+OpStore %23 %39
+OpReturn
+%20 = OpLabel
+%41 = OpLoad %25 %40
+%42 = OpLoad %30 %31
+%43 = OpLoad %34 %35
+%44 = OpSampledImage %29 %41 %42
+%45 = OpImageSampleImplicitLod %21 %44 %43
+OpStore %23 %45
+OpReturn
+%18 = OpLabel
+OpReturn
+OpFunctionEnd
|
Push constants support
These are not a part of WebGPU upstream, but useful for webgpu-native as well as regular SPIR-V related use cases.
See also - https://github.com/gfx-rs/wgpu/issues/1162
|
2021-02-07T10:04:30Z
|
0.3
|
2021-02-07T17:55:53Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"convert_wgsl_texture_array"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"back::spv::layout_tests::test_instruction_add_operands",
"back::spv::layout_tests::test_instruction_add_operand",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout_tests::test_instruction_set_result",
"back::spv::layout_tests::test_instruction_set_type",
"back::spv::layout_tests::test_instruction_set_type_twice",
"back::spv::layout_tests::test_instruction_set_result_twice",
"front::glsl::constants::tests::access",
"back::spv::writer::tests::test_write_physical_layout",
"back::spv::layout_tests::test_logical_layout_in_words",
"back::spv::layout_tests::test_instruction_to_words",
"back::spv::layout_tests::test_physical_layout_in_words",
"back::spv::writer::tests::test_writer_generate_id",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"front::spv::rosetta::simple",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::glsl::lex_tests::tokens",
"front::wgsl::tests::parse_statement",
"front::glsl::preprocess_tests::preprocess",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::constants",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_standard_fun",
"proc::interface::tests::global_use_scan",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_texture_query",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::control_flow",
"parse_glsl",
"convert_wgsl_collatz",
"convert_wgsl_empty",
"convert_wgsl_shadow",
"convert_wgsl_quad",
"convert_wgsl_boids",
"convert_wgsl_skybox"
] |
[] |
[] |
|
gfx-rs/naga
| 421
|
gfx-rs__naga-421
|
[
"420"
] |
f9f41fc9bf27ecca091e492892538afcdacd1419
|
diff --git a/src/arena.rs b/src/arena.rs
--- a/src/arena.rs
+++ b/src/arena.rs
@@ -126,6 +126,16 @@ impl<T> Arena<T> {
})
}
+ /// Returns a iterator over the items stored in this arena,
+ /// returning both the item's handle and a mutable reference to it.
+ pub fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = (Handle<T>, &mut T)> {
+ self.data.iter_mut().enumerate().map(|(i, v)| {
+ let position = i + 1;
+ let index = unsafe { Index::new_unchecked(position as u32) };
+ (Handle::new(index), v)
+ })
+ }
+
/// Adds a new value to the arena, returning a typed handle.
///
/// The value is not linked to any SPIR-V module.
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -979,11 +979,11 @@ impl<'a, W: Write> Writer<'a, W> {
// The indentation is only for readability
write!(self.out, "{}", INDENT.repeat(indent))?;
- match sta {
+ match *sta {
// Blocks are simple we just need to write the block statements between braces
// We could also just print the statements but this is more readable and maps more
// closely to the IR
- Statement::Block(block) => {
+ Statement::Block(ref block) => {
writeln!(self.out, "{{")?;
for sta in block.iter() {
// Increase the indentation to help with readability
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1001,11 +1001,11 @@ impl<'a, W: Write> Writer<'a, W> {
// ```
Statement::If {
condition,
- accept,
- reject,
+ ref accept,
+ ref reject,
} => {
write!(self.out, "if(")?;
- self.write_expr(*condition, ctx)?;
+ self.write_expr(condition, ctx)?;
writeln!(self.out, ") {{")?;
for sta in accept {
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1044,12 +1044,12 @@ impl<'a, W: Write> Writer<'a, W> {
// so that we don't need to print a `break` for it
Statement::Switch {
selector,
- cases,
- default,
+ ref cases,
+ ref default,
} => {
// Start the switch
write!(self.out, "switch(")?;
- self.write_expr(*selector, ctx)?;
+ self.write_expr(selector, ctx)?;
writeln!(self.out, ") {{")?;
// Write all cases
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1091,7 +1091,10 @@ impl<'a, W: Write> Writer<'a, W> {
// continuing
// }
// ```
- Statement::Loop { body, continuing } => {
+ Statement::Loop {
+ ref body,
+ ref continuing,
+ } => {
writeln!(self.out, "while(true) {{")?;
for sta in body.iter().chain(continuing.iter()) {
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1111,7 +1114,7 @@ impl<'a, W: Write> Writer<'a, W> {
// Write the expression to be returned if needed
if let Some(expr) = value {
write!(self.out, " ")?;
- self.write_expr(*expr, ctx)?;
+ self.write_expr(expr, ctx)?;
}
writeln!(self.out, ";")?;
}
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1121,11 +1124,20 @@ impl<'a, W: Write> Writer<'a, W> {
Statement::Kill => writeln!(self.out, "discard;")?,
// Stores in glsl are just variable assignments written as `pointer = value;`
Statement::Store { pointer, value } => {
- self.write_expr(*pointer, ctx)?;
+ self.write_expr(pointer, ctx)?;
write!(self.out, " = ")?;
- self.write_expr(*value, ctx)?;
+ self.write_expr(value, ctx)?;
writeln!(self.out, ";")?
}
+ // A `Call` is written `name(arguments)` where `arguments` is a comma separated expressions list
+ Statement::Call {
+ function,
+ ref arguments,
+ } => {
+ write!(self.out, "{}(", &self.names[&NameKey::Function(function)])?;
+ self.write_slice(arguments, |this, _, arg| this.write_expr(*arg, ctx))?;
+ write!(self.out, ");")?
+ }
}
Ok(())
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -741,6 +741,15 @@ impl<W: Write> Writer<W> {
self.put_expression(value, context)?;
writeln!(self.out, ";")?;
}
+ crate::Statement::Call {
+ function,
+ ref arguments,
+ } => {
+ let name = &self.names[&NameKey::Function(function)];
+ write!(self.out, "{}", name)?;
+ self.put_call("", arguments, context)?;
+ writeln!(self.out, ";")?;
+ }
}
}
Ok(())
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -181,7 +181,7 @@ pub struct Writer {
debugs: Vec<Instruction>,
annotations: Vec<Instruction>,
flags: WriterFlags,
- void_type: Option<u32>,
+ void_type: u32,
lookup_type: crate::FastHashMap<LookupType, Word>,
lookup_function: crate::FastHashMap<crate::Handle<crate::Function>, Word>,
lookup_function_type: crate::FastHashMap<LookupFunctionType, Word>,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -209,19 +209,19 @@ impl Writer {
Writer {
physical_layout: PhysicalLayout::new(header),
logical_layout: LogicalLayout::default(),
- id_count: 0,
+ id_count: 2, // 0 is void type, 1 is the GLSL ext inst
capabilities,
debugs: vec![],
annotations: vec![],
flags,
- void_type: None,
+ void_type: 0,
lookup_type: crate::FastHashMap::default(),
lookup_function: crate::FastHashMap::default(),
lookup_function_type: crate::FastHashMap::default(),
lookup_constant: crate::FastHashMap::default(),
lookup_global_variable: crate::FastHashMap::default(),
struct_type_handles: crate::FastHashMap::default(),
- gl450_ext_inst_id: 0,
+ gl450_ext_inst_id: 1,
layouter: Layouter::default(),
typifier: Typifier::new(),
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -295,26 +295,6 @@ impl Writer {
})
}
- fn get_function_return_type(
- &mut self,
- ty: Option<crate::Handle<crate::Type>>,
- arena: &crate::Arena<crate::Type>,
- ) -> Result<Word, Error> {
- match ty {
- Some(handle) => self.get_type_id(arena, LookupType::Handle(handle)),
- None => Ok(match self.void_type {
- Some(id) => id,
- None => {
- let id = self.generate_id();
- self.void_type = Some(id);
- super::instructions::instruction_type_void(id)
- .to_words(&mut self.logical_layout.declarations);
- id
- }
- }),
- }
- }
-
fn get_pointer_id(
&mut self,
arena: &crate::Arena<crate::Type>,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -415,8 +395,10 @@ impl Writer {
.insert(handle, LocalVariable { id, instruction });
}
- let return_type_id =
- self.get_function_return_type(ir_function.return_type, &ir_module.types)?;
+ let return_type_id = match ir_function.return_type {
+ Some(handle) => self.get_type_id(&ir_module.types, LookupType::Handle(handle))?,
+ None => self.void_type,
+ };
let mut parameter_type_ids = Vec::with_capacity(ir_function.arguments.len());
for argument in ir_function.arguments.iter() {
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1922,6 +1904,10 @@ impl Writer {
block = Block::new(merge_id);
}
+ crate::Statement::Switch { .. } => {
+ log::error!("unimplemented Switch");
+ return Err(Error::FeatureNotImplemented("switch"));
+ }
crate::Statement::Loop {
ref body,
ref continuing,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2007,9 +1993,33 @@ impl Writer {
pointer_id, value_id, None,
));
}
- _ => {
- log::error!("unimplemented {:?}", statement);
- return Err(Error::FeatureNotImplemented("statement"));
+ crate::Statement::Call {
+ function: local_function,
+ ref arguments,
+ } => {
+ let id = self.generate_id();
+ //TODO: avoid heap allocation
+ let mut argument_ids = vec![];
+
+ for argument in arguments {
+ let arg_id = self.write_expression(
+ ir_module,
+ ir_function,
+ *argument,
+ &mut block,
+ function,
+ )?;
+ argument_ids.push(arg_id);
+ }
+
+ block
+ .body
+ .push(super::instructions::instruction_function_call(
+ self.void_type,
+ id,
+ *self.lookup_function.get(&local_function).unwrap(),
+ argument_ids.as_slice(),
+ ));
}
}
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2030,7 +2040,8 @@ impl Writer {
}
fn write_logical_layout(&mut self, ir_module: &crate::Module) -> Result<(), Error> {
- self.gl450_ext_inst_id = self.generate_id();
+ super::instructions::instruction_type_void(self.void_type)
+ .to_words(&mut self.logical_layout.declarations);
super::instructions::instruction_ext_inst_import(self.gl450_ext_inst_id, "GLSL.std.450")
.to_words(&mut self.logical_layout.ext_inst_imports);
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -57,23 +57,23 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
) -> Result<(), Error> {
self.switch(ModuleState::Function, inst.op)?;
inst.expect(5)?;
- let result_type = self.next()?;
+ let result_type_id = self.next()?;
let fun_id = self.next()?;
let _fun_control = self.next()?;
- let fun_type = self.next()?;
+ let fun_type_id = self.next()?;
let mut fun = {
- let ft = self.lookup_function_type.lookup(fun_type)?;
- if ft.return_type_id != result_type {
- return Err(Error::WrongFunctionResultType(result_type));
+ let ft = self.lookup_function_type.lookup(fun_type_id)?;
+ if ft.return_type_id != result_type_id {
+ return Err(Error::WrongFunctionResultType(result_type_id));
}
crate::Function {
name: self.future_decor.remove(&fun_id).and_then(|dec| dec.name),
arguments: Vec::with_capacity(ft.parameter_type_ids.len()),
- return_type: if self.lookup_void_type.contains(&result_type) {
+ return_type: if self.lookup_void_type == Some(result_type_id) {
None
} else {
- Some(self.lookup_type.lookup(result_type)?.handle)
+ Some(self.lookup_type.lookup(result_type_id)?.handle)
},
global_usage: Vec::new(),
local_variables: Arena::new(),
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -101,7 +101,7 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
if type_id
!= self
.lookup_function_type
- .lookup(fun_type)?
+ .lookup(fun_type_id)?
.parameter_type_ids[i]
{
return Err(Error::WrongFunctionArgumentType(type_id));
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -116,7 +116,6 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
// Read body
let mut flow_graph = FlowGraph::new();
- let base_deferred_call_index = self.deferred_function_calls.len();
// Scan the blocks and add them as nodes
loop {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -268,18 +268,6 @@ struct LookupSampledImage {
image: Handle<crate::Expression>,
sampler: Handle<crate::Expression>,
}
-#[derive(Clone, Debug)]
-enum DeferredSource {
- Undefined,
- EntryPoint(crate::ShaderStage, String),
- Function(Handle<crate::Function>),
-}
-struct DeferredFunctionCall {
- source: DeferredSource,
- expr_handle: Handle<crate::Expression>,
- dst_id: spirv::Word,
- arguments: Vec<Handle<crate::Expression>>,
-}
#[derive(Clone, Debug)]
pub struct Assignment {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -302,7 +290,7 @@ pub struct Parser<I> {
lookup_member_type_id: FastHashMap<(Handle<crate::Type>, MemberIndex), spirv::Word>,
handle_sampling: FastHashMap<Handle<crate::Type>, SamplingFlags>,
lookup_type: FastHashMap<spirv::Word, LookupType>,
- lookup_void_type: FastHashSet<spirv::Word>,
+ lookup_void_type: Option<spirv::Word>,
lookup_storage_buffer_types: FastHashSet<Handle<crate::Type>>,
// Lookup for samplers and sampled images, storing flags on how they are used.
lookup_constant: FastHashMap<spirv::Word, LookupConstant>,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -312,7 +300,9 @@ pub struct Parser<I> {
lookup_function_type: FastHashMap<spirv::Word, LookupFunctionType>,
lookup_function: FastHashMap<spirv::Word, Handle<crate::Function>>,
lookup_entry_point: FastHashMap<spirv::Word, EntryPoint>,
- deferred_function_calls: Vec<DeferredFunctionCall>,
+ //Note: the key here is fully artificial, has nothing to do with the module
+ deferred_function_calls: FastHashMap<Handle<crate::Function>, spirv::Word>,
+ dummy_functions: Arena<crate::Function>,
options: Options,
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -328,7 +318,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
handle_sampling: FastHashMap::default(),
lookup_member_type_id: FastHashMap::default(),
lookup_type: FastHashMap::default(),
- lookup_void_type: FastHashSet::default(),
+ lookup_void_type: None,
lookup_storage_buffer_types: FastHashSet::default(),
lookup_constant: FastHashMap::default(),
lookup_variable: FastHashMap::default(),
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -337,7 +327,8 @@ impl<I: Iterator<Item = u32>> Parser<I> {
lookup_function_type: FastHashMap::default(),
lookup_function: FastHashMap::default(),
lookup_entry_point: FastHashMap::default(),
- deferred_function_calls: Vec::new(),
+ deferred_function_calls: FastHashMap::default(),
+ dummy_functions: Arena::new(),
options: options.clone(),
}
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -510,7 +501,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
const_arena: &Arena<crate::Constant>,
global_arena: &Arena<crate::GlobalVariable>,
) -> Result<ControlFlowNode, Error> {
- let mut assignments = Vec::new();
+ let mut block = Vec::new();
let mut phis = Vec::new();
let mut merge = None;
let terminator = loop {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -782,8 +773,8 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
let base_expr = self.lookup_expression.lookup(pointer_id)?;
let value_expr = self.lookup_expression.lookup(value_id)?;
- assignments.push(Assignment {
- to: base_expr.handle,
+ block.push(crate::Statement::Store {
+ pointer: base_expr.handle,
value: value_expr.handle,
});
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1315,22 +1306,29 @@ impl<I: Iterator<Item = u32>> Parser<I> {
let arg_id = self.next()?;
arguments.push(self.lookup_expression.lookup(arg_id)?.handle);
}
- // will be replaced by the actual expression
- let expr = crate::Expression::FunctionArgument(!0);
- let expr_handle = expressions.append(expr);
- self.deferred_function_calls.push(DeferredFunctionCall {
- source: DeferredSource::Undefined,
- expr_handle,
- dst_id: func_id,
- arguments,
- });
- self.lookup_expression.insert(
- result_id,
- LookupExpression {
- handle: expr_handle,
- type_id: result_type_id,
- },
- );
+
+ // We just need an unique handle here, nothing more.
+ let function = self.dummy_functions.append(crate::Function::default());
+ self.deferred_function_calls.insert(function, func_id);
+
+ if self.lookup_void_type == Some(result_type_id) {
+ block.push(crate::Statement::Call {
+ function,
+ arguments,
+ });
+ } else {
+ let expr_handle = expressions.append(crate::Expression::Call {
+ function,
+ arguments,
+ });
+ self.lookup_expression.insert(
+ result_id,
+ LookupExpression {
+ handle: expr_handle,
+ type_id: result_type_id,
+ },
+ );
+ }
}
Op::ExtInst => {
use crate::MathFunction as Mf;
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1551,14 +1549,6 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
};
- let mut block = Vec::new();
- for assignment in assignments.iter() {
- block.push(crate::Statement::Store {
- pointer: assignment.to,
- value: assignment.value,
- });
- }
-
Ok(ControlFlowNode {
id: block_id,
ty: None,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1610,6 +1600,67 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
}
+ fn patch_function_call_statements(
+ &self,
+ statements: &mut [crate::Statement],
+ ) -> Result<(), Error> {
+ use crate::Statement as S;
+ for statement in statements.iter_mut() {
+ match *statement {
+ S::Block(ref mut block) => {
+ self.patch_function_call_statements(block)?;
+ }
+ S::If {
+ condition: _,
+ ref mut accept,
+ ref mut reject,
+ } => {
+ self.patch_function_call_statements(accept)?;
+ self.patch_function_call_statements(reject)?;
+ }
+ S::Switch {
+ selector: _,
+ ref mut cases,
+ ref mut default,
+ } => {
+ for case in cases.iter_mut() {
+ self.patch_function_call_statements(&mut case.body)?;
+ }
+ self.patch_function_call_statements(default)?;
+ }
+ S::Loop {
+ ref mut body,
+ ref mut continuing,
+ } => {
+ self.patch_function_call_statements(body)?;
+ self.patch_function_call_statements(continuing)?;
+ }
+ S::Break | S::Continue | S::Return { .. } | S::Kill | S::Store { .. } => {}
+ S::Call {
+ ref mut function, ..
+ } => {
+ let fun_id = self.deferred_function_calls[function];
+ *function = *self.lookup_function.lookup(fun_id)?;
+ }
+ }
+ }
+ Ok(())
+ }
+
+ fn patch_function_calls(&self, fun: &mut crate::Function) -> Result<(), Error> {
+ for (_, expr) in fun.expressions.iter_mut() {
+ if let crate::Expression::Call {
+ ref mut function, ..
+ } = *expr
+ {
+ let fun_id = self.deferred_function_calls[function];
+ *function = *self.lookup_function.lookup(fun_id)?;
+ }
+ }
+ self.patch_function_call_statements(&mut fun.body)?;
+ Ok(())
+ }
+
pub fn parse(mut self) -> Result<crate::Module, Error> {
let mut module = {
if self.next()? != spirv::MAGIC_NUMBER {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1680,23 +1731,11 @@ impl<I: Iterator<Item = u32>> Parser<I> {
}
}
- for dfc in self.deferred_function_calls.drain(..) {
- let dst_handle = *self.lookup_function.lookup(dfc.dst_id)?;
- let fun = match dfc.source {
- DeferredSource::Undefined => unreachable!(),
- DeferredSource::Function(fun_handle) => module.functions.get_mut(fun_handle),
- DeferredSource::EntryPoint(stage, name) => {
- &mut module
- .entry_points
- .get_mut(&(stage, name))
- .unwrap()
- .function
- }
- };
- *fun.expressions.get_mut(dfc.expr_handle) = crate::Expression::Call {
- function: dst_handle,
- arguments: dfc.arguments,
- };
+ for (_, func) in module.functions.iter_mut() {
+ self.patch_function_calls(func)?;
+ }
+ for (_, ep) in module.entry_points.iter_mut() {
+ self.patch_function_calls(&mut ep.function)?;
}
if !self.future_decor.is_empty() {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1912,7 +1951,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
self.switch(ModuleState::Type, inst.op)?;
inst.expect(2)?;
let id = self.next()?;
- self.lookup_void_type.insert(id);
+ self.lookup_void_type = Some(id);
Ok(())
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -91,6 +91,8 @@ pub enum Error<'a> {
NotCompositeType(Handle<crate::Type>),
#[error("function redefinition: `{0}`")]
FunctionRedefinition(&'a str),
+ #[error("call to local `{0}(..)` can't be resolved")]
+ UnknownLocalFunction(&'a str),
#[error("other error")]
Other,
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -307,6 +309,8 @@ pub enum Scope {
GeneralExpr,
}
+type LocalFunctionCall = (Handle<crate::Function>, Vec<Handle<crate::Expression>>);
+
struct ParsedVariable<'a> {
name: &'a str,
class: Option<crate::StorageClass>,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -370,6 +374,36 @@ impl Parser {
})
}
+ fn parse_local_function_call<'a>(
+ &mut self,
+ lexer: &mut Lexer<'a>,
+ name: &'a str,
+ mut ctx: ExpressionContext<'a, '_, '_>,
+ ) -> Result<Option<LocalFunctionCall>, Error<'a>> {
+ let fun_handle = match ctx.functions.iter().find(|(_, fun)| match fun.name {
+ Some(ref string) => string == name,
+ None => false,
+ }) {
+ Some((fun_handle, _)) => fun_handle,
+ None => return Ok(None),
+ };
+
+ let mut arguments = Vec::new();
+ lexer.expect(Token::Paren('('))?;
+ if !lexer.skip(Token::Paren(')')) {
+ loop {
+ let arg = self.parse_general_expression(lexer, ctx.reborrow())?;
+ arguments.push(arg);
+ match lexer.next() {
+ Token::Paren(')') => break,
+ Token::Separator(',') => (),
+ other => return Err(Error::Unexpected(other, "argument list separator")),
+ }
+ }
+ }
+ Ok(Some((fun_handle, arguments)))
+ }
+
fn parse_function_call_inner<'a>(
&mut self,
lexer: &mut Lexer<'a>,
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -650,39 +684,12 @@ impl Parser {
query: crate::ImageQuery::NumSamples,
})
}
- _ => {
- match ctx.functions.iter().find(|(_, fun)| match fun.name {
- Some(ref string) => string == name,
- None => false,
- }) {
- Some((function, _)) => {
- let mut arguments = Vec::new();
- lexer.expect(Token::Paren('('))?;
- if !lexer.skip(Token::Paren(')')) {
- loop {
- let arg =
- self.parse_general_expression(lexer, ctx.reborrow())?;
- arguments.push(arg);
- match lexer.next() {
- Token::Paren(')') => break,
- Token::Separator(',') => (),
- other => {
- return Err(Error::Unexpected(
- other,
- "argument list separator",
- ))
- }
- }
- }
- }
- Some(crate::Expression::Call {
- function,
- arguments,
- })
- }
- None => None,
- }
- }
+ _ => self.parse_local_function_call(lexer, name, ctx)?.map(
+ |(function, arguments)| crate::Expression::Call {
+ function,
+ arguments,
+ },
+ ),
}
})
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1748,8 +1755,8 @@ impl Parser {
"break" => Some(crate::Statement::Break),
"continue" => Some(crate::Statement::Continue),
"discard" => Some(crate::Statement::Kill),
+ // assignment or a function call
ident => {
- // assignment
if let Some(&var_expr) = context.lookup_ident.get(ident) {
let left = self.parse_postfix(lexer, context.as_expression(), var_expr)?;
lexer.expect(Token::Operation('='))?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1759,14 +1766,15 @@ impl Parser {
pointer: left,
value,
})
- } else if let Some(expr) =
- self.parse_function_call_inner(lexer, ident, context.as_expression())?
- {
- context.expressions.append(expr);
- lexer.expect(Token::Separator(';'))?;
- None
} else {
- return Err(Error::UnknownIdent(ident));
+ let (function, arguments) = self
+ .parse_local_function_call(lexer, ident, context.as_expression())?
+ .ok_or(Error::UnknownLocalFunction(ident))?;
+ lexer.expect(Token::Separator(';'))?;
+ Some(crate::Statement::Call {
+ function,
+ arguments,
+ })
}
}
};
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -802,6 +802,11 @@ pub enum Statement {
pointer: Handle<Expression>,
value: Handle<Expression>,
},
+ /// Calls a function with no return value.
+ Call {
+ function: Handle<Function>,
+ arguments: Vec<Handle<Expression>>,
+ },
}
/// A function argument.
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -816,7 +821,7 @@ pub struct FunctionArgument {
}
/// A function defined in the module.
-#[derive(Debug)]
+#[derive(Debug, Default)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
pub struct Function {
diff --git a/src/proc/interface.rs b/src/proc/interface.rs
--- a/src/proc/interface.rs
+++ b/src/proc/interface.rs
@@ -203,6 +203,15 @@ where
self.visitor.visit_lhs_expr(&self.expressions[left]);
self.traverse_expr(value);
}
+ S::Call {
+ function,
+ ref arguments,
+ } => {
+ for &argument in arguments {
+ self.traverse_expr(argument);
+ }
+ self.visitor.visit_fun(function);
+ }
}
}
}
diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs
--- a/src/proc/terminator.rs
+++ b/src/proc/terminator.rs
@@ -35,6 +35,7 @@ pub fn ensure_block_returns(block: &mut crate::Block) {
| Some(&mut crate::Statement::Kill) => (),
Some(&mut crate::Statement::Loop { .. })
| Some(&mut crate::Statement::Store { .. })
+ | Some(&mut crate::Statement::Call { .. })
| None => block.push(crate::Statement::Return { value: None }),
}
}
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -48,6 +48,8 @@ pub enum ResolveError {
InvalidAccessIndex,
#[error("Function {name} not defined")]
FunctionNotDefined { name: String },
+ #[error("Function without return type")]
+ FunctionReturnsVoid,
#[error("Type is not found in the given immutable arena")]
TypeNotFound,
#[error("Incompatible operand: {op} {operand}")]
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -466,13 +468,10 @@ impl Typifier {
function,
arguments: _,
} => {
- match ctx.functions[function].return_type {
- Some(ty) => Resolution::Handle(ty),
- // return a type that can't ever be returned...
- // We don't have `void` in the IR, but we have to return something here.
- // This is also not a place to validate anything.
- None => Resolution::Value(crate::TypeInner::Sampler { comparison: false }),
- }
+ let ty = ctx.functions[function]
+ .return_type
+ .ok_or(ResolveError::FunctionReturnsVoid)?;
+ Resolution::Handle(ty)
}
crate::Expression::ArrayLength(_) => Resolution::Value(crate::TypeInner::Scalar {
kind: crate::ScalarKind::Uint,
|
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2113,9 +2124,9 @@ mod tests {
fn test_writer_generate_id() {
let mut writer = create_writer();
- assert_eq!(writer.id_count, 0);
+ assert_eq!(writer.id_count, 2);
writer.generate_id();
- assert_eq!(writer.id_count, 1);
+ assert_eq!(writer.id_count, 3);
}
#[test]
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2123,7 +2134,7 @@ mod tests {
let mut writer = create_writer();
assert_eq!(writer.physical_layout.bound, 0);
writer.write_physical_layout();
- assert_eq!(writer.physical_layout.bound, 1);
+ assert_eq!(writer.physical_layout.bound, 3);
}
fn create_writer() -> Writer {
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -156,39 +155,29 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
// done
fun.fill_global_use(&module.global_variables);
- let source = match self.lookup_entry_point.remove(&fun_id) {
+ let dump_suffix = match self.lookup_entry_point.remove(&fun_id) {
Some(ep) => {
+ let dump_name = format!("flow.{:?}-{}.dot", ep.stage, ep.name);
module.entry_points.insert(
- (ep.stage, ep.name.clone()),
+ (ep.stage, ep.name),
crate::EntryPoint {
early_depth_test: ep.early_depth_test,
workgroup_size: ep.workgroup_size,
function: fun,
},
);
- DeferredSource::EntryPoint(ep.stage, ep.name)
+ dump_name
}
None => {
let handle = module.functions.append(fun);
self.lookup_function.insert(fun_id, handle);
- DeferredSource::Function(handle)
+ format!("flow.Fun-{}.dot", handle.index())
}
};
- for dfc in self.deferred_function_calls[base_deferred_call_index..].iter_mut() {
- dfc.source = source.clone();
- }
-
if let Some(ref prefix) = self.options.flow_graph_dump_prefix {
let dump = flow_graph.to_graphviz().unwrap_or_default();
- let suffix = match source {
- DeferredSource::Undefined => unreachable!(),
- DeferredSource::EntryPoint(stage, ref name) => {
- format!("flow.{:?}-{}.dot", stage, name)
- }
- DeferredSource::Function(handle) => format!("flow.Fun-{}.dot", handle.index()),
- };
- let _ = std::fs::write(prefix.join(suffix), dump);
+ let _ = std::fs::write(prefix.join(dump_suffix), dump);
}
self.lookup_expression.clear();
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -85,6 +85,14 @@ fn parse_statement() {
",
)
.unwrap();
+
+ parse_str(
+ "
+ fn foo() {}
+ fn bar() { foo(); }
+ ",
+ )
+ .unwrap();
}
#[test]
diff --git a/tests/snapshots/in/collatz.wgsl b/tests/snapshots/in/collatz.wgsl
--- a/tests/snapshots/in/collatz.wgsl
+++ b/tests/snapshots/in/collatz.wgsl
@@ -15,7 +15,7 @@ var<storage> v_indices: [[access(read_write)]] PrimeIndices;
// And repeat this process for each new n, you will always eventually reach 1.
// Though the conjecture has not been proven, no counterexample has ever been found.
// This function returns how many times this recurrence needs to be applied to reach 1.
-fn collatz_iterations(n_base: u32) -> u32{
+fn collatz_iterations(n_base: u32) -> u32 {
var n: u32 = n_base;
var i: u32 = 0u;
loop {
diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/snapshots/snapshots__boids.spvasm.snap
--- a/tests/snapshots/snapshots__boids.spvasm.snap
+++ b/tests/snapshots/snapshots__boids.spvasm.snap
@@ -32,124 +32,124 @@ OpDecorate %122 DescriptorSet 0
OpDecorate %122 Binding 0
OpDecorate %274 DescriptorSet 0
OpDecorate %274 Binding 2
-%3 = OpTypeInt 32 1
-%2 = OpConstant %3 1500
-%5 = OpTypeFloat 32
-%4 = OpConstant %5 0.0
-%6 = OpConstant %3 0
-%8 = OpTypeInt 32 0
-%7 = OpConstant %8 0
-%9 = OpConstant %3 1
-%10 = OpConstant %8 1
-%11 = OpConstant %5 1.0
-%12 = OpConstant %5 0.1
-%13 = OpConstant %5 -1.0
-%15 = OpTypeVector %5 2
-%16 = OpTypePointer Function %15
-%22 = OpTypePointer Function %3
-%27 = OpTypePointer Function %8
-%28 = OpTypeVoid
-%30 = OpTypeFunction %28
+%0 = OpTypeVoid
+%4 = OpTypeInt 32 1
+%3 = OpConstant %4 1500
+%6 = OpTypeFloat 32
+%5 = OpConstant %6 0.0
+%7 = OpConstant %4 0
+%9 = OpTypeInt 32 0
+%8 = OpConstant %9 0
+%10 = OpConstant %4 1
+%11 = OpConstant %9 1
+%12 = OpConstant %6 1.0
+%13 = OpConstant %6 0.1
+%14 = OpConstant %6 -1.0
+%16 = OpTypeVector %6 2
+%17 = OpTypePointer Function %16
+%23 = OpTypePointer Function %4
+%28 = OpTypePointer Function %9
+%30 = OpTypeFunction %0
%32 = OpTypeBool
-%35 = OpTypeVector %8 3
+%35 = OpTypeVector %9 3
%37 = OpTypePointer Input %35
%36 = OpVariable %37 Input
-%38 = OpTypePointer Input %8
-%39 = OpConstant %3 0
-%45 = OpTypeStruct %15 %15
+%38 = OpTypePointer Input %9
+%39 = OpConstant %4 0
+%45 = OpTypeStruct %16 %16
%47 = OpTypeRuntimeArray %45
%49 = OpTypeStruct %47
%51 = OpTypePointer Uniform %49
%50 = OpVariable %51 Uniform
%52 = OpTypePointer Uniform %47
-%53 = OpConstant %3 0
-%55 = OpTypePointer Input %8
-%56 = OpConstant %3 0
+%53 = OpConstant %4 0
+%55 = OpTypePointer Input %9
+%56 = OpConstant %4 0
%58 = OpTypePointer Uniform %45
-%59 = OpTypePointer Uniform %15
-%60 = OpConstant %3 0
+%59 = OpTypePointer Uniform %16
+%60 = OpConstant %4 0
%65 = OpTypePointer Uniform %47
-%66 = OpConstant %3 0
-%68 = OpTypePointer Input %8
-%69 = OpConstant %3 0
+%66 = OpConstant %4 0
+%68 = OpTypePointer Input %9
+%69 = OpConstant %4 0
%71 = OpTypePointer Uniform %45
-%72 = OpTypePointer Uniform %15
-%73 = OpConstant %3 1
-%90 = OpTypePointer Input %8
-%91 = OpConstant %3 0
+%72 = OpTypePointer Uniform %16
+%73 = OpConstant %4 1
+%90 = OpTypePointer Input %9
+%91 = OpConstant %4 0
%99 = OpTypePointer Uniform %47
-%100 = OpConstant %3 0
+%100 = OpConstant %4 0
%102 = OpTypePointer Uniform %45
-%103 = OpTypePointer Uniform %15
-%104 = OpConstant %3 0
+%103 = OpTypePointer Uniform %16
+%104 = OpConstant %4 0
%109 = OpTypePointer Uniform %47
-%110 = OpConstant %3 0
+%110 = OpConstant %4 0
%112 = OpTypePointer Uniform %45
-%113 = OpTypePointer Uniform %15
-%114 = OpConstant %3 1
-%121 = OpTypeStruct %5 %5 %5 %5 %5 %5 %5
+%113 = OpTypePointer Uniform %16
+%114 = OpConstant %4 1
+%121 = OpTypeStruct %6 %6 %6 %6 %6 %6 %6
%123 = OpTypePointer Uniform %121
%122 = OpVariable %123 Uniform
-%124 = OpTypePointer Uniform %5
-%125 = OpConstant %3 1
-%140 = OpTypePointer Uniform %5
-%141 = OpConstant %3 2
-%156 = OpTypePointer Uniform %5
-%157 = OpConstant %3 3
-%198 = OpTypePointer Uniform %5
-%199 = OpConstant %3 4
-%204 = OpTypePointer Uniform %5
-%205 = OpConstant %3 5
-%210 = OpTypePointer Uniform %5
-%211 = OpConstant %3 6
-%224 = OpTypePointer Uniform %5
-%225 = OpConstant %3 0
-%229 = OpTypePointer Function %5
-%230 = OpConstant %3 0
-%236 = OpTypePointer Function %5
-%237 = OpConstant %3 0
-%240 = OpTypePointer Function %5
-%241 = OpConstant %3 0
-%247 = OpTypePointer Function %5
-%248 = OpConstant %3 0
-%251 = OpTypePointer Function %5
-%252 = OpConstant %3 1
-%258 = OpTypePointer Function %5
-%259 = OpConstant %3 1
-%262 = OpTypePointer Function %5
-%263 = OpConstant %3 1
-%269 = OpTypePointer Function %5
-%270 = OpConstant %3 1
+%124 = OpTypePointer Uniform %6
+%125 = OpConstant %4 1
+%140 = OpTypePointer Uniform %6
+%141 = OpConstant %4 2
+%156 = OpTypePointer Uniform %6
+%157 = OpConstant %4 3
+%198 = OpTypePointer Uniform %6
+%199 = OpConstant %4 4
+%204 = OpTypePointer Uniform %6
+%205 = OpConstant %4 5
+%210 = OpTypePointer Uniform %6
+%211 = OpConstant %4 6
+%224 = OpTypePointer Uniform %6
+%225 = OpConstant %4 0
+%229 = OpTypePointer Function %6
+%230 = OpConstant %4 0
+%236 = OpTypePointer Function %6
+%237 = OpConstant %4 0
+%240 = OpTypePointer Function %6
+%241 = OpConstant %4 0
+%247 = OpTypePointer Function %6
+%248 = OpConstant %4 0
+%251 = OpTypePointer Function %6
+%252 = OpConstant %4 1
+%258 = OpTypePointer Function %6
+%259 = OpConstant %4 1
+%262 = OpTypePointer Function %6
+%263 = OpConstant %4 1
+%269 = OpTypePointer Function %6
+%270 = OpConstant %4 1
%274 = OpVariable %51 Uniform
%275 = OpTypePointer Uniform %47
-%276 = OpConstant %3 0
-%278 = OpTypePointer Input %8
-%279 = OpConstant %3 0
+%276 = OpConstant %4 0
+%278 = OpTypePointer Input %9
+%279 = OpConstant %4 0
%281 = OpTypePointer Uniform %45
-%282 = OpTypePointer Uniform %15
-%283 = OpConstant %3 0
+%282 = OpTypePointer Uniform %16
+%283 = OpConstant %4 0
%288 = OpTypePointer Uniform %47
-%289 = OpConstant %3 0
-%291 = OpTypePointer Input %8
-%292 = OpConstant %3 0
+%289 = OpConstant %4 0
+%291 = OpTypePointer Input %9
+%292 = OpConstant %4 0
%294 = OpTypePointer Uniform %45
-%295 = OpTypePointer Uniform %15
-%296 = OpConstant %3 1
-%29 = OpFunction %28 None %30
+%295 = OpTypePointer Uniform %16
+%296 = OpConstant %4 1
+%29 = OpFunction %0 None %30
%31 = OpLabel
-%26 = OpVariable %27 Function %7
-%23 = OpVariable %22 Function %6
-%19 = OpVariable %16 Function
-%14 = OpVariable %16 Function
-%24 = OpVariable %16 Function
-%20 = OpVariable %16 Function
-%17 = OpVariable %16 Function
-%25 = OpVariable %16 Function
-%21 = OpVariable %22 Function %6
-%18 = OpVariable %16 Function
+%27 = OpVariable %28 Function %8
+%24 = OpVariable %23 Function %7
+%20 = OpVariable %17 Function
+%15 = OpVariable %17 Function
+%25 = OpVariable %17 Function
+%21 = OpVariable %17 Function
+%18 = OpVariable %17 Function
+%26 = OpVariable %17 Function
+%22 = OpVariable %23 Function %7
+%19 = OpVariable %17 Function
%34 = OpAccessChain %38 %36 %39
-%40 = OpLoad %8 %34
-%33 = OpUGreaterThanEqual %32 %40 %2
+%40 = OpLoad %9 %34
+%33 = OpUGreaterThanEqual %32 %40 %3
OpSelectionMerge %41 None
OpBranchConditional %33 %42 %43
%42 = OpLabel
diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/snapshots/snapshots__boids.spvasm.snap
--- a/tests/snapshots/snapshots__boids.spvasm.snap
+++ b/tests/snapshots/snapshots__boids.spvasm.snap
@@ -159,31 +159,31 @@ OpBranch %41
%41 = OpLabel
%48 = OpAccessChain %52 %50 %53
%54 = OpAccessChain %55 %36 %56
-%57 = OpLoad %8 %54
+%57 = OpLoad %9 %54
%46 = OpAccessChain %58 %48 %57
%44 = OpAccessChain %59 %46 %60
-%61 = OpLoad %15 %44
-OpStore %14 %61
+%61 = OpLoad %16 %44
+OpStore %15 %61
%64 = OpAccessChain %65 %50 %66
%67 = OpAccessChain %68 %36 %69
-%70 = OpLoad %8 %67
+%70 = OpLoad %9 %67
%63 = OpAccessChain %71 %64 %70
%62 = OpAccessChain %72 %63 %73
-%74 = OpLoad %15 %62
-OpStore %17 %74
-%75 = OpCompositeConstruct %15 %4 %4
-OpStore %18 %75
-%76 = OpCompositeConstruct %15 %4 %4
-OpStore %19 %76
-%77 = OpCompositeConstruct %15 %4 %4
-OpStore %20 %77
+%74 = OpLoad %16 %62
+OpStore %18 %74
+%75 = OpCompositeConstruct %16 %5 %5
+OpStore %19 %75
+%76 = OpCompositeConstruct %16 %5 %5
+OpStore %20 %76
+%77 = OpCompositeConstruct %16 %5 %5
+OpStore %21 %77
OpBranch %78
%78 = OpLabel
OpLoopMerge %79 %81 None
OpBranch %80
%80 = OpLabel
-%83 = OpLoad %8 %26
-%82 = OpUGreaterThanEqual %32 %83 %2
+%83 = OpLoad %9 %27
+%82 = OpUGreaterThanEqual %32 %83 %3
OpSelectionMerge %84 None
OpBranchConditional %82 %85 %86
%85 = OpLabel
diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/snapshots/snapshots__boids.spvasm.snap
--- a/tests/snapshots/snapshots__boids.spvasm.snap
+++ b/tests/snapshots/snapshots__boids.spvasm.snap
@@ -191,9 +191,9 @@ OpBranch %79
%86 = OpLabel
OpBranch %84
%84 = OpLabel
-%88 = OpLoad %8 %26
+%88 = OpLoad %9 %27
%89 = OpAccessChain %90 %36 %91
-%92 = OpLoad %8 %89
+%92 = OpLoad %9 %89
%87 = OpIEqual %32 %88 %92
OpSelectionMerge %93 None
OpBranchConditional %87 %94 %95
diff --git a/tests/snapshots/snapshots__boids.spvasm.snap b/tests/snapshots/snapshots__boids.spvasm.snap
--- a/tests/snapshots/snapshots__boids.spvasm.snap
+++ b/tests/snapshots/snapshots__boids.spvasm.snap
@@ -203,207 +203,207 @@ OpBranch %81
OpBranch %93
%93 = OpLabel
%98 = OpAccessChain %99 %50 %100
-%101 = OpLoad %8 %26
+%101 = OpLoad %9 %27
%97 = OpAccessChain %102 %98 %101
%96 = OpAccessChain %103 %97 %104
-%105 = OpLoad %15 %96
-OpStore %24 %105
+%105 = OpLoad %16 %96
+OpStore %25 %105
%108 = OpAccessChain %109 %50 %110
-%111 = OpLoad %8 %26
+%111 = OpLoad %9 %27
%107 = OpAccessChain %112 %108 %111
%106 = OpAccessChain %113 %107 %114
-%115 = OpLoad %15 %106
-OpStore %25 %115
-%117 = OpLoad %15 %24
-%118 = OpLoad %15 %14
-%119 = OpExtInst %5 %1 Distance %117 %118
+%115 = OpLoad %16 %106
+OpStore %26 %115
+%117 = OpLoad %16 %25
+%118 = OpLoad %16 %15
+%119 = OpExtInst %6 %1 Distance %117 %118
%120 = OpAccessChain %124 %122 %125
-%126 = OpLoad %5 %120
+%126 = OpLoad %6 %120
%116 = OpFOrdLessThan %32 %119 %126
OpSelectionMerge %127 None
OpBranchConditional %116 %128 %129
%128 = OpLabel
-%131 = OpLoad %15 %18
-%132 = OpLoad %15 %24
-%130 = OpFAdd %15 %131 %132
-OpStore %18 %130
-%134 = OpLoad %3 %21
-%133 = OpIAdd %3 %134 %9
-OpStore %21 %133
+%131 = OpLoad %16 %19
+%132 = OpLoad %16 %25
+%130 = OpFAdd %16 %131 %132
+OpStore %19 %130
+%134 = OpLoad %4 %22
+%133 = OpIAdd %4 %134 %10
+OpStore %22 %133
OpBranch %127
%129 = OpLabel
OpBranch %127
%127 = OpLabel
-%136 = OpLoad %15 %24
-%137 = OpLoad %15 %14
-%138 = OpExtInst %5 %1 Distance %136 %137
+%136 = OpLoad %16 %25
+%137 = OpLoad %16 %15
+%138 = OpExtInst %6 %1 Distance %136 %137
%139 = OpAccessChain %140 %122 %141
-%142 = OpLoad %5 %139
+%142 = OpLoad %6 %139
%135 = OpFOrdLessThan %32 %138 %142
OpSelectionMerge %143 None
OpBranchConditional %135 %144 %145
%144 = OpLabel
-%147 = OpLoad %15 %20
-%149 = OpLoad %15 %24
-%150 = OpLoad %15 %14
-%148 = OpFSub %15 %149 %150
-%146 = OpFSub %15 %147 %148
-OpStore %20 %146
+%147 = OpLoad %16 %21
+%149 = OpLoad %16 %25
+%150 = OpLoad %16 %15
+%148 = OpFSub %16 %149 %150
+%146 = OpFSub %16 %147 %148
+OpStore %21 %146
OpBranch %143
%145 = OpLabel
OpBranch %143
%143 = OpLabel
-%152 = OpLoad %15 %24
-%153 = OpLoad %15 %14
-%154 = OpExtInst %5 %1 Distance %152 %153
+%152 = OpLoad %16 %25
+%153 = OpLoad %16 %15
+%154 = OpExtInst %6 %1 Distance %152 %153
%155 = OpAccessChain %156 %122 %157
-%158 = OpLoad %5 %155
+%158 = OpLoad %6 %155
%151 = OpFOrdLessThan %32 %154 %158
OpSelectionMerge %159 None
OpBranchConditional %151 %160 %161
%160 = OpLabel
-%163 = OpLoad %15 %19
-%164 = OpLoad %15 %25
-%162 = OpFAdd %15 %163 %164
-OpStore %19 %162
-%166 = OpLoad %3 %23
-%165 = OpIAdd %3 %166 %9
-OpStore %23 %165
+%163 = OpLoad %16 %20
+%164 = OpLoad %16 %26
+%162 = OpFAdd %16 %163 %164
+OpStore %20 %162
+%166 = OpLoad %4 %24
+%165 = OpIAdd %4 %166 %10
+OpStore %24 %165
OpBranch %159
%161 = OpLabel
OpBranch %159
%159 = OpLabel
OpBranch %81
%81 = OpLabel
-%168 = OpLoad %8 %26
-%167 = OpIAdd %8 %168 %10
-OpStore %26 %167
+%168 = OpLoad %9 %27
+%167 = OpIAdd %9 %168 %11
+OpStore %27 %167
OpBranch %78
%79 = OpLabel
-%170 = OpLoad %3 %21
-%169 = OpSGreaterThan %32 %170 %6
+%170 = OpLoad %4 %22
+%169 = OpSGreaterThan %32 %170 %7
OpSelectionMerge %171 None
OpBranchConditional %169 %172 %173
%172 = OpLabel
-%176 = OpLoad %15 %18
-%178 = OpLoad %3 %21
-%179 = OpConvertSToF %5 %178
-%177 = OpFDiv %5 %11 %179
-%175 = OpVectorTimesScalar %15 %176 %177
-%180 = OpLoad %15 %14
-%174 = OpFSub %15 %175 %180
-OpStore %18 %174
+%176 = OpLoad %16 %19
+%178 = OpLoad %4 %22
+%179 = OpConvertSToF %6 %178
+%177 = OpFDiv %6 %12 %179
+%175 = OpVectorTimesScalar %16 %176 %177
+%180 = OpLoad %16 %15
+%174 = OpFSub %16 %175 %180
+OpStore %19 %174
OpBranch %171
%173 = OpLabel
OpBranch %171
%171 = OpLabel
-%182 = OpLoad %3 %23
-%181 = OpSGreaterThan %32 %182 %6
+%182 = OpLoad %4 %24
+%181 = OpSGreaterThan %32 %182 %7
OpSelectionMerge %183 None
OpBranchConditional %181 %184 %185
%184 = OpLabel
-%187 = OpLoad %15 %19
-%189 = OpLoad %3 %23
-%190 = OpConvertSToF %5 %189
-%188 = OpFDiv %5 %11 %190
-%186 = OpVectorTimesScalar %15 %187 %188
-OpStore %19 %186
+%187 = OpLoad %16 %20
+%189 = OpLoad %4 %24
+%190 = OpConvertSToF %6 %189
+%188 = OpFDiv %6 %12 %190
+%186 = OpVectorTimesScalar %16 %187 %188
+OpStore %20 %186
OpBranch %183
%185 = OpLabel
OpBranch %183
%183 = OpLabel
-%194 = OpLoad %15 %17
-%196 = OpLoad %15 %18
+%194 = OpLoad %16 %18
+%196 = OpLoad %16 %19
%197 = OpAccessChain %198 %122 %199
-%200 = OpLoad %5 %197
-%195 = OpVectorTimesScalar %15 %196 %200
-%193 = OpFAdd %15 %194 %195
-%202 = OpLoad %15 %20
+%200 = OpLoad %6 %197
+%195 = OpVectorTimesScalar %16 %196 %200
+%193 = OpFAdd %16 %194 %195
+%202 = OpLoad %16 %21
%203 = OpAccessChain %204 %122 %205
-%206 = OpLoad %5 %203
-%201 = OpVectorTimesScalar %15 %202 %206
-%192 = OpFAdd %15 %193 %201
-%208 = OpLoad %15 %19
+%206 = OpLoad %6 %203
+%201 = OpVectorTimesScalar %16 %202 %206
+%192 = OpFAdd %16 %193 %201
+%208 = OpLoad %16 %20
%209 = OpAccessChain %210 %122 %211
-%212 = OpLoad %5 %209
-%207 = OpVectorTimesScalar %15 %208 %212
-%191 = OpFAdd %15 %192 %207
-OpStore %17 %191
-%214 = OpLoad %15 %17
-%215 = OpExtInst %15 %1 Normalize %214
-%216 = OpLoad %15 %17
-%217 = OpExtInst %5 %1 Length %216
-%218 = OpExtInst %5 %1 FClamp %217 %4 %12
-%213 = OpVectorTimesScalar %15 %215 %218
-OpStore %17 %213
-%220 = OpLoad %15 %14
-%222 = OpLoad %15 %17
+%212 = OpLoad %6 %209
+%207 = OpVectorTimesScalar %16 %208 %212
+%191 = OpFAdd %16 %192 %207
+OpStore %18 %191
+%214 = OpLoad %16 %18
+%215 = OpExtInst %16 %1 Normalize %214
+%216 = OpLoad %16 %18
+%217 = OpExtInst %6 %1 Length %216
+%218 = OpExtInst %6 %1 FClamp %217 %5 %13
+%213 = OpVectorTimesScalar %16 %215 %218
+OpStore %18 %213
+%220 = OpLoad %16 %15
+%222 = OpLoad %16 %18
%223 = OpAccessChain %224 %122 %225
-%226 = OpLoad %5 %223
-%221 = OpVectorTimesScalar %15 %222 %226
-%219 = OpFAdd %15 %220 %221
-OpStore %14 %219
-%228 = OpAccessChain %229 %14 %230
-%231 = OpLoad %5 %228
-%227 = OpFOrdLessThan %32 %231 %13
+%226 = OpLoad %6 %223
+%221 = OpVectorTimesScalar %16 %222 %226
+%219 = OpFAdd %16 %220 %221
+OpStore %15 %219
+%228 = OpAccessChain %229 %15 %230
+%231 = OpLoad %6 %228
+%227 = OpFOrdLessThan %32 %231 %14
OpSelectionMerge %232 None
OpBranchConditional %227 %233 %234
%233 = OpLabel
-%235 = OpAccessChain %236 %14 %237
-OpStore %235 %11
+%235 = OpAccessChain %236 %15 %237
+OpStore %235 %12
OpBranch %232
%234 = OpLabel
OpBranch %232
%232 = OpLabel
-%239 = OpAccessChain %240 %14 %241
-%242 = OpLoad %5 %239
-%238 = OpFOrdGreaterThan %32 %242 %11
+%239 = OpAccessChain %240 %15 %241
+%242 = OpLoad %6 %239
+%238 = OpFOrdGreaterThan %32 %242 %12
OpSelectionMerge %243 None
OpBranchConditional %238 %244 %245
%244 = OpLabel
-%246 = OpAccessChain %247 %14 %248
-OpStore %246 %13
+%246 = OpAccessChain %247 %15 %248
+OpStore %246 %14
OpBranch %243
%245 = OpLabel
OpBranch %243
%243 = OpLabel
-%250 = OpAccessChain %251 %14 %252
-%253 = OpLoad %5 %250
-%249 = OpFOrdLessThan %32 %253 %13
+%250 = OpAccessChain %251 %15 %252
+%253 = OpLoad %6 %250
+%249 = OpFOrdLessThan %32 %253 %14
OpSelectionMerge %254 None
OpBranchConditional %249 %255 %256
%255 = OpLabel
-%257 = OpAccessChain %258 %14 %259
-OpStore %257 %11
+%257 = OpAccessChain %258 %15 %259
+OpStore %257 %12
OpBranch %254
%256 = OpLabel
OpBranch %254
%254 = OpLabel
-%261 = OpAccessChain %262 %14 %263
-%264 = OpLoad %5 %261
-%260 = OpFOrdGreaterThan %32 %264 %11
+%261 = OpAccessChain %262 %15 %263
+%264 = OpLoad %6 %261
+%260 = OpFOrdGreaterThan %32 %264 %12
OpSelectionMerge %265 None
OpBranchConditional %260 %266 %267
%266 = OpLabel
-%268 = OpAccessChain %269 %14 %270
-OpStore %268 %13
+%268 = OpAccessChain %269 %15 %270
+OpStore %268 %14
OpBranch %265
%267 = OpLabel
OpBranch %265
%265 = OpLabel
%273 = OpAccessChain %275 %274 %276
%277 = OpAccessChain %278 %36 %279
-%280 = OpLoad %8 %277
+%280 = OpLoad %9 %277
%272 = OpAccessChain %281 %273 %280
%271 = OpAccessChain %282 %272 %283
-%284 = OpLoad %15 %14
+%284 = OpLoad %16 %15
OpStore %271 %284
%287 = OpAccessChain %288 %274 %289
%290 = OpAccessChain %291 %36 %292
-%293 = OpLoad %8 %290
+%293 = OpLoad %9 %290
%286 = OpAccessChain %294 %287 %293
%285 = OpAccessChain %295 %286 %296
-%297 = OpLoad %15 %17
+%297 = OpLoad %16 %18
OpStore %285 %297
OpReturn
OpFunctionEnd
diff --git a/tests/snapshots/snapshots__collatz.spvasm.snap b/tests/snapshots/snapshots__collatz.spvasm.snap
--- a/tests/snapshots/snapshots__collatz.spvasm.snap
+++ b/tests/snapshots/snapshots__collatz.spvasm.snap
@@ -17,93 +17,93 @@ OpMemberDecorate %45 0 Offset 0
OpDecorate %46 DescriptorSet 0
OpDecorate %46 Binding 0
OpDecorate %53 BuiltIn GlobalInvocationId
-%3 = OpTypeInt 32 0
-%2 = OpConstant %3 0
-%4 = OpConstant %3 1
-%5 = OpConstant %3 2
-%6 = OpConstant %3 3
-%8 = OpTypePointer Function %3
-%12 = OpTypeFunction %3 %3
-%18 = OpTypeBool
-%38 = OpTypeVoid
-%40 = OpTypeFunction %38
-%43 = OpTypeRuntimeArray %3
+%0 = OpTypeVoid
+%4 = OpTypeInt 32 0
+%3 = OpConstant %4 0
+%5 = OpConstant %4 1
+%6 = OpConstant %4 2
+%7 = OpConstant %4 3
+%9 = OpTypePointer Function %4
+%13 = OpTypeFunction %4 %4
+%19 = OpTypeBool
+%40 = OpTypeFunction %0
+%43 = OpTypeRuntimeArray %4
%45 = OpTypeStruct %43
%47 = OpTypePointer Uniform %45
%46 = OpVariable %47 Uniform
%48 = OpTypePointer Uniform %43
%49 = OpTypeInt 32 1
%50 = OpConstant %49 0
-%52 = OpTypeVector %3 3
+%52 = OpTypeVector %4 3
%54 = OpTypePointer Input %52
%53 = OpVariable %54 Input
-%55 = OpTypePointer Input %3
+%55 = OpTypePointer Input %4
%56 = OpConstant %49 0
-%58 = OpTypePointer Uniform %3
+%58 = OpTypePointer Uniform %4
%62 = OpTypePointer Uniform %43
%63 = OpConstant %49 0
-%65 = OpTypePointer Input %3
+%65 = OpTypePointer Input %4
%66 = OpConstant %49 0
-%68 = OpTypePointer Uniform %3
-%11 = OpFunction %3 None %12
-%10 = OpFunctionParameter %3
-%13 = OpLabel
-%7 = OpVariable %8 Function
-%9 = OpVariable %8 Function %2
-OpStore %7 %10
-OpBranch %14
+%68 = OpTypePointer Uniform %4
+%12 = OpFunction %4 None %13
+%11 = OpFunctionParameter %4
%14 = OpLabel
-OpLoopMerge %15 %17 None
-OpBranch %16
-%16 = OpLabel
-%20 = OpLoad %3 %7
-%19 = OpULessThanEqual %18 %20 %4
-OpSelectionMerge %21 None
-OpBranchConditional %19 %22 %23
-%22 = OpLabel
+%8 = OpVariable %9 Function
+%10 = OpVariable %9 Function %3
+OpStore %8 %11
OpBranch %15
-%23 = OpLabel
-OpBranch %21
-%21 = OpLabel
-%26 = OpLoad %3 %7
-%25 = OpUMod %3 %26 %5
-%24 = OpIEqual %18 %25 %2
-OpSelectionMerge %27 None
-OpBranchConditional %24 %28 %29
-%28 = OpLabel
-%31 = OpLoad %3 %7
-%30 = OpUDiv %3 %31 %5
-OpStore %7 %30
-OpBranch %27
-%29 = OpLabel
-%34 = OpLoad %3 %7
-%33 = OpIMul %3 %6 %34
-%32 = OpIAdd %3 %33 %4
-OpStore %7 %32
-OpBranch %27
-%27 = OpLabel
-%36 = OpLoad %3 %9
-%35 = OpIAdd %3 %36 %4
-OpStore %9 %35
+%15 = OpLabel
+OpLoopMerge %16 %18 None
OpBranch %17
%17 = OpLabel
-OpBranch %14
-%15 = OpLabel
-%37 = OpLoad %3 %9
-OpReturnValue %37
+%21 = OpLoad %4 %8
+%20 = OpULessThanEqual %19 %21 %5
+OpSelectionMerge %22 None
+OpBranchConditional %20 %23 %24
+%23 = OpLabel
+OpBranch %16
+%24 = OpLabel
+OpBranch %22
+%22 = OpLabel
+%27 = OpLoad %4 %8
+%26 = OpUMod %4 %27 %6
+%25 = OpIEqual %19 %26 %3
+OpSelectionMerge %28 None
+OpBranchConditional %25 %29 %30
+%29 = OpLabel
+%32 = OpLoad %4 %8
+%31 = OpUDiv %4 %32 %6
+OpStore %8 %31
+OpBranch %28
+%30 = OpLabel
+%35 = OpLoad %4 %8
+%34 = OpIMul %4 %7 %35
+%33 = OpIAdd %4 %34 %5
+OpStore %8 %33
+OpBranch %28
+%28 = OpLabel
+%37 = OpLoad %4 %10
+%36 = OpIAdd %4 %37 %5
+OpStore %10 %36
+OpBranch %18
+%18 = OpLabel
+OpBranch %15
+%16 = OpLabel
+%38 = OpLoad %4 %10
+OpReturnValue %38
OpFunctionEnd
-%39 = OpFunction %38 None %40
+%39 = OpFunction %0 None %40
%41 = OpLabel
%44 = OpAccessChain %48 %46 %50
%51 = OpAccessChain %55 %53 %56
-%57 = OpLoad %3 %51
+%57 = OpLoad %4 %51
%42 = OpAccessChain %58 %44 %57
%61 = OpAccessChain %62 %46 %63
%64 = OpAccessChain %65 %53 %66
-%67 = OpLoad %3 %64
+%67 = OpLoad %4 %64
%60 = OpAccessChain %68 %61 %67
-%69 = OpLoad %3 %60
-%59 = OpFunctionCall %3 %11 %69
+%69 = OpLoad %4 %60
+%59 = OpFunctionCall %4 %12 %69
OpStore %42 %59
OpReturn
OpFunctionEnd
diff --git a/tests/snapshots/snapshots__empty.spvasm.snap b/tests/snapshots/snapshots__empty.spvasm.snap
--- a/tests/snapshots/snapshots__empty.spvasm.snap
+++ b/tests/snapshots/snapshots__empty.spvasm.snap
@@ -11,9 +11,9 @@ OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %3 "main"
OpExecutionMode %3 LocalSize 1 1 1
-%2 = OpTypeVoid
-%4 = OpTypeFunction %2
-%3 = OpFunction %2 None %4
+%0 = OpTypeVoid
+%4 = OpTypeFunction %0
+%3 = OpFunction %0 None %4
%5 = OpLabel
OpReturn
OpFunctionEnd
diff --git a/tests/snapshots/snapshots__quad.spvasm.snap b/tests/snapshots/snapshots__quad.spvasm.snap
--- a/tests/snapshots/snapshots__quad.spvasm.snap
+++ b/tests/snapshots/snapshots__quad.spvasm.snap
@@ -22,23 +22,23 @@ OpDecorate %27 Binding 0
OpDecorate %32 DescriptorSet 0
OpDecorate %32 Binding 1
OpDecorate %35 Location 0
-%3 = OpTypeFloat 32
-%2 = OpConstant %3 1.2
-%4 = OpConstant %3 0.0
-%5 = OpConstant %3 1.0
-%6 = OpTypeVoid
-%8 = OpTypeFunction %6
-%10 = OpTypeVector %3 2
+%0 = OpTypeVoid
+%4 = OpTypeFloat 32
+%3 = OpConstant %4 1.2
+%5 = OpConstant %4 0.0
+%6 = OpConstant %4 1.0
+%8 = OpTypeFunction %0
+%10 = OpTypeVector %4 2
%12 = OpTypePointer Output %10
%11 = OpVariable %12 Output
%14 = OpTypePointer Input %10
%13 = OpVariable %14 Input
-%16 = OpTypeVector %3 4
+%16 = OpTypeVector %4 4
%18 = OpTypePointer Output %16
%17 = OpVariable %18 Output
%20 = OpVariable %14 Input
%25 = OpVariable %18 Output
-%26 = OpTypeImage %3 2D 0 0 0 1 Unknown
+%26 = OpTypeImage %4 2D 0 0 0 1 Unknown
%28 = OpTypePointer UniformConstant %26
%27 = OpVariable %28 UniformConstant
%30 = OpTypeSampledImage %26
diff --git a/tests/snapshots/snapshots__quad.spvasm.snap b/tests/snapshots/snapshots__quad.spvasm.snap
--- a/tests/snapshots/snapshots__quad.spvasm.snap
+++ b/tests/snapshots/snapshots__quad.spvasm.snap
@@ -46,17 +46,17 @@ OpDecorate %35 Location 0
%33 = OpTypePointer UniformConstant %31
%32 = OpVariable %33 UniformConstant
%35 = OpVariable %14 Input
-%7 = OpFunction %6 None %8
+%7 = OpFunction %0 None %8
%9 = OpLabel
%15 = OpLoad %10 %13
OpStore %11 %15
%21 = OpLoad %10 %20
-%19 = OpVectorTimesScalar %10 %21 %2
-%22 = OpCompositeConstruct %16 %19 %4 %5
+%19 = OpVectorTimesScalar %10 %21 %3
+%22 = OpCompositeConstruct %16 %19 %5 %6
OpStore %17 %22
OpReturn
OpFunctionEnd
-%23 = OpFunction %6 None %8
+%23 = OpFunction %0 None %8
%24 = OpLabel
%29 = OpLoad %26 %27
%34 = OpLoad %31 %32
diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/snapshots/snapshots__shadow.spvasm.snap
--- a/tests/snapshots/snapshots__shadow.spvasm.snap
+++ b/tests/snapshots/snapshots__shadow.spvasm.snap
@@ -11,10 +11,10 @@ OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %64 "fs_main" %114 %111 %217
OpExecutionMode %64 OriginUpperLeft
-OpDecorate %27 DescriptorSet 0
-OpDecorate %27 Binding 2
-OpDecorate %32 DescriptorSet 0
-OpDecorate %32 Binding 3
+OpDecorate %28 DescriptorSet 0
+OpDecorate %28 Binding 2
+OpDecorate %33 DescriptorSet 0
+OpDecorate %33 Binding 3
OpDecorate %76 Block
OpMemberDecorate %76 0 Offset 0
OpDecorate %77 DescriptorSet 0
diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/snapshots/snapshots__shadow.spvasm.snap
--- a/tests/snapshots/snapshots__shadow.spvasm.snap
+++ b/tests/snapshots/snapshots__shadow.spvasm.snap
@@ -33,161 +33,161 @@ OpDecorate %102 Binding 1
OpDecorate %111 Location 1
OpDecorate %114 Location 0
OpDecorate %217 Location 0
-%3 = OpTypeFloat 32
-%2 = OpConstant %3 0.0
-%4 = OpConstant %3 1.0
-%5 = OpConstant %3 0.5
-%6 = OpConstant %3 -0.5
-%7 = OpConstant %3 0.05
-%9 = OpTypeVector %3 3
-%8 = OpConstantComposite %9 %7 %7 %7
-%11 = OpTypeInt 32 0
-%10 = OpConstant %11 10
-%12 = OpConstant %11 0
-%13 = OpConstant %11 1
-%16 = OpTypeVector %3 4
-%18 = OpTypeFunction %3 %11 %16
-%20 = OpTypeBool
-%26 = OpTypeImage %3 2D 1 1 0 1 Unknown
-%28 = OpTypePointer UniformConstant %26
-%27 = OpVariable %28 UniformConstant
-%30 = OpTypeSampledImage %26
-%31 = OpTypeSampler
-%33 = OpTypePointer UniformConstant %31
-%32 = OpVariable %33 UniformConstant
-%35 = OpTypeVector %3 2
-%49 = OpTypeInt 32 1
-%58 = OpConstant %3 0.0
-%60 = OpTypePointer Function %9
-%62 = OpTypePointer Function %11
-%63 = OpTypeVoid
-%65 = OpTypeFunction %63
-%74 = OpTypeVector %11 4
+%0 = OpTypeVoid
+%4 = OpTypeFloat 32
+%3 = OpConstant %4 0.0
+%5 = OpConstant %4 1.0
+%6 = OpConstant %4 0.5
+%7 = OpConstant %4 -0.5
+%8 = OpConstant %4 0.05
+%10 = OpTypeVector %4 3
+%9 = OpConstantComposite %10 %8 %8 %8
+%12 = OpTypeInt 32 0
+%11 = OpConstant %12 10
+%13 = OpConstant %12 0
+%14 = OpConstant %12 1
+%17 = OpTypeVector %4 4
+%19 = OpTypeFunction %4 %12 %17
+%21 = OpTypeBool
+%27 = OpTypeImage %4 2D 1 1 0 1 Unknown
+%29 = OpTypePointer UniformConstant %27
+%28 = OpVariable %29 UniformConstant
+%31 = OpTypeSampledImage %27
+%32 = OpTypeSampler
+%34 = OpTypePointer UniformConstant %32
+%33 = OpVariable %34 UniformConstant
+%36 = OpTypeVector %4 2
+%50 = OpTypeInt 32 1
+%59 = OpConstant %4 0.0
+%61 = OpTypePointer Function %10
+%63 = OpTypePointer Function %12
+%65 = OpTypeFunction %0
+%74 = OpTypeVector %12 4
%76 = OpTypeStruct %74
%78 = OpTypePointer Uniform %76
%77 = OpVariable %78 Uniform
%79 = OpTypePointer Uniform %74
-%80 = OpConstant %49 0
-%81 = OpTypePointer Uniform %11
-%82 = OpConstant %49 0
-%95 = OpTypeMatrix %16 4
-%97 = OpTypeStruct %95 %16 %16
+%80 = OpConstant %50 0
+%81 = OpTypePointer Uniform %12
+%82 = OpConstant %50 0
+%95 = OpTypeMatrix %17 4
+%97 = OpTypeStruct %95 %17 %17
%99 = OpTypeRuntimeArray %97
%101 = OpTypeStruct %99
%103 = OpTypePointer Uniform %101
%102 = OpVariable %103 Uniform
%104 = OpTypePointer Uniform %99
-%105 = OpConstant %49 0
+%105 = OpConstant %50 0
%107 = OpTypePointer Uniform %97
%108 = OpTypePointer Uniform %95
-%109 = OpConstant %49 0
-%112 = OpTypePointer Input %16
+%109 = OpConstant %50 0
+%112 = OpTypePointer Input %17
%111 = OpVariable %112 Input
-%115 = OpTypePointer Input %9
+%115 = OpTypePointer Input %10
%114 = OpVariable %115 Input
%123 = OpTypePointer Uniform %99
-%124 = OpConstant %49 0
+%124 = OpConstant %50 0
%126 = OpTypePointer Uniform %97
-%127 = OpTypePointer Uniform %16
-%128 = OpConstant %49 1
-%129 = OpTypePointer Uniform %3
-%130 = OpConstant %49 0
+%127 = OpTypePointer Uniform %17
+%128 = OpConstant %50 1
+%129 = OpTypePointer Uniform %4
+%130 = OpConstant %50 0
%136 = OpTypePointer Uniform %99
-%137 = OpConstant %49 0
+%137 = OpConstant %50 0
%139 = OpTypePointer Uniform %97
-%140 = OpTypePointer Uniform %16
-%141 = OpConstant %49 1
-%142 = OpTypePointer Uniform %3
-%143 = OpConstant %49 1
+%140 = OpTypePointer Uniform %17
+%141 = OpConstant %50 1
+%142 = OpTypePointer Uniform %4
+%143 = OpConstant %50 1
%149 = OpTypePointer Uniform %99
-%150 = OpConstant %49 0
+%150 = OpConstant %50 0
%152 = OpTypePointer Uniform %97
-%153 = OpTypePointer Uniform %16
-%154 = OpConstant %49 1
-%155 = OpTypePointer Uniform %3
-%156 = OpConstant %49 2
-%160 = OpTypePointer Input %3
-%161 = OpConstant %49 0
-%164 = OpTypePointer Input %3
-%165 = OpConstant %49 1
-%168 = OpTypePointer Input %3
-%169 = OpConstant %49 2
+%153 = OpTypePointer Uniform %17
+%154 = OpConstant %50 1
+%155 = OpTypePointer Uniform %4
+%156 = OpConstant %50 2
+%160 = OpTypePointer Input %4
+%161 = OpConstant %50 0
+%164 = OpTypePointer Input %4
+%165 = OpConstant %50 1
+%168 = OpTypePointer Input %4
+%169 = OpConstant %50 2
%179 = OpTypePointer Uniform %99
-%180 = OpConstant %49 0
+%180 = OpConstant %50 0
%182 = OpTypePointer Uniform %97
-%183 = OpTypePointer Uniform %16
-%184 = OpConstant %49 2
-%185 = OpTypePointer Uniform %3
-%186 = OpConstant %49 0
+%183 = OpTypePointer Uniform %17
+%184 = OpConstant %50 2
+%185 = OpTypePointer Uniform %4
+%186 = OpConstant %50 0
%192 = OpTypePointer Uniform %99
-%193 = OpConstant %49 0
+%193 = OpConstant %50 0
%195 = OpTypePointer Uniform %97
-%196 = OpTypePointer Uniform %16
-%197 = OpConstant %49 2
-%198 = OpTypePointer Uniform %3
-%199 = OpConstant %49 1
+%196 = OpTypePointer Uniform %17
+%197 = OpConstant %50 2
+%198 = OpTypePointer Uniform %4
+%199 = OpConstant %50 1
%205 = OpTypePointer Uniform %99
-%206 = OpConstant %49 0
+%206 = OpConstant %50 0
%208 = OpTypePointer Uniform %97
-%209 = OpTypePointer Uniform %16
-%210 = OpConstant %49 2
-%211 = OpTypePointer Uniform %3
-%212 = OpConstant %49 2
-%218 = OpTypePointer Output %16
+%209 = OpTypePointer Uniform %17
+%210 = OpConstant %50 2
+%211 = OpTypePointer Uniform %4
+%212 = OpConstant %50 2
+%218 = OpTypePointer Output %17
%217 = OpVariable %218 Output
-%17 = OpFunction %3 None %18
-%14 = OpFunctionParameter %11
-%15 = OpFunctionParameter %16
-%19 = OpLabel
-%22 = OpCompositeExtract %3 %15 3
-%21 = OpFOrdLessThanEqual %20 %22 %2
-OpSelectionMerge %23 None
-OpBranchConditional %21 %24 %25
-%24 = OpLabel
-OpReturnValue %4
+%18 = OpFunction %4 None %19
+%15 = OpFunctionParameter %12
+%16 = OpFunctionParameter %17
+%20 = OpLabel
+%23 = OpCompositeExtract %4 %16 3
+%22 = OpFOrdLessThanEqual %21 %23 %3
+OpSelectionMerge %24 None
+OpBranchConditional %22 %25 %26
%25 = OpLabel
-OpBranch %23
-%23 = OpLabel
-%29 = OpLoad %26 %27
-%34 = OpLoad %31 %32
-%39 = OpCompositeExtract %3 %15 0
-%40 = OpCompositeExtract %3 %15 1
-%41 = OpCompositeConstruct %35 %39 %40
-%42 = OpCompositeConstruct %35 %5 %6
-%38 = OpFMul %35 %41 %42
-%44 = OpCompositeExtract %3 %15 3
-%43 = OpFDiv %3 %4 %44
-%37 = OpVectorTimesScalar %35 %38 %43
-%45 = OpCompositeConstruct %35 %5 %5
-%36 = OpFAdd %35 %37 %45
-%46 = OpCompositeExtract %3 %36 0
-%47 = OpCompositeExtract %3 %36 1
-%50 = OpBitcast %49 %14
-%48 = OpConvertUToF %3 %50
-%51 = OpCompositeConstruct %9 %46 %47 %48
-%52 = OpSampledImage %30 %29 %34
-%55 = OpCompositeExtract %3 %15 2
-%57 = OpCompositeExtract %3 %15 3
-%56 = OpFDiv %3 %4 %57
-%54 = OpFMul %3 %55 %56
-%53 = OpImageSampleDrefExplicitLod %3 %52 %51 %54 Lod %58
-OpReturnValue %53
+OpReturnValue %5
+%26 = OpLabel
+OpBranch %24
+%24 = OpLabel
+%30 = OpLoad %27 %28
+%35 = OpLoad %32 %33
+%40 = OpCompositeExtract %4 %16 0
+%41 = OpCompositeExtract %4 %16 1
+%42 = OpCompositeConstruct %36 %40 %41
+%43 = OpCompositeConstruct %36 %6 %7
+%39 = OpFMul %36 %42 %43
+%45 = OpCompositeExtract %4 %16 3
+%44 = OpFDiv %4 %5 %45
+%38 = OpVectorTimesScalar %36 %39 %44
+%46 = OpCompositeConstruct %36 %6 %6
+%37 = OpFAdd %36 %38 %46
+%47 = OpCompositeExtract %4 %37 0
+%48 = OpCompositeExtract %4 %37 1
+%51 = OpBitcast %50 %15
+%49 = OpConvertUToF %4 %51
+%52 = OpCompositeConstruct %10 %47 %48 %49
+%53 = OpSampledImage %31 %30 %35
+%56 = OpCompositeExtract %4 %16 2
+%58 = OpCompositeExtract %4 %16 3
+%57 = OpFDiv %4 %5 %58
+%55 = OpFMul %4 %56 %57
+%54 = OpImageSampleDrefExplicitLod %4 %53 %52 %55 Lod %59
+OpReturnValue %54
OpFunctionEnd
-%64 = OpFunction %63 None %65
+%64 = OpFunction %0 None %65
%66 = OpLabel
-%59 = OpVariable %60 Function %8
-%61 = OpVariable %62 Function %12
+%60 = OpVariable %61 Function %9
+%62 = OpVariable %63 Function %13
OpBranch %67
%67 = OpLabel
OpLoopMerge %68 %70 None
OpBranch %69
%69 = OpLabel
-%72 = OpLoad %11 %61
+%72 = OpLoad %12 %62
%75 = OpAccessChain %79 %77 %80
%73 = OpAccessChain %81 %75 %82
-%83 = OpLoad %11 %73
-%84 = OpExtInst %11 %1 UMin %83 %10
-%71 = OpUGreaterThanEqual %20 %72 %84
+%83 = OpLoad %12 %73
+%84 = OpExtInst %12 %1 UMin %83 %11
+%71 = OpUGreaterThanEqual %21 %72 %84
OpSelectionMerge %85 None
OpBranchConditional %71 %86 %87
%86 = OpLabel
diff --git a/tests/snapshots/snapshots__shadow.spvasm.snap b/tests/snapshots/snapshots__shadow.spvasm.snap
--- a/tests/snapshots/snapshots__shadow.spvasm.snap
+++ b/tests/snapshots/snapshots__shadow.spvasm.snap
@@ -195,80 +195,80 @@ OpBranch %68
%87 = OpLabel
OpBranch %85
%85 = OpLabel
-%89 = OpLoad %9 %59
-%93 = OpLoad %11 %61
+%89 = OpLoad %10 %60
+%93 = OpLoad %12 %62
%100 = OpAccessChain %104 %102 %105
-%106 = OpLoad %11 %61
+%106 = OpLoad %12 %62
%98 = OpAccessChain %107 %100 %106
%96 = OpAccessChain %108 %98 %109
%110 = OpLoad %95 %96
-%113 = OpLoad %16 %111
-%94 = OpMatrixTimesVector %16 %110 %113
-%92 = OpFunctionCall %3 %17 %93 %94
-%116 = OpLoad %9 %114
-%117 = OpExtInst %9 %1 Normalize %116
+%113 = OpLoad %17 %111
+%94 = OpMatrixTimesVector %17 %110 %113
+%92 = OpFunctionCall %4 %18 %93 %94
+%116 = OpLoad %10 %114
+%117 = OpExtInst %10 %1 Normalize %116
%122 = OpAccessChain %123 %102 %124
-%125 = OpLoad %11 %61
+%125 = OpLoad %12 %62
%121 = OpAccessChain %126 %122 %125
%120 = OpAccessChain %127 %121 %128
%119 = OpAccessChain %129 %120 %130
-%131 = OpLoad %3 %119
+%131 = OpLoad %4 %119
%135 = OpAccessChain %136 %102 %137
-%138 = OpLoad %11 %61
+%138 = OpLoad %12 %62
%134 = OpAccessChain %139 %135 %138
%133 = OpAccessChain %140 %134 %141
%132 = OpAccessChain %142 %133 %143
-%144 = OpLoad %3 %132
+%144 = OpLoad %4 %132
%148 = OpAccessChain %149 %102 %150
-%151 = OpLoad %11 %61
+%151 = OpLoad %12 %62
%147 = OpAccessChain %152 %148 %151
%146 = OpAccessChain %153 %147 %154
%145 = OpAccessChain %155 %146 %156
-%157 = OpLoad %3 %145
-%158 = OpCompositeConstruct %9 %131 %144 %157
+%157 = OpLoad %4 %145
+%158 = OpCompositeConstruct %10 %131 %144 %157
%159 = OpAccessChain %160 %111 %161
-%162 = OpLoad %3 %159
+%162 = OpLoad %4 %159
%163 = OpAccessChain %164 %111 %165
-%166 = OpLoad %3 %163
+%166 = OpLoad %4 %163
%167 = OpAccessChain %168 %111 %169
-%170 = OpLoad %3 %167
-%171 = OpCompositeConstruct %9 %162 %166 %170
-%118 = OpFSub %9 %158 %171
-%172 = OpExtInst %9 %1 Normalize %118
-%173 = OpDot %3 %117 %172
-%174 = OpExtInst %3 %1 FMax %2 %173
-%91 = OpFMul %3 %92 %174
+%170 = OpLoad %4 %167
+%171 = OpCompositeConstruct %10 %162 %166 %170
+%118 = OpFSub %10 %158 %171
+%172 = OpExtInst %10 %1 Normalize %118
+%173 = OpDot %4 %117 %172
+%174 = OpExtInst %4 %1 FMax %3 %173
+%91 = OpFMul %4 %92 %174
%178 = OpAccessChain %179 %102 %180
-%181 = OpLoad %11 %61
+%181 = OpLoad %12 %62
%177 = OpAccessChain %182 %178 %181
%176 = OpAccessChain %183 %177 %184
%175 = OpAccessChain %185 %176 %186
-%187 = OpLoad %3 %175
+%187 = OpLoad %4 %175
%191 = OpAccessChain %192 %102 %193
-%194 = OpLoad %11 %61
+%194 = OpLoad %12 %62
%190 = OpAccessChain %195 %191 %194
%189 = OpAccessChain %196 %190 %197
%188 = OpAccessChain %198 %189 %199
-%200 = OpLoad %3 %188
+%200 = OpLoad %4 %188
%204 = OpAccessChain %205 %102 %206
-%207 = OpLoad %11 %61
+%207 = OpLoad %12 %62
%203 = OpAccessChain %208 %204 %207
%202 = OpAccessChain %209 %203 %210
%201 = OpAccessChain %211 %202 %212
-%213 = OpLoad %3 %201
-%214 = OpCompositeConstruct %9 %187 %200 %213
-%90 = OpVectorTimesScalar %9 %214 %91
-%88 = OpFAdd %9 %89 %90
-OpStore %59 %88
+%213 = OpLoad %4 %201
+%214 = OpCompositeConstruct %10 %187 %200 %213
+%90 = OpVectorTimesScalar %10 %214 %91
+%88 = OpFAdd %10 %89 %90
+OpStore %60 %88
OpBranch %70
%70 = OpLabel
-%216 = OpLoad %11 %61
-%215 = OpIAdd %11 %216 %13
-OpStore %61 %215
+%216 = OpLoad %12 %62
+%215 = OpIAdd %12 %216 %14
+OpStore %62 %215
OpBranch %67
%68 = OpLabel
-%219 = OpLoad %9 %59
-%220 = OpCompositeConstruct %16 %219 %4
+%219 = OpLoad %10 %60
+%220 = OpCompositeConstruct %17 %219 %5
OpStore %217 %220
OpReturn
OpFunctionEnd
diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/snapshots/snapshots__skybox.spvasm.snap
--- a/tests/snapshots/snapshots__skybox.spvasm.snap
+++ b/tests/snapshots/snapshots__skybox.spvasm.snap
@@ -30,95 +30,95 @@ OpDecorate %174 Binding 1
OpDecorate %179 DescriptorSet 0
OpDecorate %179 Binding 2
OpDecorate %182 Location 0
-%3 = OpTypeInt 32 1
-%2 = OpConstant %3 2
-%4 = OpConstant %3 1
-%6 = OpTypeFloat 32
-%5 = OpConstant %6 4.0
-%7 = OpConstant %6 1.0
-%8 = OpConstant %6 0.0
-%10 = OpTypePointer Function %3
-%13 = OpTypeVector %6 4
-%14 = OpTypePointer Function %13
-%15 = OpTypeVoid
-%17 = OpTypeFunction %15
+%0 = OpTypeVoid
+%4 = OpTypeInt 32 1
+%3 = OpConstant %4 2
+%5 = OpConstant %4 1
+%7 = OpTypeFloat 32
+%6 = OpConstant %7 4.0
+%8 = OpConstant %7 1.0
+%9 = OpConstant %7 0.0
+%11 = OpTypePointer Function %4
+%14 = OpTypeVector %7 4
+%15 = OpTypePointer Function %14
+%17 = OpTypeFunction %0
%20 = OpTypeInt 32 0
%22 = OpTypePointer Input %20
%21 = OpVariable %22 Input
-%29 = OpTypeMatrix %13 4
+%29 = OpTypeMatrix %14 4
%31 = OpTypeStruct %29 %29
%33 = OpTypePointer Uniform %31
%32 = OpVariable %33 Uniform
%34 = OpTypePointer Uniform %29
-%35 = OpConstant %3 0
-%46 = OpTypeVector %6 3
+%35 = OpConstant %4 0
+%46 = OpTypeVector %7 3
%48 = OpTypePointer Output %46
%47 = OpVariable %48 Output
%50 = OpTypeMatrix %46 3
%54 = OpTypePointer Uniform %29
-%55 = OpConstant %3 1
-%56 = OpTypePointer Uniform %13
-%57 = OpConstant %3 0
-%58 = OpTypePointer Uniform %6
-%59 = OpConstant %3 0
+%55 = OpConstant %4 1
+%56 = OpTypePointer Uniform %14
+%57 = OpConstant %4 0
+%58 = OpTypePointer Uniform %7
+%59 = OpConstant %4 0
%64 = OpTypePointer Uniform %29
-%65 = OpConstant %3 1
-%66 = OpTypePointer Uniform %13
-%67 = OpConstant %3 0
-%68 = OpTypePointer Uniform %6
-%69 = OpConstant %3 1
+%65 = OpConstant %4 1
+%66 = OpTypePointer Uniform %14
+%67 = OpConstant %4 0
+%68 = OpTypePointer Uniform %7
+%69 = OpConstant %4 1
%74 = OpTypePointer Uniform %29
-%75 = OpConstant %3 1
-%76 = OpTypePointer Uniform %13
-%77 = OpConstant %3 0
-%78 = OpTypePointer Uniform %6
-%79 = OpConstant %3 2
+%75 = OpConstant %4 1
+%76 = OpTypePointer Uniform %14
+%77 = OpConstant %4 0
+%78 = OpTypePointer Uniform %7
+%79 = OpConstant %4 2
%85 = OpTypePointer Uniform %29
-%86 = OpConstant %3 1
-%87 = OpTypePointer Uniform %13
-%88 = OpConstant %3 1
-%89 = OpTypePointer Uniform %6
-%90 = OpConstant %3 0
+%86 = OpConstant %4 1
+%87 = OpTypePointer Uniform %14
+%88 = OpConstant %4 1
+%89 = OpTypePointer Uniform %7
+%90 = OpConstant %4 0
%95 = OpTypePointer Uniform %29
-%96 = OpConstant %3 1
-%97 = OpTypePointer Uniform %13
-%98 = OpConstant %3 1
-%99 = OpTypePointer Uniform %6
-%100 = OpConstant %3 1
+%96 = OpConstant %4 1
+%97 = OpTypePointer Uniform %14
+%98 = OpConstant %4 1
+%99 = OpTypePointer Uniform %7
+%100 = OpConstant %4 1
%105 = OpTypePointer Uniform %29
-%106 = OpConstant %3 1
-%107 = OpTypePointer Uniform %13
-%108 = OpConstant %3 1
-%109 = OpTypePointer Uniform %6
-%110 = OpConstant %3 2
+%106 = OpConstant %4 1
+%107 = OpTypePointer Uniform %14
+%108 = OpConstant %4 1
+%109 = OpTypePointer Uniform %7
+%110 = OpConstant %4 2
%116 = OpTypePointer Uniform %29
-%117 = OpConstant %3 1
-%118 = OpTypePointer Uniform %13
-%119 = OpConstant %3 2
-%120 = OpTypePointer Uniform %6
-%121 = OpConstant %3 0
+%117 = OpConstant %4 1
+%118 = OpTypePointer Uniform %14
+%119 = OpConstant %4 2
+%120 = OpTypePointer Uniform %7
+%121 = OpConstant %4 0
%126 = OpTypePointer Uniform %29
-%127 = OpConstant %3 1
-%128 = OpTypePointer Uniform %13
-%129 = OpConstant %3 2
-%130 = OpTypePointer Uniform %6
-%131 = OpConstant %3 1
+%127 = OpConstant %4 1
+%128 = OpTypePointer Uniform %14
+%129 = OpConstant %4 2
+%130 = OpTypePointer Uniform %7
+%131 = OpConstant %4 1
%136 = OpTypePointer Uniform %29
-%137 = OpConstant %3 1
-%138 = OpTypePointer Uniform %13
-%139 = OpConstant %3 2
-%140 = OpTypePointer Uniform %6
-%141 = OpConstant %3 2
-%147 = OpTypePointer Function %6
-%148 = OpConstant %3 0
-%151 = OpTypePointer Function %6
-%152 = OpConstant %3 1
-%155 = OpTypePointer Function %6
-%156 = OpConstant %3 2
-%160 = OpTypePointer Output %13
+%137 = OpConstant %4 1
+%138 = OpTypePointer Uniform %14
+%139 = OpConstant %4 2
+%140 = OpTypePointer Uniform %7
+%141 = OpConstant %4 2
+%147 = OpTypePointer Function %7
+%148 = OpConstant %4 0
+%151 = OpTypePointer Function %7
+%152 = OpConstant %4 1
+%155 = OpTypePointer Function %7
+%156 = OpConstant %4 2
+%160 = OpTypePointer Output %14
%159 = OpVariable %160 Output
%172 = OpVariable %160 Output
-%173 = OpTypeImage %6 Cube 0 0 0 1 Unknown
+%173 = OpTypeImage %7 Cube 0 0 0 1 Unknown
%175 = OpTypePointer UniformConstant %173
%174 = OpVariable %175 UniformConstant
%177 = OpTypeSampledImage %173
diff --git a/tests/snapshots/snapshots__skybox.spvasm.snap b/tests/snapshots/snapshots__skybox.spvasm.snap
--- a/tests/snapshots/snapshots__skybox.spvasm.snap
+++ b/tests/snapshots/snapshots__skybox.spvasm.snap
@@ -127,101 +127,101 @@ OpDecorate %182 Location 0
%179 = OpVariable %180 UniformConstant
%183 = OpTypePointer Input %46
%182 = OpVariable %183 Input
-%16 = OpFunction %15 None %17
+%16 = OpFunction %0 None %17
%18 = OpLabel
-%9 = OpVariable %10 Function
-%11 = OpVariable %10 Function
-%12 = OpVariable %14 Function
+%10 = OpVariable %11 Function
+%12 = OpVariable %11 Function
+%13 = OpVariable %15 Function
%23 = OpLoad %20 %21
-%24 = OpBitcast %3 %23
-%19 = OpSDiv %3 %24 %2
-OpStore %9 %19
+%24 = OpBitcast %4 %23
+%19 = OpSDiv %4 %24 %3
+OpStore %10 %19
%26 = OpLoad %20 %21
-%27 = OpBitcast %3 %26
-%25 = OpBitwiseAnd %3 %27 %4
-OpStore %11 %25
+%27 = OpBitcast %4 %26
+%25 = OpBitwiseAnd %4 %27 %5
+OpStore %12 %25
%30 = OpAccessChain %34 %32 %35
%36 = OpLoad %29 %30
-%39 = OpLoad %3 %9
-%40 = OpConvertSToF %6 %39
-%38 = OpFMul %6 %40 %5
-%37 = OpFSub %6 %38 %7
-%43 = OpLoad %3 %11
-%44 = OpConvertSToF %6 %43
-%42 = OpFMul %6 %44 %5
-%41 = OpFSub %6 %42 %7
-%45 = OpCompositeConstruct %13 %37 %41 %8 %7
-%28 = OpMatrixTimesVector %13 %36 %45
-OpStore %12 %28
+%39 = OpLoad %4 %10
+%40 = OpConvertSToF %7 %39
+%38 = OpFMul %7 %40 %6
+%37 = OpFSub %7 %38 %8
+%43 = OpLoad %4 %12
+%44 = OpConvertSToF %7 %43
+%42 = OpFMul %7 %44 %6
+%41 = OpFSub %7 %42 %8
+%45 = OpCompositeConstruct %14 %37 %41 %9 %8
+%28 = OpMatrixTimesVector %14 %36 %45
+OpStore %13 %28
%53 = OpAccessChain %54 %32 %55
%52 = OpAccessChain %56 %53 %57
%51 = OpAccessChain %58 %52 %59
-%60 = OpLoad %6 %51
+%60 = OpLoad %7 %51
%63 = OpAccessChain %64 %32 %65
%62 = OpAccessChain %66 %63 %67
%61 = OpAccessChain %68 %62 %69
-%70 = OpLoad %6 %61
+%70 = OpLoad %7 %61
%73 = OpAccessChain %74 %32 %75
%72 = OpAccessChain %76 %73 %77
%71 = OpAccessChain %78 %72 %79
-%80 = OpLoad %6 %71
+%80 = OpLoad %7 %71
%81 = OpCompositeConstruct %46 %60 %70 %80
%84 = OpAccessChain %85 %32 %86
%83 = OpAccessChain %87 %84 %88
%82 = OpAccessChain %89 %83 %90
-%91 = OpLoad %6 %82
+%91 = OpLoad %7 %82
%94 = OpAccessChain %95 %32 %96
%93 = OpAccessChain %97 %94 %98
%92 = OpAccessChain %99 %93 %100
-%101 = OpLoad %6 %92
+%101 = OpLoad %7 %92
%104 = OpAccessChain %105 %32 %106
%103 = OpAccessChain %107 %104 %108
%102 = OpAccessChain %109 %103 %110
-%111 = OpLoad %6 %102
+%111 = OpLoad %7 %102
%112 = OpCompositeConstruct %46 %91 %101 %111
%115 = OpAccessChain %116 %32 %117
%114 = OpAccessChain %118 %115 %119
%113 = OpAccessChain %120 %114 %121
-%122 = OpLoad %6 %113
+%122 = OpLoad %7 %113
%125 = OpAccessChain %126 %32 %127
%124 = OpAccessChain %128 %125 %129
%123 = OpAccessChain %130 %124 %131
-%132 = OpLoad %6 %123
+%132 = OpLoad %7 %123
%135 = OpAccessChain %136 %32 %137
%134 = OpAccessChain %138 %135 %139
%133 = OpAccessChain %140 %134 %141
-%142 = OpLoad %6 %133
+%142 = OpLoad %7 %133
%143 = OpCompositeConstruct %46 %122 %132 %142
%144 = OpCompositeConstruct %50 %81 %112 %143
%145 = OpTranspose %50 %144
-%146 = OpAccessChain %147 %12 %148
-%149 = OpLoad %6 %146
-%150 = OpAccessChain %151 %12 %152
-%153 = OpLoad %6 %150
-%154 = OpAccessChain %155 %12 %156
-%157 = OpLoad %6 %154
+%146 = OpAccessChain %147 %13 %148
+%149 = OpLoad %7 %146
+%150 = OpAccessChain %151 %13 %152
+%153 = OpLoad %7 %150
+%154 = OpAccessChain %155 %13 %156
+%157 = OpLoad %7 %154
%158 = OpCompositeConstruct %46 %149 %153 %157
%49 = OpMatrixTimesVector %46 %145 %158
OpStore %47 %49
-%163 = OpLoad %3 %9
-%164 = OpConvertSToF %6 %163
-%162 = OpFMul %6 %164 %5
-%161 = OpFSub %6 %162 %7
-%167 = OpLoad %3 %11
-%168 = OpConvertSToF %6 %167
-%166 = OpFMul %6 %168 %5
-%165 = OpFSub %6 %166 %7
-%169 = OpCompositeConstruct %13 %161 %165 %8 %7
+%163 = OpLoad %4 %10
+%164 = OpConvertSToF %7 %163
+%162 = OpFMul %7 %164 %6
+%161 = OpFSub %7 %162 %8
+%167 = OpLoad %4 %12
+%168 = OpConvertSToF %7 %167
+%166 = OpFMul %7 %168 %6
+%165 = OpFSub %7 %166 %8
+%169 = OpCompositeConstruct %14 %161 %165 %9 %8
OpStore %159 %169
OpReturn
OpFunctionEnd
-%170 = OpFunction %15 None %17
+%170 = OpFunction %0 None %17
%171 = OpLabel
%176 = OpLoad %173 %174
%181 = OpLoad %178 %179
%184 = OpLoad %46 %182
%185 = OpSampledImage %177 %176 %181
-%186 = OpImageSampleImplicitLod %13 %185 %184
+%186 = OpImageSampleImplicitLod %14 %185 %184
OpStore %172 %186
OpReturn
OpFunctionEnd
|
Turn function calls into statements
This would fix #416 naturally.
|
2021-02-05T23:56:01Z
|
0.3
|
2021-02-06T15:42:58Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"back::spv::writer::tests::test_write_physical_layout",
"back::spv::writer::tests::test_writer_generate_id",
"convert_wgsl_collatz",
"convert_wgsl_empty",
"convert_wgsl_shadow",
"convert_wgsl_boids",
"convert_wgsl_quad",
"convert_wgsl_skybox"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::spv::layout_tests::test_instruction_add_operand",
"back::spv::layout_tests::test_instruction_set_result",
"back::spv::layout_tests::test_instruction_add_operands",
"back::spv::layout_tests::test_instruction_set_type",
"back::spv::layout_tests::test_instruction_set_result_twice",
"back::spv::layout_tests::test_instruction_to_words",
"back::spv::layout_tests::test_instruction_set_type_twice",
"back::spv::layout_tests::test_physical_layout_in_words",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"back::spv::layout_tests::test_logical_layout_in_words",
"front::glsl::constants::tests::unary_op",
"front::spv::rosetta::simple",
"front::wgsl::lexer::test_tokens",
"front::spv::test::parse",
"front::glsl::lex_tests::tokens",
"front::glsl::preprocess_tests::preprocess",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_standard_fun",
"proc::interface::tests::global_use_scan",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_types",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::control_flow",
"parse_glsl"
] |
[] |
[] |
|
gfx-rs/naga
| 417
|
gfx-rs__naga-417
|
[
"412"
] |
c496c05ba413af699c1d2621ce741d45ab04d499
|
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1338,6 +1338,74 @@ impl<'a, W: Write> Writer<'a, W> {
}
write!(self.out, ")")?;
}
+ // Query translates into one of the:
+ // - textureSize/imageSize
+ // - textureQueryLevels
+ // - textureSamples/imageSamples
+ Expression::ImageQuery { image, query } => {
+ // This will only panic if the module is invalid
+ let (dim, class) = match ctx.typifier.get(image, &self.module.types) {
+ TypeInner::Image {
+ dim,
+ arrayed: _,
+ class,
+ } => (dim, class),
+ _ => unreachable!(),
+ };
+ let components = match dim {
+ crate::ImageDimension::D1 => 1,
+ crate::ImageDimension::D2 => 2,
+ crate::ImageDimension::D3 => 3,
+ crate::ImageDimension::Cube => 2,
+ };
+ match query {
+ crate::ImageQuery::Size { level } => {
+ match class {
+ ImageClass::Sampled { .. } | ImageClass::Depth => {
+ write!(self.out, "textureSize(")?;
+ self.write_expr(image, ctx)?;
+ write!(self.out, ",")?;
+ if let Some(expr) = level {
+ self.write_expr(expr, ctx)?;
+ } else {
+ write!(self.out, "0",)?;
+ }
+ }
+ ImageClass::Storage(_) => {
+ write!(self.out, "imageSize(")?;
+ self.write_expr(image, ctx)?;
+ }
+ }
+ write!(self.out, ").{}", &"xyz"[..components])?;
+ }
+ crate::ImageQuery::NumLevels => {
+ write!(self.out, "textureQueryLevels(",)?;
+ self.write_expr(image, ctx)?;
+ write!(self.out, ")",)?;
+ }
+ crate::ImageQuery::NumLayers => {
+ let selector = ['x', 'y', 'z', 'w'];
+ let fun_name = match class {
+ ImageClass::Sampled { .. } | ImageClass::Depth => "textureSize",
+ ImageClass::Storage(_) => "imageSize",
+ };
+ write!(self.out, "{}(", fun_name)?;
+ self.write_expr(image, ctx)?;
+ write!(self.out, ",0).{}", selector[components])?;
+ }
+ crate::ImageQuery::NumSamples => {
+ // assumes ARB_shader_texture_image_samples
+ let fun_name = match class {
+ ImageClass::Sampled { .. } | ImageClass::Depth => "textureSamples",
+ ImageClass::Storage(_) => "imageSamples",
+ };
+ write!(self.out, "{}(", fun_name)?;
+ self.write_expr(image, ctx)?;
+ write!(self.out, ")",)?;
+ }
+ }
+ return Err(Error::Custom("ImageQuery not implemented".to_string()));
+ }
// `Unary` is pretty straightforward
// "-" - for `Negate`
// "~" - for `Not` if it's an integer
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -143,6 +143,22 @@ impl<W: Write> Writer<W> {
Ok(())
}
+ fn put_image_query(
+ &mut self,
+ image: Handle<crate::Expression>,
+ query: &str,
+ level: Option<Handle<crate::Expression>>,
+ context: &ExpressionContext,
+ ) -> Result<(), Error> {
+ self.put_expression(image, context)?;
+ write!(self.out, ".get_{}(", query)?;
+ if let Some(expr) = level {
+ self.put_expression(expr, context)?;
+ }
+ write!(self.out, ")")?;
+ Ok(())
+ }
+
fn put_expression(
&mut self,
expr_handle: Handle<crate::Expression>,
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -331,6 +347,61 @@ impl<W: Write> Writer<W> {
}
write!(self.out, ")")?;
}
+ //Note: for all the queries, the signed integers are expected,
+ // so a conversion is needed.
+ crate::Expression::ImageQuery { image, query } => match query {
+ crate::ImageQuery::Size { level } => {
+ //Note: MSL only has separate width/height/depth queries,
+ // so compose the result of them.
+ let dim = match *self.typifier.get(image, &context.module.types) {
+ crate::TypeInner::Image { dim, .. } => dim,
+ ref other => unreachable!("Unexpected type {:?}", other),
+ };
+ match dim {
+ crate::ImageDimension::D1 => {
+ write!(self.out, "int(")?;
+ self.put_image_query(image, "width", level, context)?;
+ write!(self.out, ")")?;
+ }
+ crate::ImageDimension::D2 => {
+ write!(self.out, "int2(")?;
+ self.put_image_query(image, "width", level, context)?;
+ write!(self.out, ", ")?;
+ self.put_image_query(image, "height", level, context)?;
+ write!(self.out, ")")?;
+ }
+ crate::ImageDimension::D3 => {
+ write!(self.out, "int3(")?;
+ self.put_image_query(image, "width", level, context)?;
+ write!(self.out, ", ")?;
+ self.put_image_query(image, "height", level, context)?;
+ write!(self.out, ", ")?;
+ self.put_image_query(image, "depth", level, context)?;
+ write!(self.out, ")")?;
+ }
+ crate::ImageDimension::Cube => {
+ write!(self.out, "int(")?;
+ self.put_image_query(image, "width", level, context)?;
+ write!(self.out, ").xxx")?;
+ }
+ }
+ }
+ crate::ImageQuery::NumLevels => {
+ write!(self.out, "int(")?;
+ self.put_expression(image, context)?;
+ write!(self.out, ".get_num_mip_levels())")?;
+ }
+ crate::ImageQuery::NumLayers => {
+ write!(self.out, "int(")?;
+ self.put_expression(image, context)?;
+ write!(self.out, ".get_array_size())")?;
+ }
+ crate::ImageQuery::NumSamples => {
+ write!(self.out, "int(")?;
+ self.put_expression(image, context)?;
+ write!(self.out, ".get_num_samples())")?;
+ }
+ },
crate::Expression::Unary { op, expr } => {
let op_str = match op {
crate::UnaryOperator::Negate => "-",
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1113,6 +1113,90 @@ impl<I: Iterator<Item = u32>> Parser<I> {
},
);
}
+ Op::ImageQuerySize => {
+ inst.expect(4)?;
+ let result_type_id = self.next()?;
+ let result_id = self.next()?;
+ let image_id = self.next()?;
+
+ //TODO: handle arrays and cubes
+ let image_lexp = self.lookup_expression.lookup(image_id)?.clone();
+
+ let expr = crate::Expression::ImageQuery {
+ image: image_lexp.handle,
+ query: crate::ImageQuery::Size { level: None },
+ };
+ self.lookup_expression.insert(
+ result_id,
+ LookupExpression {
+ handle: expressions.append(expr),
+ type_id: result_type_id,
+ },
+ );
+ }
+ Op::ImageQuerySizeLod => {
+ inst.expect(5)?;
+ let result_type_id = self.next()?;
+ let result_id = self.next()?;
+ let image_id = self.next()?;
+ let level_id = self.next()?;
+
+ //TODO: handle arrays and cubes
+ let image_lexp = self.lookup_expression.lookup(image_id)?.clone();
+ let level_lexp = self.lookup_expression.lookup(level_id)?.clone();
+
+ let expr = crate::Expression::ImageQuery {
+ image: image_lexp.handle,
+ query: crate::ImageQuery::Size {
+ level: Some(level_lexp.handle),
+ },
+ };
+ self.lookup_expression.insert(
+ result_id,
+ LookupExpression {
+ handle: expressions.append(expr),
+ type_id: result_type_id,
+ },
+ );
+ }
+ Op::ImageQueryLevels => {
+ let result_type_id = self.next()?;
+ let result_id = self.next()?;
+ let image_id = self.next()?;
+
+ let image_lexp = self.lookup_expression.lookup(image_id)?.clone();
+
+ let expr = crate::Expression::ImageQuery {
+ image: image_lexp.handle,
+ query: crate::ImageQuery::NumLevels,
+ };
+ self.lookup_expression.insert(
+ result_id,
+ LookupExpression {
+ handle: expressions.append(expr),
+ type_id: result_type_id,
+ },
+ );
+ }
+ Op::ImageQuerySamples => {
+ let result_type_id = self.next()?;
+ let result_id = self.next()?;
+ let image_id = self.next()?;
+
+ let image_lexp = self.lookup_expression.lookup(image_id)?.clone();
+
+ let expr = crate::Expression::ImageQuery {
+ image: image_lexp.handle,
+ query: crate::ImageQuery::NumSamples,
+ };
+ self.lookup_expression.insert(
+ result_id,
+ LookupExpression {
+ handle: expressions.append(expr),
+ type_id: result_type_id,
+ },
+ );
+ }
Op::Select => {
inst.expect(6)?;
let result_type_id = self.next()?;
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -604,6 +604,52 @@ impl Parser {
index,
})
}
+ "textureDimensions" => {
+ lexer.expect(Token::Paren('('))?;
+ let image_name = lexer.next_ident()?;
+ let image = ctx.lookup_ident.lookup(image_name)?;
+ let level = if lexer.skip(Token::Separator(',')) {
+ let expr = self.parse_general_expression(lexer, ctx.reborrow())?;
+ Some(expr)
+ } else {
+ None
+ };
+ lexer.expect(Token::Paren(')'))?;
+ Some(crate::Expression::ImageQuery {
+ image,
+ query: crate::ImageQuery::Size { level },
+ })
+ }
+ "textureNumLevels" => {
+ lexer.expect(Token::Paren('('))?;
+ let image_name = lexer.next_ident()?;
+ let image = ctx.lookup_ident.lookup(image_name)?;
+ lexer.expect(Token::Paren(')'))?;
+ Some(crate::Expression::ImageQuery {
+ image,
+ query: crate::ImageQuery::NumLevels,
+ })
+ }
+ "textureNumLayers" => {
+ lexer.expect(Token::Paren('('))?;
+ let image_name = lexer.next_ident()?;
+ let image = ctx.lookup_ident.lookup(image_name)?;
+ lexer.expect(Token::Paren(')'))?;
+ Some(crate::Expression::ImageQuery {
+ image,
+ query: crate::ImageQuery::NumLayers,
+ })
+ }
+ "textureNumSamples" => {
+ lexer.expect(Token::Paren('('))?;
+ let image_name = lexer.next_ident()?;
+ let image = ctx.lookup_ident.lookup(image_name)?;
+ lexer.expect(Token::Paren(')'))?;
+ Some(crate::Expression::ImageQuery {
+ image,
+ query: crate::ImageQuery::NumSamples,
+ })
+ }
_ => {
match ctx.functions.iter().find(|(_, fun)| match fun.name {
Some(ref string) => string == name,
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -621,6 +621,24 @@ pub enum SampleLevel {
},
}
+/// Type of an image query.
+#[derive(Clone, Copy, Debug, PartialEq)]
+#[cfg_attr(feature = "serialize", derive(Serialize))]
+#[cfg_attr(feature = "deserialize", derive(Deserialize))]
+pub enum ImageQuery {
+ /// Get the size at the specified level.
+ Size {
+ /// If `None`, the base level is considered.
+ level: Option<Handle<Expression>>,
+ },
+ /// Get the number of mipmap levels.
+ NumLevels,
+ /// Get the number of array layers.
+ NumLayers,
+ /// Get the number of samples.
+ NumSamples,
+}
+
/// An expression that can be evaluated to obtain a value.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -671,6 +689,11 @@ pub enum Expression {
/// For multisampled images, this is Some(Sample).
index: Option<Handle<Expression>>,
},
+ /// Query information from an image.
+ ImageQuery {
+ image: Handle<Expression>,
+ query: ImageQuery,
+ },
/// Apply an unary operator.
Unary {
op: UnaryOperator,
diff --git a/src/proc/constants.rs b/src/proc/constants.rs
--- a/src/proc/constants.rs
+++ b/src/proc/constants.rs
@@ -120,8 +120,9 @@ impl<'a> ConstantSolver<'a> {
Expression::Call { .. } => Err(ConstantSolvingError::Call),
Expression::FunctionArgument(_) => Err(ConstantSolvingError::FunctionArg),
Expression::GlobalVariable(_) => Err(ConstantSolvingError::GlobalVariable),
- Expression::ImageSample { .. } => Err(ConstantSolvingError::ImageExpression),
- Expression::ImageLoad { .. } => Err(ConstantSolvingError::ImageExpression),
+ Expression::ImageSample { .. }
+ | Expression::ImageLoad { .. }
+ | Expression::ImageQuery { .. } => Err(ConstantSolvingError::ImageExpression),
}
}
diff --git a/src/proc/interface.rs b/src/proc/interface.rs
--- a/src/proc/interface.rs
+++ b/src/proc/interface.rs
@@ -85,6 +85,16 @@ where
self.traverse_expr(index);
}
}
+ E::ImageQuery { image, query } => {
+ self.traverse_expr(image);
+ match query {
+ crate::ImageQuery::Size { level: Some(expr) } => self.traverse_expr(expr),
+ crate::ImageQuery::Size { .. }
+ | crate::ImageQuery::NumLevels
+ | crate::ImageQuery::NumLayers
+ | crate::ImageQuery::NumSamples => (),
+ }
+ }
E::Unary { expr, .. } => {
self.traverse_expr(expr);
}
diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs
--- a/src/proc/typifier.rs
+++ b/src/proc/typifier.rs
@@ -204,6 +204,35 @@ impl Typifier {
}),
_ => unreachable!(),
},
+ crate::Expression::ImageQuery { image, query } => Resolution::Value(match query {
+ crate::ImageQuery::Size { level: _ } => match *self.get(image, types) {
+ crate::TypeInner::Image { dim, .. } => match dim {
+ crate::ImageDimension::D1 => crate::TypeInner::Scalar {
+ kind: crate::ScalarKind::Sint,
+ width: 4,
+ },
+ crate::ImageDimension::D2 => crate::TypeInner::Vector {
+ size: crate::VectorSize::Bi,
+ kind: crate::ScalarKind::Sint,
+ width: 4,
+ },
+ crate::ImageDimension::D3 | crate::ImageDimension::Cube => {
+ crate::TypeInner::Vector {
+ size: crate::VectorSize::Tri,
+ kind: crate::ScalarKind::Sint,
+ width: 4,
+ }
+ }
+ },
+ _ => unreachable!(),
+ },
+ crate::ImageQuery::NumLevels
+ | crate::ImageQuery::NumLayers
+ | crate::ImageQuery::NumSamples => crate::TypeInner::Scalar {
+ kind: crate::ScalarKind::Sint,
+ width: 4,
+ },
+ }),
crate::Expression::Unary { expr, .. } => self.resolutions[expr.index()].clone(),
crate::Expression::Binary { op, left, right } => match op {
crate::BinaryOperator::Add
|
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -155,7 +155,7 @@ fn parse_texture_load() {
"
var t: texture_multisampled_2d_array<i32>;
fn foo() {
- const r: vec4<i32> = textureLoad(t, vec2<i32>(10, 20), 2, 3);
+ const r: vec4<i32> = textureLoad(t, vec2<i32>(10, 20), 2, 3);
}
",
)
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -171,6 +171,22 @@ fn parse_texture_load() {
.unwrap();
}
+#[test]
+fn parse_texture_query() {
+ parse_str(
+ "
+ var t: texture_multisampled_2d_array<f32>;
+ fn foo() {
+ var dim: vec2<i32> = textureDimensions(t);
+ dim = textureDimensions(t, 0);
+ const layers: i32 = textureNumLayers(t);
+ const samples: i32 = textureNumSamples(t);
+ }
+ ",
+ )
+ .unwrap();
+}
+
#[test]
fn parse_postfix() {
parse_str("fn foo() { const x: f32 = vec4<f32>(1.0, 2.0, 3.0, 4.0).xyz.rgbr.aaaa.wz.g; }")
|
Image queries
Getting the size, LOD count, sample counts of images.
|
2021-02-05T15:06:03Z
|
0.3
|
2021-02-05T20:26:49Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"front::wgsl::tests::parse_texture_query"
] |
[
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout_tests::test_instruction_set_type",
"back::spv::layout_tests::test_instruction_set_result_twice",
"back::spv::layout_tests::test_instruction_set_result",
"back::spv::layout_tests::test_instruction_add_operand",
"back::spv::layout_tests::test_instruction_to_words",
"back::spv::layout_tests::test_instruction_add_operands",
"back::spv::layout_tests::test_instruction_set_type_twice",
"back::spv::layout_tests::test_physical_layout_in_words",
"back::spv::writer::tests::test_write_physical_layout",
"back::spv::writer::tests::test_writer_generate_id",
"back::spv::layout_tests::test_logical_layout_in_words",
"front::spv::rosetta::simple",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::glsl::lex_tests::tokens",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_if",
"front::glsl::preprocess_tests::preprocess",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::version",
"proc::constants::tests::cast",
"proc::constants::tests::unary_op",
"front::wgsl::tests::parse_switch",
"proc::constants::tests::access",
"proc::interface::tests::global_use_scan",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::control_flow",
"parse_glsl",
"convert_wgsl_collatz",
"convert_wgsl_empty",
"convert_wgsl_shadow",
"convert_wgsl_boids",
"convert_wgsl_quad",
"convert_wgsl_skybox"
] |
[] |
[] |
|
gfx-rs/naga
| 377
|
gfx-rs__naga-377
|
[
"367"
] |
292304b66f27c7f07b855c929bdf671c14dd904d
|
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -265,24 +265,31 @@ enum Composition {
}
impl Composition {
+ //TODO: could be `const fn` once MSRV allows
+ fn letter_pos(letter: char) -> u32 {
+ match letter {
+ 'x' | 'r' => 0,
+ 'y' | 'g' => 1,
+ 'z' | 'b' => 2,
+ 'w' | 'a' => 3,
+ _ => !0,
+ }
+ }
+
fn make<'a>(
base: Handle<crate::Expression>,
base_size: crate::VectorSize,
name: &'a str,
expressions: &mut Arena<crate::Expression>,
) -> Result<Self, Error<'a>> {
- const MEMBERS: [char; 4] = ['x', 'y', 'z', 'w'];
-
Ok(if name.len() > 1 {
let mut components = Vec::with_capacity(name.len());
for ch in name.chars() {
- let expr = crate::Expression::AccessIndex {
- base,
- index: MEMBERS[..base_size as usize]
- .iter()
- .position(|&m| m == ch)
- .ok_or(Error::BadAccessor(name))? as u32,
- };
+ let index = Self::letter_pos(ch);
+ if index >= base_size as u32 {
+ return Err(Error::BadAccessor(name));
+ }
+ let expr = crate::Expression::AccessIndex { base, index };
components.push(expressions.append(expr));
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -295,10 +302,10 @@ impl Composition {
Composition::Multi(size, components)
} else {
let ch = name.chars().next().ok_or(Error::BadAccessor(name))?;
- let index = MEMBERS[..base_size as usize]
- .iter()
- .position(|&m| m == ch)
- .ok_or(Error::BadAccessor(name))? as u32;
+ let index = Self::letter_pos(ch);
+ if index >= base_size as u32 {
+ return Err(Error::BadAccessor(name));
+ }
Composition::Single(crate::Expression::AccessIndex { base, index })
})
}
|
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -150,5 +150,7 @@ fn parse_texture_load() {
#[test]
fn parse_postfix() {
+ parse_str("fn foo() { const x: f32 = vec4<f32>(1.0, 2.0, 3.0, 4.0).xyz.rgbr.aaaa.wz.g; }")
+ .unwrap();
parse_str("fn foo() { const x: f32 = fract(vec2<f32>(0.5, 1.0)).x; }").unwrap();
}
|
Accessor rgba doesn't work
` ParseError { error: BadAccessor("r"), scopes: [FunctionDecl, Block, Statement, GeneralExpr, SingularExpr], pos: (36, 32) }'`
It seems it is supposed to according to the specs.
```wgsl
fn main() {
var test: vec2<f32> = vec2<f32>(1.0, 1.0);
out_target = vec4<f32>( test.r, 1.0, 0.0 , 1.0);
}
```
|
2021-01-27T05:55:16Z
|
0.2
|
2021-01-26T22:04:17Z
|
292304b66f27c7f07b855c929bdf671c14dd904d
|
[
"front::wgsl::tests::parse_postfix"
] |
[
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::spv::layout_tests::test_instruction_add_operand",
"back::spv::layout_tests::test_instruction_set_result",
"back::spv::layout_tests::test_instruction_add_operands",
"back::spv::layout_tests::test_instruction_set_type",
"back::spv::layout_tests::test_instruction_to_words",
"back::spv::layout_tests::test_physical_layout_in_words",
"back::spv::layout_tests::test_instruction_set_result_twice",
"back::spv::layout_tests::test_instruction_set_type_twice",
"back::spv::writer::tests::test_write_physical_layout",
"back::spv::writer::tests::test_writer_generate_id",
"back::spv::layout_tests::test_logical_layout_in_words",
"front::spv::rosetta::simple",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::spv::test::parse",
"front::wgsl::tests::parse_comment",
"front::glsl::lex_tests::tokens",
"front::glsl::preprocess_tests::preprocess",
"front::wgsl::tests::parse_if",
"proc::interface::tests::global_use_scan",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_switch",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::control_flow",
"parse_glsl",
"convert_wgsl_collatz",
"convert_wgsl_boids",
"convert_wgsl_empty",
"convert_wgsl_quad",
"convert_wgsl_skybox"
] |
[] |
[] |
|
gfx-rs/naga
| 376
|
gfx-rs__naga-376
|
[
"368"
] |
986550aff8767fe541fb9e2fc3a7e01e16f1dc21
|
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -947,12 +947,13 @@ impl Parser {
Some(expr) => ctx.expressions.append(expr),
None => {
*lexer = backup;
- let handle = self.parse_primary_expression(lexer, ctx.reborrow())?;
- self.parse_postfix(lexer, ctx, handle)?
+ self.parse_primary_expression(lexer, ctx.reborrow())?
}
};
+
+ let post_handle = self.parse_postfix(lexer, ctx, handle)?;
self.scopes.pop();
- Ok(handle)
+ Ok(post_handle)
}
fn parse_equality_expression<'a>(
|
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -147,3 +147,8 @@ fn parse_texture_load() {
)
.unwrap();
}
+
+#[test]
+fn parse_postfix() {
+ parse_str("fn foo() { const x: f32 = fract(vec2<f32>(0.5, 1.0)).x; }").unwrap();
+}
|
Cannot swizzle the return value of a function
I couldn't swizzle function return values such as `textureSample( ... ).x`
`ParseError { error: Unexpected(Separator('.')), scopes: [FunctionDecl, Block, Statement], pos: (34, 86) }',`
```wgsl
[[stage(fragment)]]
fn main() {
var test: vec2<f32> = vec2<f32>(1.0, 1.0);
out_target = vec4<f32>( fract(test).x, 1.0, 0.0, 1.0);
}
```
|
2021-01-27T05:40:56Z
|
0.2
|
2021-01-26T21:44:23Z
|
292304b66f27c7f07b855c929bdf671c14dd904d
|
[
"front::wgsl::tests::parse_postfix"
] |
[
"arena::tests::append_unique",
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::spv::layout_tests::test_instruction_add_operand",
"back::spv::layout_tests::test_instruction_add_operands",
"back::spv::layout_tests::test_instruction_set_result",
"back::spv::layout_tests::test_instruction_set_type",
"back::spv::layout_tests::test_instruction_to_words",
"back::spv::layout_tests::test_physical_layout_in_words",
"back::spv::layout_tests::test_instruction_set_type_twice",
"back::spv::layout_tests::test_instruction_set_result_twice",
"back::spv::writer::tests::test_writer_generate_id",
"back::spv::writer::tests::test_write_physical_layout",
"back::spv::layout_tests::test_logical_layout_in_words",
"front::spv::rosetta::simple",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::glsl::lex_tests::tokens",
"front::wgsl::tests::parse_comment",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::version",
"front::glsl::preprocess_tests::preprocess",
"proc::interface::tests::global_use_scan",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::control_flow",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_texture_load",
"parse_glsl",
"convert_wgsl_collatz",
"convert_wgsl_boids",
"convert_wgsl_empty",
"convert_wgsl_quad",
"convert_wgsl_skybox"
] |
[] |
[] |
|
gfx-rs/naga
| 187
|
gfx-rs__naga-187
|
[
"100"
] |
0129aa2ca699070497e7d0c6c749fc872e395623
|
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -34,5 +34,5 @@ wgsl-in = []
[dev-dependencies]
difference = "2.0"
env_logger = "0.6"
-ron = "0.5"
+ron = "0.6"
serde = { version = "1.0", features = ["derive"] }
diff --git a/examples/convert.rs b/examples/convert.rs
--- a/examples/convert.rs
+++ b/examples/convert.rs
@@ -181,7 +181,11 @@ fn main() {
}
#[cfg(feature = "serialize")]
"ron" => {
- let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap();
+ let config = ron::ser::PrettyConfig::new()
+ .with_enumerate_arrays(true)
+ .with_decimal_floats(true);
+
+ let output = ron::ser::to_string_pretty(&module, config).unwrap();
fs::write(&args[2], output).unwrap();
}
other => {
diff --git a/src/back/msl.rs b/src/back/msl.rs
--- a/src/back/msl.rs
+++ b/src/back/msl.rs
@@ -546,6 +546,19 @@ impl<W: Write> Writer<W> {
&crate::TypeInner::Vector { size, kind, width },
&crate::TypeInner::Vector { .. },
) => MaybeOwned::Owned(crate::TypeInner::Vector { size, kind, width }),
+ (
+ &crate::TypeInner::Matrix {
+ rows,
+ columns: _,
+ kind,
+ width,
+ },
+ &crate::TypeInner::Vector { .. },
+ ) => MaybeOwned::Owned(crate::TypeInner::Vector {
+ size: rows,
+ kind,
+ width,
+ }),
(_, _) => {
return Err(Error::UnableToInferBinaryOpOutput(ty_left, op, ty_right))
}
diff --git a/src/back/msl.rs b/src/back/msl.rs
--- a/src/back/msl.rs
+++ b/src/back/msl.rs
@@ -702,7 +715,16 @@ impl<W: Write> Writer<W> {
write!(self.out, ")")?;
Ok(MaybeOwned::Owned(result))
}
-
+ "mix" => {
+ write!(self.out, "mix(")?;
+ let result = self.put_expression(arguments[0], function, module)?;
+ write!(self.out, ", ")?;
+ self.put_expression(arguments[1], function, module)?;
+ write!(self.out, ", ")?;
+ self.put_expression(arguments[2], function, module)?;
+ write!(self.out, ")")?;
+ Ok(result)
+ }
other => Err(Error::UnsupportedCall(other.to_owned())),
},
ref other => Err(Error::UnsupportedExpression(other.clone())),
diff --git a/src/front/mod.rs b/src/front/mod.rs
--- a/src/front/mod.rs
+++ b/src/front/mod.rs
@@ -11,6 +11,7 @@ use crate::arena::Arena;
pub const GENERATOR: u32 = 0;
+#[allow(dead_code)]
impl crate::Module {
fn from_header(header: crate::Header) -> Self {
crate::Module {
diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs
--- a/src/front/spv/error.rs
+++ b/src/front/spv/error.rs
@@ -35,8 +35,6 @@ pub enum Error {
InvalidAccessType(spirv::Word),
InvalidAccess(Handle<crate::Expression>),
InvalidAccessIndex(spirv::Word),
- InvalidLoadType(spirv::Word),
- InvalidStoreType(spirv::Word),
InvalidBinding(spirv::Word),
InvalidImageExpression(Handle<crate::Expression>),
InvalidImageBaseType(Handle<crate::Type>),
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -119,7 +119,7 @@ pub fn parse_function<I: Iterator<Item = u32>>(
// Scan the blocks and add them as nodes
loop {
let fun_inst = parser.next_inst()?;
- log::debug!("\t\t{:?}", fun_inst.op);
+ log::debug!("{:?}", fun_inst.op);
match fun_inst.op {
spirv::Op::Label => {
// Read the label ID
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -254,7 +256,7 @@ struct EntryPoint {
variable_ids: Vec<spirv::Word>,
}
-#[derive(Debug)]
+#[derive(Clone, Debug)]
struct LookupType {
handle: Handle<crate::Type>,
base_id: Option<spirv::Word>,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -302,7 +304,7 @@ pub struct Parser<I> {
ext_glsl_id: Option<spirv::Word>,
future_decor: FastHashMap<spirv::Word, Decoration>,
future_member_decor: FastHashMap<(spirv::Word, MemberIndex), Decoration>,
- lookup_member_type_id: FastHashMap<(spirv::Word, MemberIndex), spirv::Word>,
+ lookup_member_type_id: FastHashMap<(Handle<crate::Type>, MemberIndex), spirv::Word>,
handle_sampling: FastHashMap<Handle<crate::Type>, SamplingFlags>,
lookup_type: FastHashMap<spirv::Word, LookupType>,
lookup_void_type: FastHashSet<spirv::Word>,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -603,15 +605,14 @@ impl<I: Iterator<Item = u32>> Parser<I> {
log::trace!("\t\t\tlooking up expr {:?}", base_id);
let mut acex = {
let expr = self.lookup_expression.lookup(base_id)?;
- let ptr_type = self.lookup_type.lookup(expr.type_id)?;
AccessExpression {
base_handle: expr.handle,
- type_id: ptr_type.base_id.unwrap(),
+ type_id: expr.type_id,
}
};
for _ in 4..inst.wc {
let access_id = self.next()?;
- log::trace!("\t\t\tlooking up expr {:?}", access_id);
+ log::trace!("\t\t\tlooking up index expr {:?}", access_id);
let index_expr = self.lookup_expression.lookup(access_id)?.clone();
let index_type_handle = self.lookup_type.lookup(index_expr.type_id)?.handle;
match type_arena[index_type_handle].inner {
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -650,7 +651,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
),
type_id: *self
.lookup_member_type_id
- .get(&(acex.type_id, index))
+ .get(&(type_lookup.handle, index))
.ok_or(Error::InvalidAccessType(acex.type_id))?,
}
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -695,7 +696,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
let type_id = match type_arena[type_lookup.handle].inner {
crate::TypeInner::Struct { .. } => *self
.lookup_member_type_id
- .get(&(lexp.type_id, index))
+ .get(&(type_lookup.handle, index))
.ok_or(Error::InvalidAccessType(lexp.type_id))?,
crate::TypeInner::Array { .. }
| crate::TypeInner::Vector { .. }
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -753,22 +754,11 @@ impl<I: Iterator<Item = u32>> Parser<I> {
inst.expect(5)?;
let _memory_access = self.next()?;
}
- let base_expr = self.lookup_expression.lookup(pointer_id)?;
- let base_type = self.lookup_type.lookup(base_expr.type_id)?;
- if base_type.base_id != Some(result_type_id) {
- return Err(Error::InvalidLoadType(result_type_id));
- }
- match type_arena[base_type.handle].inner {
- crate::TypeInner::Pointer { .. } => (),
- _ => return Err(Error::UnsupportedType(base_type.handle)),
- }
- let expr = crate::Expression::Load {
- pointer: base_expr.handle,
- };
+ let base_expr = self.lookup_expression.lookup(pointer_id)?.clone();
self.lookup_expression.insert(
result_id,
LookupExpression {
- handle: expressions.append(expr),
+ handle: base_expr.handle, // pass-through pointers
type_id: result_type_id,
},
);
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -782,15 +772,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
let _memory_access = self.next()?;
}
let base_expr = self.lookup_expression.lookup(pointer_id)?;
- let base_type = self.lookup_type.lookup(base_expr.type_id)?;
- match type_arena[base_type.handle].inner {
- crate::TypeInner::Pointer { .. } => (),
- _ => return Err(Error::UnsupportedType(base_type.handle)),
- };
let value_expr = self.lookup_expression.lookup(value_id)?;
- if base_type.base_id != Some(value_expr.type_id) {
- return Err(Error::InvalidStoreType(value_expr.type_id));
- }
assignments.push(Assignment {
to: base_expr.handle,
value: value_expr.handle,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -1923,27 +1905,15 @@ impl<I: Iterator<Item = u32>> Parser<I> {
fn parse_type_pointer(
&mut self,
inst: Instruction,
- module: &mut crate::Module,
+ _module: &mut crate::Module,
) -> Result<(), Error> {
self.switch(ModuleState::Type, inst.op)?;
inst.expect(4)?;
let id = self.next()?;
- let storage = self.next()?;
+ let _storage = self.next()?;
let type_id = self.next()?;
- let inner = crate::TypeInner::Pointer {
- base: self.lookup_type.lookup(type_id)?.handle,
- class: map_storage_class(storage)?,
- };
- self.lookup_type.insert(
- id,
- LookupType {
- handle: module.types.append(crate::Type {
- name: self.future_decor.remove(&id).and_then(|dec| dec.name),
- inner,
- }),
- base_id: Some(type_id),
- },
- );
+ let type_lookup = self.lookup_type.lookup(type_id)?.clone();
+ self.lookup_type.insert(id, type_lookup); // don't register pointers in the IR
Ok(())
}
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2020,11 +1990,13 @@ impl<I: Iterator<Item = u32>> Parser<I> {
// do nothing
}
}
+
let mut members = Vec::with_capacity(inst.wc as usize - 2);
+ let mut member_type_ids = Vec::with_capacity(members.capacity());
for i in 0..u32::from(inst.wc) - 2 {
let type_id = self.next()?;
+ member_type_ids.push(type_id);
let ty = self.lookup_type.lookup(type_id)?.handle;
- self.lookup_member_type_id.insert((id, i), type_id);
let decor = self
.future_member_decor
.remove(&(id, i))
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2037,13 +2009,19 @@ impl<I: Iterator<Item = u32>> Parser<I> {
});
}
let inner = crate::TypeInner::Struct { members };
+ let ty_handle = module.types.append(crate::Type {
+ name: parent_decor.and_then(|dec| dec.name),
+ inner,
+ });
+
+ for (i, type_id) in member_type_ids.into_iter().enumerate() {
+ self.lookup_member_type_id
+ .insert((ty_handle, i as u32), type_id);
+ }
self.lookup_type.insert(
id,
LookupType {
- handle: module.types.append(crate::Type {
- name: parent_decor.and_then(|dec| dec.name),
- inner,
- }),
+ handle: ty_handle,
base_id: None,
},
);
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2278,20 +2256,17 @@ impl<I: Iterator<Item = u32>> Parser<I> {
.future_decor
.remove(&id)
.ok_or(Error::InvalidBinding(id))?;
- let (ty, binding) = match module.types[lookup_type.handle].inner {
- crate::TypeInner::Pointer { base, class } => {
- let binding = match (class, &module.types[base].inner) {
- (crate::StorageClass::Input, &crate::TypeInner::Struct { .. })
- | (crate::StorageClass::Output, &crate::TypeInner::Struct { .. }) => None,
- _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?),
- };
- (base, binding)
- }
- _ => return Err(Error::UnsupportedType(lookup_type.handle)),
- };
let class = map_storage_class(storage)?;
- let is_storage = match module.types[ty].inner {
- crate::TypeInner::Struct { .. } => class == crate::StorageClass::StorageBuffer,
+ let binding = match (class, &module.types[lookup_type.handle].inner) {
+ (crate::StorageClass::Input, &crate::TypeInner::Struct { .. })
+ | (crate::StorageClass::Output, &crate::TypeInner::Struct { .. }) => None,
+ _ => Some(dec.get_binding().ok_or(Error::InvalidBinding(id))?),
+ };
+ let is_storage = match module.types[lookup_type.handle].inner {
+ crate::TypeInner::Struct { .. } => match class {
+ crate::StorageClass::StorageBuffer | crate::StorageClass::Constant => true, // careful with `Constant` here!
+ _ => false,
+ },
crate::TypeInner::Image {
class: crate::ImageClass::Storage(_),
..
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2316,7 +2291,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
name: dec.name,
class,
binding,
- ty,
+ ty: lookup_type.handle,
interpolation: dec.interpolation,
storage_access,
};
|
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -15,6 +15,8 @@ mod convert;
mod error;
mod flow;
mod function;
+#[cfg(test)]
+mod rosetta;
use convert::*;
use error::Error;
diff --git /dev/null b/src/front/spv/rosetta.rs
new file mode 100644
--- /dev/null
+++ b/src/front/spv/rosetta.rs
@@ -0,0 +1,24 @@
+use std::{fs, path::Path};
+
+const TEST_PATH: &str = "test-data";
+
+fn rosetta_test(file_name: &str) {
+ if true {
+ return; //TODO: fix this test
+ }
+ let test_dir = Path::new(TEST_PATH);
+ let input = fs::read(test_dir.join(file_name)).unwrap();
+
+ let module = super::parse_u8_slice(&input).unwrap();
+ let output = ron::ser::to_string_pretty(&module, Default::default()).unwrap();
+
+ let expected =
+ fs::read_to_string(test_dir.join(file_name).with_extension("expected.ron")).unwrap();
+
+ difference::assert_diff!(output.as_str(), expected.as_str(), "", 0);
+}
+
+#[test]
+fn simple() {
+ rosetta_test("simple/simple.spv")
+}
diff --git a/tests/convert.rs b/tests/convert.rs
--- a/tests/convert.rs
+++ b/tests/convert.rs
@@ -105,6 +105,43 @@ fn convert_cube() {
validator.validate(&vs).unwrap();
let fs = load_spv("cube.frag.spv");
validator.validate(&fs).unwrap();
+
+ {
+ use naga::back::msl;
+ let mut binding_map = msl::BindingMap::default();
+ binding_map.insert(
+ msl::BindSource { set: 0, binding: 0 },
+ msl::BindTarget {
+ buffer: Some(0),
+ texture: None,
+ sampler: None,
+ mutable: false,
+ },
+ );
+ binding_map.insert(
+ msl::BindSource { set: 0, binding: 1 },
+ msl::BindTarget {
+ buffer: None,
+ texture: Some(1),
+ sampler: None,
+ mutable: false,
+ },
+ );
+ binding_map.insert(
+ msl::BindSource { set: 0, binding: 2 },
+ msl::BindTarget {
+ buffer: None,
+ texture: None,
+ sampler: Some(1),
+ mutable: false,
+ },
+ );
+ let options = msl::Options {
+ binding_map: &binding_map,
+ };
+ msl::write_string(&vs, options).unwrap();
+ msl::write_string(&fs, options).unwrap();
+ }
}
#[cfg(feature = "glsl-in")]
|
Don't use pointers for accessing global variables
In spir-v any access to variables is done via load/stores in pointers. In WGSL that pointer step is skipped.
I think we should change the SPIR-V front-end to ignore the indirection, and write the IR validation accordingly (#59).
|
2020-09-11T04:27:23Z
|
0.2
|
2020-09-11T19:24:43Z
|
292304b66f27c7f07b855c929bdf671c14dd904d
|
[
"convert_cube"
] |
[
"arena::tests::append_non_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"back::spv::instructions::tests::test_instruction_capability",
"back::spv::instructions::tests::test_instruction_constant",
"back::spv::instructions::tests::test_instruction_constant_composite",
"back::spv::instructions::tests::test_instruction_constant_false",
"back::spv::instructions::tests::test_instruction_composite_construct",
"back::spv::instructions::tests::test_instruction_constant_true",
"back::spv::instructions::tests::test_instruction_decorate",
"back::spv::instructions::tests::test_instruction_entry_point",
"back::spv::instructions::tests::test_instruction_execution_mode",
"back::spv::instructions::tests::test_instruction_ext_inst_import",
"back::spv::instructions::tests::test_instruction_function",
"back::spv::instructions::tests::test_instruction_function_call",
"back::spv::instructions::tests::test_instruction_function_end",
"back::spv::instructions::tests::test_instruction_function_parameter",
"back::spv::instructions::tests::test_instruction_label",
"back::spv::instructions::tests::test_instruction_load",
"back::spv::instructions::tests::test_instruction_memory_model",
"back::spv::instructions::tests::test_instruction_name",
"back::spv::instructions::tests::test_instruction_return",
"back::spv::instructions::tests::test_instruction_return_value",
"back::spv::instructions::tests::test_instruction_source",
"back::spv::instructions::tests::test_instruction_store",
"back::spv::instructions::tests::test_instruction_type_array",
"back::spv::instructions::tests::test_instruction_type_bool",
"back::spv::instructions::tests::test_instruction_type_float",
"back::spv::instructions::tests::test_instruction_type_function",
"back::spv::instructions::tests::test_instruction_type_image",
"back::spv::instructions::tests::test_instruction_type_int",
"back::spv::instructions::tests::test_instruction_type_matrix",
"back::spv::instructions::tests::test_instruction_type_pointer",
"back::spv::instructions::tests::test_instruction_type_runtime_array",
"back::spv::instructions::tests::test_instruction_type_sampler",
"back::spv::instructions::tests::test_instruction_type_struct",
"back::spv::instructions::tests::test_instruction_type_vector",
"back::spv::instructions::tests::test_instruction_type_void",
"back::spv::instructions::tests::test_instruction_variable",
"back::spv::instructions::tests::test_instruction_vector_times_scalar",
"back::spv::layout_tests::test_instruction_add_operand",
"back::spv::layout_tests::test_instruction_add_operands",
"back::spv::layout_tests::test_instruction_set_result",
"back::spv::layout_tests::test_instruction_set_type",
"back::spv::layout_tests::test_instruction_to_words",
"back::spv::layout_tests::test_instruction_set_type_twice",
"back::spv::layout_tests::test_instruction_set_result_twice",
"back::spv::layout_tests::test_physical_layout_in_words",
"back::spv::writer::tests::test_write_physical_layout",
"back::spv::writer::tests::test_try_add_capabilities",
"back::spv::writer::tests::test_writer_generate_id",
"back::spv::layout_tests::test_logical_layout_in_words",
"front::glsl::lex_tests::glsl_lex_identifier",
"front::glsl::lex_tests::glsl_lex_line_comment",
"front::glsl::lex_tests::glsl_lex_simple",
"front::glsl::lex_tests::glsl_lex_multi_line_comment",
"front::spv::rosetta::simple",
"front::glsl::lex_tests::glsl_lex_version",
"front::spv::test::parse",
"front::wgsl::tests::check_constant_type_scalar_err",
"front::glsl::parser_tests::glsl_parser_version_invalid",
"front::wgsl::tests::check_constant_type_scalar_ok",
"front::wgsl::tests::check_lexer",
"front::glsl::parser_tests::glsl_parser_version_valid",
"proc::interface::tests::global_use_scan",
"back::spv::rosetta_tests::simple",
"front::wgsl::rosetta_tests::simple",
"front::glsl::rosetta_tests::simple",
"convert_quad",
"convert_boids"
] |
[] |
[] |
|
gfx-rs/naga
| 817
|
gfx-rs__naga-817
|
[
"583"
] |
bb7ebed23a0cdd3cf7d62b927f3a4483f90d82d2
|
diff --git a/src/back/dot/mod.rs b/src/back/dot/mod.rs
--- a/src/back/dot/mod.rs
+++ b/src/back/dot/mod.rs
@@ -42,6 +42,7 @@ impl StatementGraph {
S::Break => "Break", //TODO: loop context
S::Continue => "Continue", //TODO: loop context
S::Kill => "Kill", //TODO: link to the beginning
+ S::Barrier(_flags) => "Barrier",
S::Block(ref b) => {
let other = self.add(b);
self.flow.push((id, other, ""));
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -1398,9 +1398,15 @@ impl<'a, W: Write> Writer<'a, W> {
// This is one of the places were glsl adds to the syntax of C in this case the discard
// keyword which ceases all further processing in a fragment shader, it's called OpKill
// in spir-v that's why it's called `Statement::Kill`
- Statement::Kill => {
- write!(self.out, "{}", INDENT.repeat(indent))?;
- writeln!(self.out, "discard;")?
+ Statement::Kill => writeln!(self.out, "{}discard;", INDENT.repeat(indent))?,
+ // Just issue a memory barrier, ignoring the flags.
+ Statement::Barrier(flags) => {
+ if flags.contains(crate::Barrier::WORK_GROUP) {
+ writeln!(self.out, "{}barrier();", INDENT.repeat(indent))?;
+ }
+ if flags.contains(crate::Barrier::STORAGE) {
+ writeln!(self.out, "{}groupMemoryBarrier();", INDENT.repeat(indent))?;
+ }
}
// Stores in glsl are just variable assignments written as `pointer = value;`
Statement::Store { pointer, value } => {
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -1347,6 +1347,22 @@ impl<W: Write> Writer<W> {
crate::Statement::Kill => {
writeln!(self.out, "{}{}::discard_fragment();", level, NAMESPACE)?;
}
+ crate::Statement::Barrier(flags) => {
+ if flags.contains(crate::Barrier::STORAGE) {
+ writeln!(
+ self.out,
+ "{}{}::threadgroup_barrier({}::mem_flags::mem_device);",
+ level, NAMESPACE, NAMESPACE,
+ )?;
+ }
+ if flags.contains(crate::Barrier::WORK_GROUP) {
+ writeln!(
+ self.out,
+ "{}{}::threadgroup_barrier({}::mem_flags::mem_threadgroup);",
+ level, NAMESPACE, NAMESPACE,
+ )?;
+ }
+ }
crate::Statement::Store { pointer, value } => {
// we can't assign fixed-size arrays
let pointer_info = &context.expression.info[pointer];
diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs
--- a/src/back/spv/instructions.rs
+++ b/src/back/spv/instructions.rs
@@ -853,4 +853,18 @@ impl super::Instruction {
//
// Primitive Instructions
//
+
+ // Barriers
+
+ pub(super) fn control_barrier(
+ exec_scope_id: Word,
+ mem_scope_id: Word,
+ semantics_id: Word,
+ ) -> Self {
+ let mut instruction = Self::new(Op::ControlBarrier);
+ instruction.add_operand(exec_scope_id);
+ instruction.add_operand(mem_scope_id);
+ instruction.add_operand(semantics_id);
+ instruction
+ }
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -12,7 +12,6 @@ use std::{collections::hash_map::Entry, ops};
use thiserror::Error;
const BITS_PER_BYTE: crate::Bytes = 8;
-const CACHED_CONSTANT_INDICES: usize = 8;
#[derive(Clone, Debug, Error)]
pub enum Error {
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -295,7 +294,7 @@ pub struct Writer {
lookup_function_type: crate::FastHashMap<LookupFunctionType, Word>,
lookup_function_call: crate::FastHashMap<Handle<crate::Expression>, Word>,
constant_ids: Vec<Word>,
- index_constant_ids: Vec<Word>,
+ cached_constants: crate::FastHashMap<(crate::ScalarValue, crate::Bytes), Word>,
global_variables: Vec<GlobalVariable>,
cached: CachedExpressions,
gl450_ext_inst_id: Word,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -336,7 +335,7 @@ impl Writer {
lookup_function_type: crate::FastHashMap::default(),
lookup_function_call: crate::FastHashMap::default(),
constant_ids: Vec::new(),
- index_constant_ids: Vec::new(),
+ cached_constants: crate::FastHashMap::default(),
global_variables: Vec::new(),
cached: CachedExpressions::default(),
gl450_ext_inst_id,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -415,41 +414,6 @@ impl Writer {
})
}
- fn create_constant(&mut self, type_id: Word, value: &[Word]) -> Word {
- let id = self.id_gen.next();
- let instruction = Instruction::constant(type_id, id, value);
- instruction.to_words(&mut self.logical_layout.declarations);
- id
- }
-
- fn get_index_constant(
- &mut self,
- index: Word,
- types: &Arena<crate::Type>,
- ) -> Result<Word, Error> {
- while self.index_constant_ids.len() <= index as usize {
- self.index_constant_ids.push(0);
- }
- let cached = self.index_constant_ids[index as usize];
- if cached != 0 {
- return Ok(cached);
- }
-
- let type_id = self.get_type_id(
- types,
- LookupType::Local(LocalType::Value {
- vector_size: None,
- kind: crate::ScalarKind::Sint,
- width: 4,
- pointer_class: None,
- }),
- )?;
-
- let id = self.create_constant(type_id, &[index]);
- self.index_constant_ids[index as usize] = id;
- Ok(id)
- }
-
fn decorate(&mut self, id: Word, decoration: spirv::Decoration, operands: &[Word]) {
self.annotations
.push(Instruction::decorate(id, decoration, operands));
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1019,6 +983,29 @@ impl Writer {
Ok(id)
}
+ fn get_index_constant(
+ &mut self,
+ index: Word,
+ types: &Arena<crate::Type>,
+ ) -> Result<Word, Error> {
+ self.get_constant_scalar(crate::ScalarValue::Uint(index as _), 4, types)
+ }
+
+ fn get_constant_scalar(
+ &mut self,
+ value: crate::ScalarValue,
+ width: crate::Bytes,
+ types: &Arena<crate::Type>,
+ ) -> Result<Word, Error> {
+ if let Some(&id) = self.cached_constants.get(&(value, width)) {
+ return Ok(id);
+ }
+ let id = self.id_gen.next();
+ self.write_constant_scalar(id, &value, width, None, types)?;
+ self.cached_constants.insert((value, width), id);
+ Ok(id)
+ }
+
fn write_constant_scalar(
&mut self,
id: Word,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1046,17 +1033,6 @@ impl Writer {
crate::ScalarValue::Sint(val) => {
let words = match width {
4 => {
- if debug_name.is_none()
- && 0 <= val
- && val < CACHED_CONSTANT_INDICES as i64
- && self.index_constant_ids.get(val as usize).unwrap_or(&0) == &0
- {
- // cache this as an indexing constant
- while self.index_constant_ids.len() <= val as usize {
- self.index_constant_ids.push(0);
- }
- self.index_constant_ids[val as usize] = id;
- }
solo = [val as u32];
&solo[..]
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2063,13 +2039,9 @@ impl Writer {
depth_id,
);
- //TODO: cache this!
- let zero_id = self.id_gen.next();
- self.write_constant_scalar(
- zero_id,
- &crate::ScalarValue::Float(0.0),
+ let zero_id = self.get_constant_scalar(
+ crate::ScalarValue::Float(0.0),
4,
- None,
&ir_module.types,
)?;
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2794,6 +2766,33 @@ impl Writer {
crate::Statement::Kill => {
block.termination = Some(Instruction::kill());
}
+ crate::Statement::Barrier(flags) => {
+ let memory_scope = if flags.contains(crate::Barrier::STORAGE) {
+ spirv::Scope::Device
+ } else {
+ spirv::Scope::Workgroup
+ };
+ let mut semantics = spirv::MemorySemantics::ACQUIRE_RELEASE;
+ semantics.set(
+ spirv::MemorySemantics::UNIFORM_MEMORY,
+ flags.contains(crate::Barrier::STORAGE),
+ );
+ semantics.set(
+ spirv::MemorySemantics::WORKGROUP_MEMORY,
+ flags.contains(crate::Barrier::WORK_GROUP),
+ );
+ let exec_scope_id =
+ self.get_index_constant(spirv::Scope::Workgroup as u32, &ir_module.types)?;
+ let mem_scope_id =
+ self.get_index_constant(memory_scope as u32, &ir_module.types)?;
+ let semantics_id =
+ self.get_index_constant(semantics.bits(), &ir_module.types)?;
+ block.body.push(Instruction::control_barrier(
+ exec_scope_id,
+ mem_scope_id,
+ semantics_id,
+ ));
+ }
crate::Statement::Store { pointer, value } => {
let (pointer_id, _) = self.write_expression_pointer(
ir_module,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2923,15 +2922,20 @@ impl Writer {
match constant.inner {
crate::ConstantInner::Composite { .. } => continue,
crate::ConstantInner::Scalar { width, ref value } => {
- let id = self.id_gen.next();
- self.constant_ids[handle.index()] = id;
- self.write_constant_scalar(
- id,
- value,
- width,
- constant.name.as_ref(),
- &ir_module.types,
- )?;
+ self.constant_ids[handle.index()] = match constant.name {
+ Some(ref name) => {
+ let id = self.id_gen.next();
+ self.write_constant_scalar(
+ id,
+ value,
+ width,
+ Some(name),
+ &ir_module.types,
+ )?;
+ id
+ }
+ None => self.get_constant_scalar(*value, width, &ir_module.types)?,
+ };
}
}
}
diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs
--- a/src/front/spv/error.rs
+++ b/src/front/spv/error.rs
@@ -9,7 +9,7 @@ pub enum Error {
InvalidWordCount,
#[error("unknown instruction {0}")]
UnknownInstruction(u16),
- #[error("unknown capability {0}")]
+ #[error("unknown capability %{0}")]
UnknownCapability(spirv::Word),
#[error("unsupported instruction {1:?} at {0:?}")]
UnsupportedInstruction(ModuleState, spirv::Op),
diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs
--- a/src/front/spv/error.rs
+++ b/src/front/spv/error.rs
@@ -19,27 +19,27 @@ pub enum Error {
UnsupportedExtension(String),
#[error("unsupported extension set {0}")]
UnsupportedExtSet(String),
- #[error("unsupported extension instantiation set {0}")]
+ #[error("unsupported extension instantiation set %{0}")]
UnsupportedExtInstSet(spirv::Word),
- #[error("unsupported extension instantiation {0}")]
+ #[error("unsupported extension instantiation %{0}")]
UnsupportedExtInst(spirv::Word),
#[error("unsupported type {0:?}")]
UnsupportedType(Handle<crate::Type>),
- #[error("unsupported execution model {0}")]
+ #[error("unsupported execution model %{0}")]
UnsupportedExecutionModel(spirv::Word),
- #[error("unsupported execution mode {0}")]
+ #[error("unsupported execution mode %{0}")]
UnsupportedExecutionMode(spirv::Word),
- #[error("unsupported storage class {0}")]
+ #[error("unsupported storage class %{0}")]
UnsupportedStorageClass(spirv::Word),
- #[error("unsupported image dimension {0}")]
+ #[error("unsupported image dimension %{0}")]
UnsupportedImageDim(spirv::Word),
- #[error("unsupported image format {0}")]
+ #[error("unsupported image format %{0}")]
UnsupportedImageFormat(spirv::Word),
- #[error("unsupported builtin {0}")]
+ #[error("unsupported builtin %{0}")]
UnsupportedBuiltIn(spirv::Word),
- #[error("unsupported control flow {0}")]
+ #[error("unsupported control flow %{0}")]
UnsupportedControlFlow(spirv::Word),
- #[error("unsupported binary operator {0}")]
+ #[error("unsupported binary operator %{0}")]
UnsupportedBinaryOperator(spirv::Word),
#[error("unknown binary operator {0:?}")]
UnknownBinaryOperator(spirv::Op),
diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs
--- a/src/front/spv/error.rs
+++ b/src/front/spv/error.rs
@@ -51,25 +51,25 @@ pub enum Error {
InvalidOperandCount(spirv::Op, u16),
#[error("invalid operand")]
InvalidOperand,
- #[error("invalid id {0}")]
+ #[error("invalid id %{0}")]
InvalidId(spirv::Word),
- #[error("invalid decoration {0}")]
+ #[error("invalid decoration %{0}")]
InvalidDecoration(spirv::Word),
- #[error("invalid type width {0}")]
+ #[error("invalid type width %{0}")]
InvalidTypeWidth(spirv::Word),
- #[error("invalid sign {0}")]
+ #[error("invalid sign %{0}")]
InvalidSign(spirv::Word),
- #[error("invalid inner type {0}")]
+ #[error("invalid inner type %{0}")]
InvalidInnerType(spirv::Word),
- #[error("invalid vector size {0}")]
+ #[error("invalid vector size %{0}")]
InvalidVectorSize(spirv::Word),
- #[error("invalid access type {0}")]
+ #[error("invalid access type %{0}")]
InvalidAccessType(spirv::Word),
#[error("invalid access {0:?}")]
InvalidAccess(crate::Expression),
- #[error("invalid access index {0}")]
+ #[error("invalid access index %{0}")]
InvalidAccessIndex(spirv::Word),
- #[error("invalid binding {0}")]
+ #[error("invalid binding %{0}")]
InvalidBinding(spirv::Word),
#[error("invalid global var {0:?}")]
InvalidGlobalVar(crate::Expression),
diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs
--- a/src/front/spv/error.rs
+++ b/src/front/spv/error.rs
@@ -83,9 +83,9 @@ pub enum Error {
InvalidVectorType(Handle<crate::Type>),
#[error("inconsistent comparison sampling {0:?}")]
InconsistentComparisonSampling(Handle<crate::GlobalVariable>),
- #[error("wrong function result type {0}")]
+ #[error("wrong function result type %{0}")]
WrongFunctionResultType(spirv::Word),
- #[error("wrong function argument type {0}")]
+ #[error("wrong function argument type %{0}")]
WrongFunctionArgumentType(spirv::Word),
#[error("missing decoration {0:?}")]
MissingDecoration(spirv::Decoration),
diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs
--- a/src/front/spv/error.rs
+++ b/src/front/spv/error.rs
@@ -97,8 +97,12 @@ pub enum Error {
InvalidTerminator,
#[error("invalid edge classification")]
InvalidEdgeClassification,
- #[error("recursive function call {0}")]
+ #[error("recursive function call %{0}")]
FunctionCallCycle(spirv::Word),
+ #[error("invalid barrier scope %{0}")]
+ InvalidBarrierScope(spirv::Word),
+ #[error("invalid barrier memory semantics %{0}")]
+ InvalidBarrierMemorySemantics(spirv::Word),
// incomplete implementation errors
#[error("unsupported matrix stride {0}")]
UnsupportedMatrixStride(spirv::Word),
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2046,6 +2046,42 @@ impl<I: Iterator<Item = u32>> Parser<I> {
emitter.start(expressions);
}
+ Op::ControlBarrier => {
+ inst.expect(4)?;
+ let exec_scope_id = self.next()?;
+ let _mem_scope_raw = self.next()?;
+ let semantics_id = self.next()?;
+ let exec_scope_const = self.lookup_constant.lookup(exec_scope_id)?;
+ let semantics_const = self.lookup_constant.lookup(semantics_id)?;
+ let exec_scope = match const_arena[exec_scope_const.handle].inner {
+ crate::ConstantInner::Scalar {
+ value: crate::ScalarValue::Uint(raw),
+ width: _,
+ } => raw as u32,
+ _ => return Err(Error::InvalidBarrierScope(exec_scope_id)),
+ };
+ let semantics = match const_arena[semantics_const.handle].inner {
+ crate::ConstantInner::Scalar {
+ value: crate::ScalarValue::Uint(raw),
+ width: _,
+ } => raw as u32,
+ _ => return Err(Error::InvalidBarrierMemorySemantics(semantics_id)),
+ };
+ if exec_scope == spirv::Scope::Workgroup as u32 {
+ let mut flags = crate::Barrier::empty();
+ flags.set(
+ crate::Barrier::STORAGE,
+ semantics & spirv::MemorySemantics::UNIFORM_MEMORY.bits() != 0,
+ );
+ flags.set(
+ crate::Barrier::WORK_GROUP,
+ semantics & spirv::MemorySemantics::WORKGROUP_MEMORY.bits() != 0,
+ );
+ block.push(crate::Statement::Barrier(flags));
+ } else {
+ log::warn!("Unsupported barrier execution scope: {}", exec_scope);
+ }
+ }
_ => return Err(Error::UnsupportedInstruction(self.state, inst.op)),
}
};
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2148,6 +2184,7 @@ impl<I: Iterator<Item = u32>> Parser<I> {
| S::Continue
| S::Return { .. }
| S::Kill
+ | S::Barrier(_)
| S::Store { .. }
| S::ImageStore { .. } => {}
S::Call {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -980,6 +980,7 @@ impl Parser {
query: crate::ImageQuery::NumSamples,
}
}
+ // other
_ => {
let handle =
match self.parse_local_function_call(lexer, name, ctx.reborrow())? {
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -2334,6 +2335,16 @@ impl Parser {
"break" => block.push(crate::Statement::Break),
"continue" => block.push(crate::Statement::Continue),
"discard" => block.push(crate::Statement::Kill),
+ "storageBarrier" => {
+ lexer.expect(Token::Paren('('))?;
+ lexer.expect(Token::Paren(')'))?;
+ block.push(crate::Statement::Barrier(crate::Barrier::STORAGE));
+ }
+ "workgroupBarrier" => {
+ lexer.expect(Token::Paren('('))?;
+ lexer.expect(Token::Paren(')'))?;
+ block.push(crate::Statement::Barrier(crate::Barrier::WORK_GROUP));
+ }
"textureStore" => {
emitter.start(context.expressions);
lexer.open_arguments()?;
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -444,7 +444,7 @@ pub struct Constant {
}
/// A literal scalar value, used in constants.
-#[derive(Debug, PartialEq, Clone, Copy, PartialOrd)]
+#[derive(Debug, Clone, Copy, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
pub enum ScalarValue {
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -696,6 +696,19 @@ pub enum SwizzleComponent {
W = 3,
}
+bitflags::bitflags! {
+ /// Control barrier flags.
+ #[cfg_attr(feature = "serialize", derive(Serialize))]
+ #[cfg_attr(feature = "deserialize", derive(Deserialize))]
+ #[derive(Default)]
+ pub struct Barrier: u32 {
+ /// Barrier affects all `StorageClass::Storage` accesses.
+ const STORAGE = 0x1;
+ /// Barrier affects all `StorageClass::WorkGroup` accesses.
+ const WORK_GROUP = 0x2;
+ }
+}
+
/// An expression that can be evaluated to obtain a value.
///
/// This is a Single Static Assignment (SSA) scheme similar to SPIR-V.
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -871,6 +884,8 @@ pub enum Statement {
Return { value: Option<Handle<Expression>> },
/// Aborts the current shader execution.
Kill,
+ /// Synchronize accesses within the work group.
+ Barrier(Barrier),
/// Stores a value at an address.
///
/// This statement is a barrier for any operations on the
diff --git a/src/proc/mod.rs b/src/proc/mod.rs
--- a/src/proc/mod.rs
+++ b/src/proc/mod.rs
@@ -218,3 +218,27 @@ impl crate::Binding {
}
}
}
+
+//TODO: should we use an existing crate for hashable floats?
+impl PartialEq for crate::ScalarValue {
+ fn eq(&self, other: &Self) -> bool {
+ match (*self, *other) {
+ (Self::Uint(a), Self::Uint(b)) => a == b,
+ (Self::Sint(a), Self::Sint(b)) => a == b,
+ (Self::Float(a), Self::Float(b)) => a.to_bits() == b.to_bits(),
+ (Self::Bool(a), Self::Bool(b)) => a == b,
+ _ => false,
+ }
+ }
+}
+impl Eq for crate::ScalarValue {}
+impl std::hash::Hash for crate::ScalarValue {
+ fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
+ match *self {
+ Self::Sint(v) => v.hash(hasher),
+ Self::Uint(v) => v.hash(hasher),
+ Self::Float(v) => v.to_bits().hash(hasher),
+ Self::Bool(v) => v.hash(hasher),
+ }
+ }
+}
diff --git a/src/proc/terminator.rs b/src/proc/terminator.rs
--- a/src/proc/terminator.rs
+++ b/src/proc/terminator.rs
@@ -39,6 +39,7 @@ pub fn ensure_block_returns(block: &mut crate::Block) {
| Some(&mut S::Store { .. })
| Some(&mut S::ImageStore { .. })
| Some(&mut S::Call { .. })
+ | Some(&mut S::Barrier(_))
| None => block.push(S::Return { value: None }),
}
}
diff --git a/src/valid/analyzer.rs b/src/valid/analyzer.rs
--- a/src/valid/analyzer.rs
+++ b/src/valid/analyzer.rs
@@ -573,6 +573,13 @@ impl FunctionInfo {
result: Uniformity::new(),
exit: ExitFlags::MAY_KILL,
},
+ S::Barrier(_) => FunctionUniformity {
+ result: Uniformity {
+ non_uniform_result: None,
+ requirements: UniformityRequirements::WORK_GROUP_BARRIER,
+ },
+ exit: ExitFlags::empty(),
+ },
S::Block(ref b) => self.process_block(b, other_functions, disruptor)?,
S::If {
condition,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -1,6 +1,6 @@
use super::{
analyzer::{UniformityDisruptor, UniformityRequirements},
- ExpressionError, FunctionInfo, ModuleInfo, TypeFlags, ValidationFlags,
+ ExpressionError, FunctionInfo, ModuleInfo, ShaderStages, TypeFlags, ValidationFlags,
};
use crate::arena::{Arena, Handle};
use bit_set::BitSet;
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -121,11 +121,17 @@ struct BlockContext<'a> {
types: &'a Arena<crate::Type>,
global_vars: &'a Arena<crate::GlobalVariable>,
functions: &'a Arena<crate::Function>,
+ prev_infos: &'a [FunctionInfo],
return_type: Option<Handle<crate::Type>>,
}
impl<'a> BlockContext<'a> {
- fn new(fun: &'a crate::Function, module: &'a crate::Module, info: &'a FunctionInfo) -> Self {
+ fn new(
+ fun: &'a crate::Function,
+ module: &'a crate::Module,
+ info: &'a FunctionInfo,
+ prev_infos: &'a [FunctionInfo],
+ ) -> Self {
Self {
flags: Flags::CAN_JUMP,
info,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -133,6 +139,7 @@ impl<'a> BlockContext<'a> {
types: &module.types,
global_vars: &module.global_variables,
functions: &module.functions,
+ prev_infos,
return_type: fun.result.as_ref().map(|fr| fr.ty),
}
}
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -145,6 +152,7 @@ impl<'a> BlockContext<'a> {
types: self.types,
global_vars: self.global_vars,
functions: self.functions,
+ prev_infos: self.prev_infos,
return_type: self.return_type,
}
}
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -203,7 +211,7 @@ impl super::Validator {
arguments: &[Handle<crate::Expression>],
result: Option<Handle<crate::Expression>>,
context: &BlockContext,
- ) -> Result<(), CallError> {
+ ) -> Result<ShaderStages, CallError> {
let fun = context
.functions
.try_get(function)
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -241,16 +249,18 @@ impl super::Validator {
return Err(CallError::ExpressionMismatch(result));
}
- Ok(())
+ let callee_info = &context.prev_infos[function.index()];
+ Ok(callee_info.available_stages)
}
fn validate_block_impl(
&mut self,
statements: &[crate::Statement],
context: &BlockContext,
- ) -> Result<(), FunctionError> {
+ ) -> Result<ShaderStages, FunctionError> {
use crate::{Statement as S, TypeInner as Ti};
let mut finished = false;
+ let mut stages = ShaderStages::all();
for statement in statements {
if finished {
return Err(FunctionError::InstructionsAfterReturn);
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -265,7 +275,9 @@ impl super::Validator {
}
}
}
- S::Block(ref block) => self.validate_block(block, context)?,
+ S::Block(ref block) => {
+ stages &= self.validate_block(block, context)?;
+ }
S::If {
condition,
ref accept,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -278,8 +290,8 @@ impl super::Validator {
} => {}
_ => return Err(FunctionError::InvalidIfType(condition)),
}
- self.validate_block(accept, context)?;
- self.validate_block(reject, context)?;
+ stages &= self.validate_block(accept, context)?;
+ stages &= self.validate_block(reject, context)?;
}
S::Switch {
selector,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -300,9 +312,9 @@ impl super::Validator {
}
}
for case in cases {
- self.validate_block(&case.body, context)?;
+ stages &= self.validate_block(&case.body, context)?;
}
- self.validate_block(default, context)?;
+ stages &= self.validate_block(default, context)?;
}
S::Loop {
ref body,
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -311,11 +323,12 @@ impl super::Validator {
// special handling for block scoping is needed here,
// because the continuing{} block inherits the scope
let base_expression_count = self.valid_expression_list.len();
- self.validate_block_impl(
+ stages &= self.validate_block_impl(
body,
&context.with_flags(Flags::CAN_JUMP | Flags::IN_LOOP),
)?;
- self.validate_block_impl(continuing, &context.with_flags(Flags::empty()))?;
+ stages &=
+ self.validate_block_impl(continuing, &context.with_flags(Flags::empty()))?;
for handle in self.valid_expression_list.drain(base_expression_count..) {
self.valid_expression_set.remove(handle.index());
}
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -347,6 +360,9 @@ impl super::Validator {
S::Kill => {
finished = true;
}
+ S::Barrier(_) => {
+ stages &= ShaderStages::COMPUTE;
+ }
S::Store { pointer, value } => {
let mut current = pointer;
loop {
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -472,27 +488,26 @@ impl super::Validator {
function,
ref arguments,
result,
- } => {
- if let Err(error) = self.validate_call(function, arguments, result, context) {
- return Err(FunctionError::InvalidCall { function, error });
- }
- }
+ } => match self.validate_call(function, arguments, result, context) {
+ Ok(callee_stages) => stages &= callee_stages,
+ Err(error) => return Err(FunctionError::InvalidCall { function, error }),
+ },
}
}
- Ok(())
+ Ok(stages)
}
fn validate_block(
&mut self,
statements: &[crate::Statement],
context: &BlockContext,
- ) -> Result<(), FunctionError> {
+ ) -> Result<ShaderStages, FunctionError> {
let base_expression_count = self.valid_expression_list.len();
- self.validate_block_impl(statements, context)?;
+ let stages = self.validate_block_impl(statements, context)?;
for handle in self.valid_expression_list.drain(base_expression_count..) {
self.valid_expression_set.remove(handle.index());
}
- Ok(())
+ Ok(stages)
}
fn validate_local_var(
diff --git a/src/valid/function.rs b/src/valid/function.rs
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -573,7 +588,11 @@ impl super::Validator {
}
if self.flags.contains(ValidationFlags::BLOCKS) {
- self.validate_block(&fun.body, &BlockContext::new(fun, module, &info))?;
+ let stages = self.validate_block(
+ &fun.body,
+ &BlockContext::new(fun, module, &info, &mod_info.functions),
+ )?;
+ info.available_stages &= stages;
}
Ok(info)
}
diff --git a/src/valid/mod.rs b/src/valid/mod.rs
--- a/src/valid/mod.rs
+++ b/src/valid/mod.rs
@@ -40,6 +40,7 @@ bitflags::bitflags! {
}
}
+#[must_use]
bitflags::bitflags! {
/// Validation flags.
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
|
diff --git /dev/null b/tests/in/control-flow.param.ron
new file mode 100644
--- /dev/null
+++ b/tests/in/control-flow.param.ron
@@ -0,0 +1,7 @@
+(
+ spv_version: (1, 1),
+ spv_capabilities: [ Shader ],
+ spv_debug: false,
+ spv_adjust_coordinate_space: false,
+ msl_custom: false,
+)
diff --git /dev/null b/tests/in/control-flow.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/in/control-flow.wgsl
@@ -0,0 +1,5 @@
+[[stage(compute), workgroup_size(1)]]
+fn main([[builtin(global_invocation_id)]] global_id: vec3<u32>) {
+ storageBarrier();
+ workgroupBarrier();
+}
diff --git a/tests/out/access.spvasm b/tests/out/access.spvasm
--- a/tests/out/access.spvasm
+++ b/tests/out/access.spvasm
@@ -45,7 +45,7 @@ OpDecorate %21 BuiltIn Position
%24 = OpTypeFunction %2
%26 = OpTypePointer StorageBuffer %10
%29 = OpTypePointer StorageBuffer %6
-%30 = OpConstant %6 0
+%30 = OpConstant %4 0
%34 = OpTypePointer Function %14
%37 = OpTypePointer Function %6
%39 = OpTypeVector %6 4
diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm
--- a/tests/out/boids.spvasm
+++ b/tests/out/boids.spvasm
@@ -94,11 +94,11 @@ OpDecorate %40 BuiltIn GlobalInvocationId
%52 = OpTypePointer StorageBuffer %16
%53 = OpTypePointer StorageBuffer %15
%82 = OpTypePointer Uniform %6
-%96 = OpConstant %8 2
-%110 = OpConstant %8 3
-%145 = OpConstant %8 4
-%151 = OpConstant %8 5
-%157 = OpConstant %8 6
+%96 = OpConstant %4 2
+%110 = OpConstant %4 3
+%145 = OpConstant %4 4
+%151 = OpConstant %4 5
+%157 = OpConstant %4 6
%179 = OpTypePointer Function %6
%43 = OpFunction %2 None %44
%39 = OpLabel
diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm
--- a/tests/out/boids.spvasm
+++ b/tests/out/boids.spvasm
@@ -122,10 +122,10 @@ OpBranchConditional %48 %50 %49
%50 = OpLabel
OpReturn
%49 = OpLabel
-%54 = OpAccessChain %53 %23 %7 %46 %7
+%54 = OpAccessChain %53 %23 %9 %46 %9
%55 = OpLoad %15 %54
OpStore %26 %55
-%56 = OpAccessChain %53 %23 %7 %46 %10
+%56 = OpAccessChain %53 %23 %9 %46 %11
%57 = OpLoad %15 %56
OpStore %28 %57
%58 = OpCompositeConstruct %15 %5 %5
diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm
--- a/tests/out/boids.spvasm
+++ b/tests/out/boids.spvasm
@@ -154,17 +154,17 @@ OpBranchConditional %70 %72 %71
OpBranch %64
%71 = OpLabel
%73 = OpLoad %4 %37
-%74 = OpAccessChain %53 %23 %7 %73 %7
+%74 = OpAccessChain %53 %23 %9 %73 %9
%75 = OpLoad %15 %74
OpStore %35 %75
%76 = OpLoad %4 %37
-%77 = OpAccessChain %53 %23 %7 %76 %10
+%77 = OpAccessChain %53 %23 %9 %76 %11
%78 = OpLoad %15 %77
OpStore %36 %78
%79 = OpLoad %15 %35
%80 = OpLoad %15 %26
%81 = OpExtInst %6 %1 Distance %79 %80
-%83 = OpAccessChain %82 %21 %10
+%83 = OpAccessChain %82 %21 %11
%84 = OpLoad %6 %83
%85 = OpFOrdLessThan %47 %81 %84
OpSelectionMerge %86 None
diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm
--- a/tests/out/boids.spvasm
+++ b/tests/out/boids.spvasm
@@ -275,7 +275,7 @@ OpStore %28 %161
OpStore %28 %167
%168 = OpLoad %15 %26
%169 = OpLoad %15 %28
-%170 = OpAccessChain %82 %21 %7
+%170 = OpAccessChain %82 %21 %9
%171 = OpLoad %6 %170
%172 = OpVectorTimesScalar %15 %169 %171
%173 = OpFAdd %15 %168 %172
diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm
--- a/tests/out/boids.spvasm
+++ b/tests/out/boids.spvasm
@@ -286,7 +286,7 @@ OpStore %26 %173
OpSelectionMerge %177 None
OpBranchConditional %176 %178 %177
%178 = OpLabel
-%180 = OpAccessChain %179 %26 %7
+%180 = OpAccessChain %179 %26 %9
OpStore %180 %14
OpBranch %177
%177 = OpLabel
diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm
--- a/tests/out/boids.spvasm
+++ b/tests/out/boids.spvasm
@@ -296,7 +296,7 @@ OpBranch %177
OpSelectionMerge %184 None
OpBranchConditional %183 %185 %184
%185 = OpLabel
-%186 = OpAccessChain %179 %26 %7
+%186 = OpAccessChain %179 %26 %9
OpStore %186 %13
OpBranch %184
%184 = OpLabel
diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm
--- a/tests/out/boids.spvasm
+++ b/tests/out/boids.spvasm
@@ -306,7 +306,7 @@ OpBranch %184
OpSelectionMerge %190 None
OpBranchConditional %189 %191 %190
%191 = OpLabel
-%192 = OpAccessChain %179 %26 %10
+%192 = OpAccessChain %179 %26 %11
OpStore %192 %14
OpBranch %190
%190 = OpLabel
diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm
--- a/tests/out/boids.spvasm
+++ b/tests/out/boids.spvasm
@@ -316,15 +316,15 @@ OpBranch %190
OpSelectionMerge %196 None
OpBranchConditional %195 %197 %196
%197 = OpLabel
-%198 = OpAccessChain %179 %26 %10
+%198 = OpAccessChain %179 %26 %11
OpStore %198 %13
OpBranch %196
%196 = OpLabel
%199 = OpLoad %15 %26
-%200 = OpAccessChain %53 %25 %7 %46 %7
+%200 = OpAccessChain %53 %25 %9 %46 %9
OpStore %200 %199
%201 = OpLoad %15 %28
-%202 = OpAccessChain %53 %25 %7 %46 %10
+%202 = OpAccessChain %53 %25 %9 %46 %11
OpStore %202 %201
OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/collatz.spvasm b/tests/out/collatz.spvasm
--- a/tests/out/collatz.spvasm
+++ b/tests/out/collatz.spvasm
@@ -1,7 +1,7 @@
; SPIR-V
; Version: 1.0
; Generator: rspirv
-; Bound: 61
+; Bound: 59
OpCapability Shader
OpExtension "SPV_KHR_storage_buffer_storage_class"
%1 = OpExtInstImport "GLSL.std.450"
diff --git a/tests/out/collatz.spvasm b/tests/out/collatz.spvasm
--- a/tests/out/collatz.spvasm
+++ b/tests/out/collatz.spvasm
@@ -42,8 +42,6 @@ OpDecorate %45 BuiltIn GlobalInvocationId
%49 = OpTypeFunction %2
%51 = OpTypePointer StorageBuffer %8
%53 = OpTypePointer StorageBuffer %4
-%55 = OpTypeInt 32 1
-%56 = OpConstant %55 0
%18 = OpFunction %4 None %19
%17 = OpFunctionParameter %4
%16 = OpLabel
diff --git a/tests/out/collatz.spvasm b/tests/out/collatz.spvasm
--- a/tests/out/collatz.spvasm
+++ b/tests/out/collatz.spvasm
@@ -98,10 +96,10 @@ OpBranch %50
%50 = OpLabel
%52 = OpCompositeExtract %4 %47 0
%54 = OpCompositeExtract %4 %47 0
-%57 = OpAccessChain %53 %11 %56 %54
-%58 = OpLoad %4 %57
-%59 = OpFunctionCall %4 %18 %58
-%60 = OpAccessChain %53 %11 %56 %52
-OpStore %60 %59
+%55 = OpAccessChain %53 %11 %3 %54
+%56 = OpLoad %4 %55
+%57 = OpFunctionCall %4 %18 %56
+%58 = OpAccessChain %53 %11 %3 %52
+OpStore %58 %57
OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git /dev/null b/tests/out/control-flow.Compute.glsl
new file mode 100644
--- /dev/null
+++ b/tests/out/control-flow.Compute.glsl
@@ -0,0 +1,14 @@
+#version 310 es
+
+precision highp float;
+
+layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
+
+
+void main() {
+ uvec3 global_id = gl_GlobalInvocationID;
+ groupMemoryBarrier();
+ barrier();
+ return;
+}
+
diff --git /dev/null b/tests/out/control-flow.msl
new file mode 100644
--- /dev/null
+++ b/tests/out/control-flow.msl
@@ -0,0 +1,13 @@
+#include <metal_stdlib>
+#include <simd/simd.h>
+
+
+struct main1Input {
+};
+kernel void main1(
+ metal::uint3 global_id [[thread_position_in_grid]]
+) {
+ metal::threadgroup_barrier(metal::mem_flags::mem_device);
+ metal::threadgroup_barrier(metal::mem_flags::mem_threadgroup);
+ return;
+}
diff --git /dev/null b/tests/out/control-flow.spvasm
new file mode 100644
--- /dev/null
+++ b/tests/out/control-flow.spvasm
@@ -0,0 +1,29 @@
+; SPIR-V
+; Version: 1.1
+; Generator: rspirv
+; Bound: 16
+OpCapability Shader
+%1 = OpExtInstImport "GLSL.std.450"
+OpMemoryModel Logical GLSL450
+OpEntryPoint GLCompute %9 "main" %6
+OpExecutionMode %9 LocalSize 1 1 1
+OpDecorate %6 BuiltIn GlobalInvocationId
+%2 = OpTypeVoid
+%4 = OpTypeInt 32 0
+%3 = OpTypeVector %4 3
+%7 = OpTypePointer Input %3
+%6 = OpVariable %7 Input
+%10 = OpTypeFunction %2
+%12 = OpConstant %4 2
+%13 = OpConstant %4 1
+%14 = OpConstant %4 72
+%15 = OpConstant %4 264
+%9 = OpFunction %2 None %10
+%5 = OpLabel
+%8 = OpLoad %3 %6
+OpBranch %11
+%11 = OpLabel
+OpControlBarrier %12 %13 %14
+OpControlBarrier %12 %12 %15
+OpReturn
+OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/image.spvasm b/tests/out/image.spvasm
--- a/tests/out/image.spvasm
+++ b/tests/out/image.spvasm
@@ -90,7 +90,7 @@ OpDecorate %59 BuiltIn Position
%55 = OpTypeVector %8 4
%60 = OpTypePointer Output %20
%59 = OpVariable %60 Output
-%70 = OpConstant %4 0
+%70 = OpConstant %8 0
%75 = OpTypeVector %4 3
%43 = OpFunction %2 None %44
%39 = OpLabel
diff --git a/tests/out/interpolate.spvasm b/tests/out/interpolate.spvasm
--- a/tests/out/interpolate.spvasm
+++ b/tests/out/interpolate.spvasm
@@ -1,14 +1,14 @@
; SPIR-V
; Version: 1.0
; Generator: rspirv
-; Bound: 109
+; Bound: 108
OpCapability Shader
OpCapability SampleRateShading
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Vertex %42 "main" %29 %31 %33 %35 %37 %39 %40 %41
-OpEntryPoint Fragment %107 "main" %86 %89 %92 %95 %98 %101 %103 %105
-OpExecutionMode %107 OriginUpperLeft
+OpEntryPoint Fragment %106 "main" %85 %88 %91 %94 %97 %100 %102 %104
+OpExecutionMode %106 OriginUpperLeft
OpSource GLSL 450
OpName %25 "FragmentInput"
OpMemberName %25 0 "position"
diff --git a/tests/out/interpolate.spvasm b/tests/out/interpolate.spvasm
--- a/tests/out/interpolate.spvasm
+++ b/tests/out/interpolate.spvasm
@@ -29,15 +29,15 @@ OpName %39 "perspective"
OpName %40 "perspective_centroid"
OpName %41 "perspective_sample"
OpName %42 "main"
-OpName %86 "position"
-OpName %89 "flat"
-OpName %92 "linear"
-OpName %95 "linear_centroid"
-OpName %98 "linear_sample"
-OpName %101 "perspective"
-OpName %103 "perspective_centroid"
-OpName %105 "perspective_sample"
-OpName %107 "main"
+OpName %85 "position"
+OpName %88 "flat"
+OpName %91 "linear"
+OpName %94 "linear_centroid"
+OpName %97 "linear_sample"
+OpName %100 "perspective"
+OpName %102 "perspective_centroid"
+OpName %104 "perspective_sample"
+OpName %106 "main"
OpMemberDecorate %25 0 Offset 0
OpMemberDecorate %25 1 Offset 16
OpMemberDecorate %25 2 Offset 20
diff --git a/tests/out/interpolate.spvasm b/tests/out/interpolate.spvasm
--- a/tests/out/interpolate.spvasm
+++ b/tests/out/interpolate.spvasm
@@ -62,22 +62,22 @@ OpDecorate %40 Location 5
OpDecorate %40 Centroid
OpDecorate %41 Location 6
OpDecorate %41 Sample
-OpDecorate %86 BuiltIn FragCoord
-OpDecorate %89 Location 0
-OpDecorate %89 Flat
-OpDecorate %92 Location 1
-OpDecorate %92 NoPerspective
-OpDecorate %95 Location 2
-OpDecorate %95 NoPerspective
-OpDecorate %95 Centroid
-OpDecorate %98 Location 3
-OpDecorate %98 NoPerspective
-OpDecorate %98 Sample
-OpDecorate %101 Location 4
-OpDecorate %103 Location 5
-OpDecorate %103 Centroid
-OpDecorate %105 Location 6
-OpDecorate %105 Sample
+OpDecorate %85 BuiltIn FragCoord
+OpDecorate %88 Location 0
+OpDecorate %88 Flat
+OpDecorate %91 Location 1
+OpDecorate %91 NoPerspective
+OpDecorate %94 Location 2
+OpDecorate %94 NoPerspective
+OpDecorate %94 Centroid
+OpDecorate %97 Location 3
+OpDecorate %97 NoPerspective
+OpDecorate %97 Sample
+OpDecorate %100 Location 4
+OpDecorate %102 Location 5
+OpDecorate %102 Centroid
+OpDecorate %104 Location 6
+OpDecorate %104 Sample
%2 = OpTypeVoid
%4 = OpTypeFloat 32
%3 = OpConstant %4 2.0
diff --git a/tests/out/interpolate.spvasm b/tests/out/interpolate.spvasm
--- a/tests/out/interpolate.spvasm
+++ b/tests/out/interpolate.spvasm
@@ -118,93 +118,92 @@ OpDecorate %105 Sample
%41 = OpVariable %34 Output
%43 = OpTypeFunction %2
%45 = OpTypePointer Function %22
-%47 = OpTypeInt 32 1
-%48 = OpConstant %47 0
-%50 = OpTypePointer Function %9
-%51 = OpConstant %47 1
-%53 = OpTypePointer Function %4
-%54 = OpConstant %47 2
-%56 = OpTypePointer Function %23
-%58 = OpConstant %47 3
-%60 = OpTypePointer Function %24
-%62 = OpConstant %47 4
-%65 = OpConstant %47 5
-%67 = OpConstant %47 6
-%69 = OpConstant %47 7
-%74 = OpTypePointer Output %4
-%87 = OpTypePointer Input %22
-%86 = OpVariable %87 Input
-%90 = OpTypePointer Input %9
-%89 = OpVariable %90 Input
-%93 = OpTypePointer Input %4
-%92 = OpVariable %93 Input
-%96 = OpTypePointer Input %23
-%95 = OpVariable %96 Input
-%99 = OpTypePointer Input %24
-%98 = OpVariable %99 Input
-%101 = OpVariable %87 Input
-%103 = OpVariable %93 Input
-%105 = OpVariable %93 Input
+%47 = OpConstant %9 0
+%49 = OpTypePointer Function %9
+%50 = OpConstant %9 1
+%52 = OpTypePointer Function %4
+%53 = OpConstant %9 2
+%55 = OpTypePointer Function %23
+%57 = OpConstant %9 3
+%59 = OpTypePointer Function %24
+%61 = OpConstant %9 4
+%64 = OpConstant %9 5
+%66 = OpConstant %9 6
+%68 = OpConstant %9 7
+%73 = OpTypePointer Output %4
+%86 = OpTypePointer Input %22
+%85 = OpVariable %86 Input
+%89 = OpTypePointer Input %9
+%88 = OpVariable %89 Input
+%92 = OpTypePointer Input %4
+%91 = OpVariable %92 Input
+%95 = OpTypePointer Input %23
+%94 = OpVariable %95 Input
+%98 = OpTypePointer Input %24
+%97 = OpVariable %98 Input
+%100 = OpVariable %86 Input
+%102 = OpVariable %92 Input
+%104 = OpVariable %92 Input
%42 = OpFunction %2 None %43
%28 = OpLabel
%26 = OpVariable %27 Function
OpBranch %44
%44 = OpLabel
%46 = OpCompositeConstruct %22 %3 %5 %6 %7
-%49 = OpAccessChain %45 %26 %48
-OpStore %49 %46
-%52 = OpAccessChain %50 %26 %51
-OpStore %52 %8
-%55 = OpAccessChain %53 %26 %54
-OpStore %55 %10
-%57 = OpCompositeConstruct %23 %11 %12
-%59 = OpAccessChain %56 %26 %58
-OpStore %59 %57
-%61 = OpCompositeConstruct %24 %13 %14 %15
-%63 = OpAccessChain %60 %26 %62
-OpStore %63 %61
-%64 = OpCompositeConstruct %22 %16 %17 %18 %19
-%66 = OpAccessChain %45 %26 %65
-OpStore %66 %64
-%68 = OpAccessChain %53 %26 %67
-OpStore %68 %20
-%70 = OpAccessChain %53 %26 %69
-OpStore %70 %21
-%71 = OpLoad %25 %26
-%72 = OpCompositeExtract %22 %71 0
-OpStore %29 %72
-%73 = OpAccessChain %74 %29 %51
-%75 = OpLoad %4 %73
-%76 = OpFNegate %4 %75
-OpStore %73 %76
-%77 = OpCompositeExtract %9 %71 1
-OpStore %31 %77
-%78 = OpCompositeExtract %4 %71 2
-OpStore %33 %78
-%79 = OpCompositeExtract %23 %71 3
-OpStore %35 %79
-%80 = OpCompositeExtract %24 %71 4
-OpStore %37 %80
-%81 = OpCompositeExtract %22 %71 5
-OpStore %39 %81
-%82 = OpCompositeExtract %4 %71 6
-OpStore %40 %82
-%83 = OpCompositeExtract %4 %71 7
-OpStore %41 %83
+%48 = OpAccessChain %45 %26 %47
+OpStore %48 %46
+%51 = OpAccessChain %49 %26 %50
+OpStore %51 %8
+%54 = OpAccessChain %52 %26 %53
+OpStore %54 %10
+%56 = OpCompositeConstruct %23 %11 %12
+%58 = OpAccessChain %55 %26 %57
+OpStore %58 %56
+%60 = OpCompositeConstruct %24 %13 %14 %15
+%62 = OpAccessChain %59 %26 %61
+OpStore %62 %60
+%63 = OpCompositeConstruct %22 %16 %17 %18 %19
+%65 = OpAccessChain %45 %26 %64
+OpStore %65 %63
+%67 = OpAccessChain %52 %26 %66
+OpStore %67 %20
+%69 = OpAccessChain %52 %26 %68
+OpStore %69 %21
+%70 = OpLoad %25 %26
+%71 = OpCompositeExtract %22 %70 0
+OpStore %29 %71
+%72 = OpAccessChain %73 %29 %50
+%74 = OpLoad %4 %72
+%75 = OpFNegate %4 %74
+OpStore %72 %75
+%76 = OpCompositeExtract %9 %70 1
+OpStore %31 %76
+%77 = OpCompositeExtract %4 %70 2
+OpStore %33 %77
+%78 = OpCompositeExtract %23 %70 3
+OpStore %35 %78
+%79 = OpCompositeExtract %24 %70 4
+OpStore %37 %79
+%80 = OpCompositeExtract %22 %70 5
+OpStore %39 %80
+%81 = OpCompositeExtract %4 %70 6
+OpStore %40 %81
+%82 = OpCompositeExtract %4 %70 7
+OpStore %41 %82
OpReturn
OpFunctionEnd
-%107 = OpFunction %2 None %43
-%84 = OpLabel
-%88 = OpLoad %22 %86
-%91 = OpLoad %9 %89
-%94 = OpLoad %4 %92
-%97 = OpLoad %23 %95
-%100 = OpLoad %24 %98
-%102 = OpLoad %22 %101
-%104 = OpLoad %4 %103
-%106 = OpLoad %4 %105
-%85 = OpCompositeConstruct %25 %88 %91 %94 %97 %100 %102 %104 %106
-OpBranch %108
-%108 = OpLabel
+%106 = OpFunction %2 None %43
+%83 = OpLabel
+%87 = OpLoad %22 %85
+%90 = OpLoad %9 %88
+%93 = OpLoad %4 %91
+%96 = OpLoad %23 %94
+%99 = OpLoad %24 %97
+%101 = OpLoad %22 %100
+%103 = OpLoad %4 %102
+%105 = OpLoad %4 %104
+%84 = OpCompositeConstruct %25 %87 %90 %93 %96 %99 %101 %103 %105
+OpBranch %107
+%107 = OpLabel
OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/quad.spvasm b/tests/out/quad.spvasm
--- a/tests/out/quad.spvasm
+++ b/tests/out/quad.spvasm
@@ -57,8 +57,8 @@ OpDecorate %43 Location 0
%24 = OpVariable %25 Output
%27 = OpTypeFunction %2
%35 = OpTypePointer Output %4
-%36 = OpTypeInt 32 1
-%37 = OpConstant %36 1
+%37 = OpTypeInt 32 0
+%36 = OpConstant %37 1
%41 = OpVariable %18 Input
%43 = OpVariable %25 Output
%48 = OpTypeSampledImage %10
diff --git a/tests/out/quad.spvasm b/tests/out/quad.spvasm
--- a/tests/out/quad.spvasm
+++ b/tests/out/quad.spvasm
@@ -76,7 +76,7 @@ OpBranch %28
OpStore %22 %32
%33 = OpCompositeExtract %8 %31 1
OpStore %24 %33
-%34 = OpAccessChain %35 %24 %37
+%34 = OpAccessChain %35 %24 %36
%38 = OpLoad %4 %34
%39 = OpFNegate %4 %38
OpStore %34 %39
diff --git a/tests/out/shadow.spvasm b/tests/out/shadow.spvasm
--- a/tests/out/shadow.spvasm
+++ b/tests/out/shadow.spvasm
@@ -1,13 +1,13 @@
; SPIR-V
; Version: 1.2
; Generator: rspirv
-; Bound: 126
+; Bound: 124
OpCapability Shader
OpExtension "SPV_KHR_storage_buffer_storage_class"
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
-OpEntryPoint Fragment %80 "fs_main" %72 %75 %78
-OpExecutionMode %80 OriginUpperLeft
+OpEntryPoint Fragment %79 "fs_main" %71 %74 %77
+OpExecutionMode %79 OriginUpperLeft
OpSource GLSL 450
OpName %9 "c_max_lights"
OpName %14 "Globals"
diff --git a/tests/out/shadow.spvasm b/tests/out/shadow.spvasm
--- a/tests/out/shadow.spvasm
+++ b/tests/out/shadow.spvasm
@@ -24,11 +24,11 @@ OpName %27 "s_lights"
OpName %29 "t_shadow"
OpName %31 "sampler_shadow"
OpName %36 "fetch_shadow"
-OpName %67 "color"
-OpName %69 "i"
-OpName %72 "raw_normal"
-OpName %75 "position"
-OpName %80 "fs_main"
+OpName %66 "color"
+OpName %68 "i"
+OpName %71 "raw_normal"
+OpName %74 "position"
+OpName %79 "fs_main"
OpDecorate %14 Block
OpMemberDecorate %14 0 Offset 0
OpMemberDecorate %17 0 Offset 0
diff --git a/tests/out/shadow.spvasm b/tests/out/shadow.spvasm
--- a/tests/out/shadow.spvasm
+++ b/tests/out/shadow.spvasm
@@ -48,9 +48,9 @@ OpDecorate %29 DescriptorSet 0
OpDecorate %29 Binding 2
OpDecorate %31 DescriptorSet 0
OpDecorate %31 Binding 3
-OpDecorate %72 Location 0
-OpDecorate %75 Location 1
-OpDecorate %78 Location 0
+OpDecorate %71 Location 0
+OpDecorate %74 Location 1
+OpDecorate %77 Location 0
%2 = OpTypeVoid
%4 = OpTypeFloat 32
%3 = OpConstant %4 0.0
diff --git a/tests/out/shadow.spvasm b/tests/out/shadow.spvasm
--- a/tests/out/shadow.spvasm
+++ b/tests/out/shadow.spvasm
@@ -86,20 +86,18 @@ OpDecorate %78 Location 0
%42 = OpTypeBool
%54 = OpTypeInt 32 1
%59 = OpTypeSampledImage %20
-%66 = OpConstant %4 0.0
-%68 = OpTypePointer Function %23
-%70 = OpTypePointer Function %10
-%73 = OpTypePointer Input %23
-%72 = OpVariable %73 Input
-%76 = OpTypePointer Input %16
-%75 = OpVariable %76 Input
-%79 = OpTypePointer Output %16
-%78 = OpVariable %79 Output
-%81 = OpTypeFunction %2
-%91 = OpTypePointer Uniform %13
-%92 = OpConstant %54 0
-%100 = OpTypePointer StorageBuffer %18
-%102 = OpTypePointer StorageBuffer %17
+%67 = OpTypePointer Function %23
+%69 = OpTypePointer Function %10
+%72 = OpTypePointer Input %23
+%71 = OpVariable %72 Input
+%75 = OpTypePointer Input %16
+%74 = OpVariable %75 Input
+%78 = OpTypePointer Output %16
+%77 = OpVariable %78 Output
+%80 = OpTypeFunction %2
+%90 = OpTypePointer Uniform %13
+%98 = OpTypePointer StorageBuffer %18
+%100 = OpTypePointer StorageBuffer %17
%36 = OpFunction %4 None %37
%34 = OpFunctionParameter %10
%35 = OpFunctionParameter %16
diff --git a/tests/out/shadow.spvasm b/tests/out/shadow.spvasm
--- a/tests/out/shadow.spvasm
+++ b/tests/out/shadow.spvasm
@@ -132,66 +130,66 @@ OpReturnValue %5
%62 = OpConvertUToF %4 %55
%63 = OpCompositeConstruct %23 %60 %61 %62
%64 = OpSampledImage %59 %38 %39
-%65 = OpImageSampleDrefExplicitLod %4 %64 %63 %58 Lod %66
+%65 = OpImageSampleDrefExplicitLod %4 %64 %63 %58 Lod %3
OpReturnValue %65
OpFunctionEnd
-%80 = OpFunction %2 None %81
-%71 = OpLabel
-%67 = OpVariable %68 Function %24
-%69 = OpVariable %70 Function %11
-%74 = OpLoad %23 %72
-%77 = OpLoad %16 %75
-%82 = OpLoad %20 %29
-%83 = OpLoad %21 %31
-OpBranch %84
-%84 = OpLabel
-%85 = OpExtInst %23 %1 Normalize %74
+%79 = OpFunction %2 None %80
+%70 = OpLabel
+%66 = OpVariable %67 Function %24
+%68 = OpVariable %69 Function %11
+%73 = OpLoad %23 %71
+%76 = OpLoad %16 %74
+%81 = OpLoad %20 %29
+%82 = OpLoad %21 %31
+OpBranch %83
+%83 = OpLabel
+%84 = OpExtInst %23 %1 Normalize %73
+OpBranch %85
+%85 = OpLabel
+OpLoopMerge %86 %88 None
+OpBranch %87
+%87 = OpLabel
+%89 = OpLoad %10 %68
+%91 = OpAccessChain %90 %25 %11
+%92 = OpLoad %13 %91
+%93 = OpCompositeExtract %10 %92 0
+%94 = OpExtInst %10 %1 UMin %93 %9
+%95 = OpUGreaterThanEqual %42 %89 %94
+OpSelectionMerge %96 None
+OpBranchConditional %95 %97 %96
+%97 = OpLabel
OpBranch %86
-%86 = OpLabel
-OpLoopMerge %87 %89 None
+%96 = OpLabel
+%99 = OpLoad %10 %68
+%101 = OpAccessChain %100 %27 %11 %99
+%102 = OpLoad %17 %101
+%103 = OpLoad %10 %68
+%104 = OpCompositeExtract %15 %102 0
+%105 = OpMatrixTimesVector %16 %104 %76
+%106 = OpFunctionCall %4 %36 %103 %105
+%107 = OpCompositeExtract %16 %102 1
+%108 = OpVectorShuffle %23 %107 %107 0 1 2
+%109 = OpVectorShuffle %23 %76 %76 0 1 2
+%110 = OpFSub %23 %108 %109
+%111 = OpExtInst %23 %1 Normalize %110
+%112 = OpDot %4 %84 %111
+%113 = OpExtInst %4 %1 FMax %3 %112
+%114 = OpLoad %23 %66
+%115 = OpFMul %4 %106 %113
+%116 = OpCompositeExtract %16 %102 2
+%117 = OpVectorShuffle %23 %116 %116 0 1 2
+%118 = OpVectorTimesScalar %23 %117 %115
+%119 = OpFAdd %23 %114 %118
+OpStore %66 %119
OpBranch %88
%88 = OpLabel
-%90 = OpLoad %10 %69
-%93 = OpAccessChain %91 %25 %92
-%94 = OpLoad %13 %93
-%95 = OpCompositeExtract %10 %94 0
-%96 = OpExtInst %10 %1 UMin %95 %9
-%97 = OpUGreaterThanEqual %42 %90 %96
-OpSelectionMerge %98 None
-OpBranchConditional %97 %99 %98
-%99 = OpLabel
-OpBranch %87
-%98 = OpLabel
-%101 = OpLoad %10 %69
-%103 = OpAccessChain %102 %27 %92 %101
-%104 = OpLoad %17 %103
-%105 = OpLoad %10 %69
-%106 = OpCompositeExtract %15 %104 0
-%107 = OpMatrixTimesVector %16 %106 %77
-%108 = OpFunctionCall %4 %36 %105 %107
-%109 = OpCompositeExtract %16 %104 1
-%110 = OpVectorShuffle %23 %109 %109 0 1 2
-%111 = OpVectorShuffle %23 %77 %77 0 1 2
-%112 = OpFSub %23 %110 %111
-%113 = OpExtInst %23 %1 Normalize %112
-%114 = OpDot %4 %85 %113
-%115 = OpExtInst %4 %1 FMax %3 %114
-%116 = OpLoad %23 %67
-%117 = OpFMul %4 %108 %115
-%118 = OpCompositeExtract %16 %104 2
-%119 = OpVectorShuffle %23 %118 %118 0 1 2
-%120 = OpVectorTimesScalar %23 %119 %117
-%121 = OpFAdd %23 %116 %120
-OpStore %67 %121
-OpBranch %89
-%89 = OpLabel
-%122 = OpLoad %10 %69
-%123 = OpIAdd %10 %122 %12
-OpStore %69 %123
-OpBranch %86
-%87 = OpLabel
-%124 = OpLoad %23 %67
-%125 = OpCompositeConstruct %16 %124 %5
-OpStore %78 %125
+%120 = OpLoad %10 %68
+%121 = OpIAdd %10 %120 %12
+OpStore %68 %121
+OpBranch %85
+%86 = OpLabel
+%122 = OpLoad %23 %66
+%123 = OpCompositeConstruct %16 %122 %5
+OpStore %77 %123
OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/skybox.spvasm b/tests/out/skybox.spvasm
--- a/tests/out/skybox.spvasm
+++ b/tests/out/skybox.spvasm
@@ -1,13 +1,13 @@
; SPIR-V
; Version: 1.0
; Generator: rspirv
-; Bound: 93
+; Bound: 94
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Vertex %36 "vs_main" %29 %32 %34
-OpEntryPoint Fragment %85 "fs_main" %78 %81 %84
-OpExecutionMode %85 OriginUpperLeft
+OpEntryPoint Fragment %86 "fs_main" %79 %82 %85
+OpExecutionMode %86 OriginUpperLeft
OpMemberDecorate %12 0 Offset 0
OpMemberDecorate %12 1 Offset 16
OpDecorate %14 Block
diff --git a/tests/out/skybox.spvasm b/tests/out/skybox.spvasm
--- a/tests/out/skybox.spvasm
+++ b/tests/out/skybox.spvasm
@@ -26,9 +26,9 @@ OpDecorate %23 Binding 2
OpDecorate %29 BuiltIn VertexIndex
OpDecorate %32 BuiltIn Position
OpDecorate %34 Location 0
-OpDecorate %78 BuiltIn FragCoord
-OpDecorate %81 Location 0
-OpDecorate %84 Location 0
+OpDecorate %79 BuiltIn FragCoord
+OpDecorate %82 Location 0
+OpDecorate %85 Location 0
%2 = OpTypeVoid
%4 = OpTypeInt 32 1
%3 = OpConstant %4 2
diff --git a/tests/out/skybox.spvasm b/tests/out/skybox.spvasm
--- a/tests/out/skybox.spvasm
+++ b/tests/out/skybox.spvasm
@@ -61,13 +61,14 @@ OpDecorate %84 Location 0
%34 = OpVariable %35 Output
%37 = OpTypeFunction %2
%52 = OpTypePointer Uniform %13
-%67 = OpConstant %4 0
-%79 = OpTypePointer Input %10
-%78 = OpVariable %79 Input
-%82 = OpTypePointer Input %11
-%81 = OpVariable %82 Input
-%84 = OpVariable %33 Output
-%90 = OpTypeSampledImage %17
+%53 = OpConstant %15 1
+%68 = OpConstant %15 0
+%80 = OpTypePointer Input %10
+%79 = OpVariable %80 Input
+%83 = OpTypePointer Input %11
+%82 = OpVariable %83 Input
+%85 = OpVariable %33 Output
+%91 = OpTypeSampledImage %17
%36 = OpFunction %2 None %37
%28 = OpLabel
%25 = OpVariable %26 Function
diff --git a/tests/out/skybox.spvasm b/tests/out/skybox.spvasm
--- a/tests/out/skybox.spvasm
+++ b/tests/out/skybox.spvasm
@@ -90,44 +91,44 @@ OpStore %27 %42
%49 = OpFMul %7 %48 %6
%50 = OpFSub %7 %49 %8
%51 = OpCompositeConstruct %10 %46 %50 %9 %8
-%53 = OpAccessChain %52 %19 %5
-%54 = OpLoad %13 %53
-%55 = OpCompositeExtract %10 %54 0
-%56 = OpVectorShuffle %11 %55 %55 0 1 2
-%57 = OpAccessChain %52 %19 %5
-%58 = OpLoad %13 %57
-%59 = OpCompositeExtract %10 %58 1
-%60 = OpVectorShuffle %11 %59 %59 0 1 2
-%61 = OpAccessChain %52 %19 %5
-%62 = OpLoad %13 %61
-%63 = OpCompositeExtract %10 %62 2
-%64 = OpVectorShuffle %11 %63 %63 0 1 2
-%65 = OpCompositeConstruct %16 %56 %60 %64
-%66 = OpTranspose %16 %65
-%68 = OpAccessChain %52 %19 %67
-%69 = OpLoad %13 %68
-%70 = OpMatrixTimesVector %10 %69 %51
-%71 = OpVectorShuffle %11 %70 %70 0 1 2
-%72 = OpMatrixTimesVector %11 %66 %71
-%73 = OpCompositeConstruct %12 %51 %72
-%74 = OpCompositeExtract %10 %73 0
-OpStore %32 %74
-%75 = OpCompositeExtract %11 %73 1
-OpStore %34 %75
+%54 = OpAccessChain %52 %19 %53
+%55 = OpLoad %13 %54
+%56 = OpCompositeExtract %10 %55 0
+%57 = OpVectorShuffle %11 %56 %56 0 1 2
+%58 = OpAccessChain %52 %19 %53
+%59 = OpLoad %13 %58
+%60 = OpCompositeExtract %10 %59 1
+%61 = OpVectorShuffle %11 %60 %60 0 1 2
+%62 = OpAccessChain %52 %19 %53
+%63 = OpLoad %13 %62
+%64 = OpCompositeExtract %10 %63 2
+%65 = OpVectorShuffle %11 %64 %64 0 1 2
+%66 = OpCompositeConstruct %16 %57 %61 %65
+%67 = OpTranspose %16 %66
+%69 = OpAccessChain %52 %19 %68
+%70 = OpLoad %13 %69
+%71 = OpMatrixTimesVector %10 %70 %51
+%72 = OpVectorShuffle %11 %71 %71 0 1 2
+%73 = OpMatrixTimesVector %11 %67 %72
+%74 = OpCompositeConstruct %12 %51 %73
+%75 = OpCompositeExtract %10 %74 0
+OpStore %32 %75
+%76 = OpCompositeExtract %11 %74 1
+OpStore %34 %76
OpReturn
OpFunctionEnd
-%85 = OpFunction %2 None %37
-%76 = OpLabel
-%80 = OpLoad %10 %78
-%83 = OpLoad %11 %81
-%77 = OpCompositeConstruct %12 %80 %83
-%86 = OpLoad %17 %21
-%87 = OpLoad %18 %23
-OpBranch %88
-%88 = OpLabel
-%89 = OpCompositeExtract %11 %77 1
-%91 = OpSampledImage %90 %86 %87
-%92 = OpImageSampleImplicitLod %10 %91 %89
-OpStore %84 %92
+%86 = OpFunction %2 None %37
+%77 = OpLabel
+%81 = OpLoad %10 %79
+%84 = OpLoad %11 %82
+%78 = OpCompositeConstruct %12 %81 %84
+%87 = OpLoad %17 %21
+%88 = OpLoad %18 %23
+OpBranch %89
+%89 = OpLabel
+%90 = OpCompositeExtract %11 %78 1
+%92 = OpSampledImage %91 %87 %88
+%93 = OpImageSampleImplicitLod %10 %92 %90
+OpStore %85 %93
OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/texture-array.spvasm b/tests/out/texture-array.spvasm
--- a/tests/out/texture-array.spvasm
+++ b/tests/out/texture-array.spvasm
@@ -1,7 +1,7 @@
; SPIR-V
; Version: 1.5
; Generator: rspirv
-; Bound: 45
+; Bound: 43
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
diff --git a/tests/out/texture-array.spvasm b/tests/out/texture-array.spvasm
--- a/tests/out/texture-array.spvasm
+++ b/tests/out/texture-array.spvasm
@@ -48,10 +48,8 @@ OpDecorate %22 Location 1
%22 = OpVariable %23 Output
%25 = OpTypeFunction %2
%30 = OpTypePointer PushConstant %4
-%31 = OpTypeInt 32 1
-%32 = OpConstant %31 0
-%35 = OpTypeBool
-%40 = OpTypeSampledImage %5
+%33 = OpTypeBool
+%38 = OpTypeSampledImage %5
%24 = OpFunction %2 None %25
%18 = OpLabel
%21 = OpLoad %9 %19
diff --git a/tests/out/texture-array.spvasm b/tests/out/texture-array.spvasm
--- a/tests/out/texture-array.spvasm
+++ b/tests/out/texture-array.spvasm
@@ -60,21 +58,21 @@ OpDecorate %22 Location 1
%28 = OpLoad %7 %14
OpBranch %29
%29 = OpLabel
-%33 = OpAccessChain %30 %16 %32
-%34 = OpLoad %4 %33
-%36 = OpIEqual %35 %34 %3
-OpSelectionMerge %37 None
-OpBranchConditional %36 %38 %39
-%38 = OpLabel
-%41 = OpSampledImage %40 %26 %28
+%31 = OpAccessChain %30 %16 %3
+%32 = OpLoad %4 %31
+%34 = OpIEqual %33 %32 %3
+OpSelectionMerge %35 None
+OpBranchConditional %34 %36 %37
+%36 = OpLabel
+%39 = OpSampledImage %38 %26 %28
+%40 = OpImageSampleImplicitLod %10 %39 %21
+OpStore %22 %40
+OpReturn
+%37 = OpLabel
+%41 = OpSampledImage %38 %27 %28
%42 = OpImageSampleImplicitLod %10 %41 %21
OpStore %22 %42
OpReturn
-%39 = OpLabel
-%43 = OpSampledImage %40 %27 %28
-%44 = OpImageSampleImplicitLod %10 %43 %21
-OpStore %22 %44
-OpReturn
-%37 = OpLabel
+%35 = OpLabel
OpReturn
OpFunctionEnd
\ No newline at end of file
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -252,6 +252,10 @@ fn convert_wgsl() {
Targets::SPIRV | Targets::METAL | Targets::GLSL,
),
("access", Targets::SPIRV | Targets::METAL),
+ (
+ "control-flow",
+ Targets::SPIRV | Targets::METAL | Targets::GLSL,
+ ),
];
for &(name, targets) in inputs.iter() {
|
Control barriers
Upstream - https://github.com/gpuweb/gpuweb/issues/1374
Example - https://github.com/gfx-rs/wgpu/issues/1264
> thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: UnsupportedInstruction(Function, ControlBarrier)', bin/convert.rs:108:64
|
2021-05-03T12:28:51Z
|
0.4
|
2021-05-06T18:05:10Z
|
575304a50c102f2e2a3a622b4be567c0ccf6e6c0
|
[
"convert_wgsl"
] |
[
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_non_unique",
"back::msl::test_error_size",
"arena::tests::fetch_or_append_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::wgsl::lexer::test_tokens",
"front::spv::test::parse",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"back::msl::writer::test_stack_size",
"front::wgsl::tests::parse_array_length",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_expressions",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::functions",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_texture_store",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::control_flow",
"function_without_identifier",
"invalid_float",
"invalid_integer",
"invalid_scalar_width",
"parse_glsl",
"convert_glsl_quad",
"convert_spv_quad_vert",
"convert_spv_shadow"
] |
[] |
[] |
|
gfx-rs/naga
| 749
|
gfx-rs__naga-749
|
[
"646"
] |
36bace2b41a776caa12d2e0ecac9991c08204aa6
|
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -138,7 +138,12 @@ impl<'a> Display for TypeContext<'a> {
};
let (texture_str, msaa_str, kind, access) = match class {
crate::ImageClass::Sampled { kind, multi } => {
- ("texture", if multi { "_ms" } else { "" }, kind, "sample")
+ let (msaa_str, access) = if multi {
+ ("_ms", "read")
+ } else {
+ ("", "sample")
+ };
+ ("texture", msaa_str, kind, access)
}
crate::ImageClass::Depth => ("depth", "", crate::ScalarKind::Float, "sample"),
crate::ImageClass::Storage(format) => {
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -510,9 +515,9 @@ impl<W: Write> Writer<W> {
write!(self.out, ")")?;
}
crate::ImageDimension::Cube => {
- write!(self.out, "int(")?;
+ write!(self.out, "int3(")?;
self.put_image_query(image, "width", level, context)?;
- write!(self.out, ").xxx")?;
+ write!(self.out, ")")?;
}
}
Ok(())
diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs
--- a/src/back/spv/instructions.rs
+++ b/src/back/spv/instructions.rs
@@ -594,6 +594,14 @@ impl super::Instruction {
instruction
}
+ pub(super) fn image_query(op: Op, result_type_id: Word, id: Word, image: Word) -> Self {
+ let mut instruction = Self::new(op);
+ instruction.set_type(result_type_id);
+ instruction.set_result(id);
+ instruction.add_operand(image);
+ instruction
+ }
+
//
// Conversion Instructions
//
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -21,6 +21,8 @@ pub enum Error {
MissingCapabilities(Vec<spirv::Capability>),
#[error("unimplemented {0}")]
FeatureNotImplemented(&'static str),
+ #[error("module is not validated properly: {0}")]
+ Validation(&'static str),
}
#[derive(Default)]
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -186,7 +188,7 @@ fn map_dim(dim: crate::ImageDimension) -> spirv::Dim {
match dim {
crate::ImageDimension::D1 => spirv::Dim::Dim1D,
crate::ImageDimension::D2 => spirv::Dim::Dim2D,
- crate::ImageDimension::D3 => spirv::Dim::Dim2D,
+ crate::ImageDimension::D3 => spirv::Dim::Dim3D,
crate::ImageDimension::Cube => spirv::Dim::DimCube,
}
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1261,11 +1263,14 @@ impl Writer {
crate::VectorSize::Bi => crate::VectorSize::Tri,
crate::VectorSize::Tri => crate::VectorSize::Quad,
crate::VectorSize::Quad => {
- unimplemented!("Unable to extend the vec4 coordinate")
+ return Err(Error::Validation("extending vec4 coordinate"));
}
}
}
- ref other => unimplemented!("wrong coordinate type {:?}", other),
+ ref other => {
+ log::error!("wrong coordinate type {:?}", other);
+ return Err(Error::Validation("coordinate type"));
+ }
};
let array_index_f32_id = self.id_gen.next();
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1894,12 +1899,16 @@ impl Writer {
instruction.add_operand(index_id);
}
- if instruction.type_id != Some(result_type_id) {
+ let inst_type_id = instruction.type_id;
+ block.body.push(instruction);
+ if inst_type_id != Some(result_type_id) {
let sub_id = self.id_gen.next();
- let index_id = self.get_index_constant(0, &ir_module.types)?;
- let sub_instruction =
- Instruction::vector_extract_dynamic(result_type_id, sub_id, id, index_id);
- block.body.push(sub_instruction);
+ block.body.push(Instruction::composite_extract(
+ result_type_id,
+ sub_id,
+ id,
+ &[0],
+ ));
sub_id
} else {
id
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2062,10 +2071,12 @@ impl Writer {
if needs_sub_access {
let sub_id = self.id_gen.next();
- let index_id = self.get_index_constant(0, &ir_module.types)?;
- let sub_instruction =
- Instruction::vector_extract_dynamic(result_type_id, sub_id, id, index_id);
- block.body.push(sub_instruction);
+ block.body.push(Instruction::composite_extract(
+ result_type_id,
+ sub_id,
+ id,
+ &[0],
+ ));
sub_id
} else {
id
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -2098,9 +2109,147 @@ impl Writer {
});
id
}
- crate::Expression::ImageQuery { .. }
- | crate::Expression::Relational { .. }
- | crate::Expression::ArrayLength(_) => {
+ crate::Expression::ImageQuery { image, query } => {
+ use crate::{ImageClass as Ic, ImageDimension as Id, ImageQuery as Iq};
+
+ let image_id = self.get_expression_global(ir_function, image);
+ let image_type = fun_info[image].ty.handle().unwrap();
+ let (dim, arrayed, class) = match ir_module.types[image_type].inner {
+ crate::TypeInner::Image {
+ dim,
+ arrayed,
+ class,
+ } => (dim, arrayed, class),
+ _ => {
+ return Err(Error::Validation("image type"));
+ }
+ };
+
+ match query {
+ Iq::Size { level } => {
+ let dim_coords = match dim {
+ Id::D1 => 1,
+ Id::D2 | Id::Cube => 2,
+ Id::D3 => 3,
+ };
+ let extended_size_type_id = {
+ let array_coords = if arrayed { 1 } else { 0 };
+ let vector_size = match dim_coords + array_coords {
+ 2 => Some(crate::VectorSize::Bi),
+ 3 => Some(crate::VectorSize::Tri),
+ 4 => Some(crate::VectorSize::Quad),
+ _ => None,
+ };
+ self.get_type_id(
+ &ir_module.types,
+ LookupType::Local(LocalType::Value {
+ vector_size,
+ kind: crate::ScalarKind::Sint,
+ width: 4,
+ pointer_class: None,
+ }),
+ )?
+ };
+
+ let (query_op, level_id) = match class {
+ Ic::Storage(_) => (spirv::Op::ImageQuerySize, None),
+ _ => {
+ let level_id = match level {
+ Some(expr) => self.cached[expr],
+ None => self.get_index_constant(0, &ir_module.types)?,
+ };
+ (spirv::Op::ImageQuerySizeLod, Some(level_id))
+ }
+ };
+ // The ID of the vector returned by SPIR-V, which contains the dimensions
+ // as well as the layer count.
+ let id_extended = self.id_gen.next();
+ let mut inst = Instruction::image_query(
+ query_op,
+ extended_size_type_id,
+ id_extended,
+ image_id,
+ );
+ if let Some(expr_id) = level_id {
+ inst.add_operand(expr_id);
+ }
+ block.body.push(inst);
+
+ if result_type_id != extended_size_type_id {
+ let id = self.id_gen.next();
+ let components = match dim {
+ // always pick the first component, and duplicate it for all 3 dimensions
+ Id::Cube => &[0u32, 0, 0][..],
+ _ => &[0u32, 1, 2, 3][..dim_coords],
+ };
+ block.body.push(Instruction::vector_shuffle(
+ result_type_id,
+ id,
+ id_extended,
+ id_extended,
+ components,
+ ));
+ id
+ } else {
+ id_extended
+ }
+ }
+ Iq::NumLevels => {
+ let id = self.id_gen.next();
+ block.body.push(Instruction::image_query(
+ spirv::Op::ImageQueryLevels,
+ result_type_id,
+ id,
+ image_id,
+ ));
+ id
+ }
+ Iq::NumLayers => {
+ let vec_size = match dim {
+ Id::D1 => crate::VectorSize::Bi,
+ Id::D2 | Id::Cube => crate::VectorSize::Tri,
+ Id::D3 => crate::VectorSize::Quad,
+ };
+ let extended_size_type_id = self.get_type_id(
+ &ir_module.types,
+ LookupType::Local(LocalType::Value {
+ vector_size: Some(vec_size),
+ kind: crate::ScalarKind::Sint,
+ width: 4,
+ pointer_class: None,
+ }),
+ )?;
+ let id_extended = self.id_gen.next();
+ let mut inst = Instruction::image_query(
+ spirv::Op::ImageQuerySizeLod,
+ extended_size_type_id,
+ id_extended,
+ image_id,
+ );
+ inst.add_operand(self.get_index_constant(0, &ir_module.types)?);
+ block.body.push(inst);
+ let id = self.id_gen.next();
+ block.body.push(Instruction::composite_extract(
+ result_type_id,
+ id,
+ id_extended,
+ &[vec_size as u32 - 1],
+ ));
+ id
+ }
+ Iq::NumSamples => {
+ let id = self.id_gen.next();
+ block.body.push(Instruction::image_query(
+ spirv::Op::ImageQuerySamples,
+ result_type_id,
+ id,
+ image_id,
+ ));
+ id
+ }
+ }
+ }
+ crate::Expression::Relational { .. } | crate::Expression::ArrayLength(_) => {
log::error!("unimplemented {:?}", ir_function.expressions[expr_handle]);
return Err(Error::FeatureNotImplemented("expression"));
}
|
diff --git a/tests/in/image-copy.wgsl /dev/null
--- a/tests/in/image-copy.wgsl
+++ /dev/null
@@ -1,16 +0,0 @@
-[[group(0), binding(1)]]
-var image_src: [[access(read)]] texture_storage_2d<rgba8uint>;
-[[group(0), binding(2)]]
-var image_dst: [[access(write)]] texture_storage_1d<r32uint>;
-
-[[stage(compute), workgroup_size(16)]]
-fn main(
- [[builtin(local_invocation_id)]] local_id: vec3<u32>,
- //TODO: https://github.com/gpuweb/gpuweb/issues/1590
- //[[builtin(workgroup_size)]] wg_size: vec3<u32>
-) {
- let dim = textureDimensions(image_src);
- let itc = dim * vec2<i32>(local_id.xy) % vec2<i32>(10, 20);
- let value = textureLoad(image_src, itc);
- textureStore(image_dst, itc.x, value);
-}
diff --git a/tests/in/image-copy.param.ron b/tests/in/image.param.ron
--- a/tests/in/image-copy.param.ron
+++ b/tests/in/image.param.ron
@@ -1,6 +1,6 @@
(
spv_version: (1, 1),
- spv_capabilities: [ Shader, Image1D, Sampled1D ],
+ spv_capabilities: [ Shader, ImageQuery, Image1D, Sampled1D ],
spv_debug: true,
spv_adjust_coordinate_space: false,
msl_custom: false,
diff --git /dev/null b/tests/in/image.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/in/image.wgsl
@@ -0,0 +1,60 @@
+[[group(0), binding(1)]]
+var image_src: [[access(read)]] texture_storage_2d<rgba8uint>;
+[[group(0), binding(2)]]
+var image_dst: [[access(write)]] texture_storage_1d<r32uint>;
+
+[[stage(compute), workgroup_size(16)]]
+fn main(
+ [[builtin(local_invocation_id)]] local_id: vec3<u32>,
+ //TODO: https://github.com/gpuweb/gpuweb/issues/1590
+ //[[builtin(workgroup_size)]] wg_size: vec3<u32>
+) {
+ let dim = textureDimensions(image_src);
+ let itc = dim * vec2<i32>(local_id.xy) % vec2<i32>(10, 20);
+ let value = textureLoad(image_src, itc);
+ textureStore(image_dst, itc.x, value);
+}
+
+[[group(0), binding(0)]]
+var image_1d: texture_1d<f32>;
+[[group(0), binding(1)]]
+var image_2d: texture_2d<f32>;
+[[group(0), binding(2)]]
+var image_2d_array: texture_2d_array<f32>;
+[[group(0), binding(3)]]
+var image_cube: texture_cube<f32>;
+[[group(0), binding(4)]]
+var image_cube_array: texture_cube_array<f32>;
+[[group(0), binding(5)]]
+var image_3d: texture_3d<f32>;
+[[group(0), binding(6)]]
+var image_aa: texture_multisampled_2d<f32>;
+
+[[stage(vertex)]]
+fn queries() -> [[builtin(position)]] vec4<f32> {
+ let dim_1d = textureDimensions(image_1d);
+ let dim_2d = textureDimensions(image_2d);
+ let num_levels_2d = textureNumLevels(image_2d);
+ let dim_2d_lod = textureDimensions(image_2d, 1);
+ let dim_2d_array = textureDimensions(image_2d_array);
+ let num_levels_2d_array = textureNumLevels(image_2d_array);
+ let dim_2d_array_lod = textureDimensions(image_2d_array, 1);
+ let num_layers_2d = textureNumLayers(image_2d_array);
+ let dim_cube = textureDimensions(image_cube);
+ let num_levels_cube = textureNumLevels(image_cube);
+ let dim_cube_lod = textureDimensions(image_cube, 1);
+ let dim_cube_array = textureDimensions(image_cube_array);
+ let num_levels_cube_array = textureNumLevels(image_cube_array);
+ let dim_cube_array_lod = textureDimensions(image_cube_array, 1);
+ let num_layers_cube = textureNumLayers(image_cube_array);
+ let dim_3d = textureDimensions(image_3d);
+ let num_levels_3d = textureNumLevels(image_3d);
+ let dim_3d_lod = textureDimensions(image_3d, 1);
+ let num_samples_aa = textureNumSamples(image_aa);
+
+ let sum = dim_1d + dim_2d.y + dim_2d_lod.y + dim_2d_array.y + dim_2d_array_lod.y +
+ num_layers_2d + dim_cube.y + dim_cube_lod.y + dim_cube_array.y + dim_cube_array_lod.y +
+ num_layers_cube + dim_3d.z + dim_3d_lod.z + num_samples_aa +
+ num_levels_2d + num_levels_2d_array + num_levels_3d + num_levels_cube + num_levels_cube_array;
+ return vec4<f32>(f32(sum));
+}
diff --git a/tests/out/image-copy.msl /dev/null
--- a/tests/out/image-copy.msl
+++ /dev/null
@@ -1,16 +0,0 @@
-#include <metal_stdlib>
-#include <simd/simd.h>
-
-
-struct main1Input {
-};
-kernel void main1(
- metal::uint3 local_id [[thread_position_in_threadgroup]]
-, metal::texture2d<uint, metal::access::read> image_src [[user(fake0)]]
-, metal::texture1d<uint, metal::access::write> image_dst [[user(fake0)]]
-) {
- metal::int2 _e10 = (int2(image_src.get_width(), image_src.get_height()) * static_cast<int2>(local_id.xy)) % metal::int2(10, 20);
- metal::uint4 _e11 = image_src.read(metal::uint2(_e10));
- image_dst.write(_e11, metal::uint(_e10.x));
- return;
-}
diff --git /dev/null b/tests/out/image.msl
new file mode 100644
--- /dev/null
+++ b/tests/out/image.msl
@@ -0,0 +1,32 @@
+#include <metal_stdlib>
+#include <simd/simd.h>
+
+
+struct main1Input {
+};
+kernel void main1(
+ metal::uint3 local_id [[thread_position_in_threadgroup]]
+, metal::texture2d<uint, metal::access::read> image_src [[user(fake0)]]
+, metal::texture1d<uint, metal::access::write> image_dst [[user(fake0)]]
+) {
+ metal::int2 _e10 = (int2(image_src.get_width(), image_src.get_height()) * static_cast<int2>(local_id.xy)) % metal::int2(10, 20);
+ metal::uint4 _e11 = image_src.read(metal::uint2(_e10));
+ image_dst.write(_e11, metal::uint(_e10.x));
+ return;
+}
+
+
+struct queriesOutput {
+ metal::float4 member1 [[position]];
+};
+vertex queriesOutput queries(
+ metal::texture1d<float, metal::access::sample> image_1d [[user(fake0)]]
+, metal::texture2d<float, metal::access::sample> image_2d [[user(fake0)]]
+, metal::texture2d_array<float, metal::access::sample> image_2d_array [[user(fake0)]]
+, metal::texturecube<float, metal::access::sample> image_cube [[user(fake0)]]
+, metal::texturecube_array<float, metal::access::sample> image_cube_array [[user(fake0)]]
+, metal::texture3d<float, metal::access::sample> image_3d [[user(fake0)]]
+, metal::texture2d_ms<float, metal::access::read> image_aa [[user(fake0)]]
+) {
+ return queriesOutput { float4(static_cast<float>((((((((((((((((((int(image_1d.get_width()) + int2(image_2d.get_width(), image_2d.get_height()).y) + int2(image_2d.get_width(1), image_2d.get_height(1)).y) + int2(image_2d_array.get_width(), image_2d_array.get_height()).y) + int2(image_2d_array.get_width(1), image_2d_array.get_height(1)).y) + int(image_2d_array.get_array_size())) + int3(image_cube.get_width()).y) + int3(image_cube.get_width(1)).y) + int3(image_cube_array.get_width()).y) + int3(image_cube_array.get_width(1)).y) + int(image_cube_array.get_array_size())) + int3(image_3d.get_width(), image_3d.get_height(), image_3d.get_depth()).z) + int3(image_3d.get_width(1), image_3d.get_height(1), image_3d.get_depth(1)).z) + int(image_aa.get_num_samples())) + int(image_2d.get_num_mip_levels())) + int(image_2d_array.get_num_mip_levels())) + int(image_3d.get_num_mip_levels())) + int(image_cube.get_num_mip_levels())) + int(image_cube_array.get_num_mip_levels()))) };
+}
diff --git /dev/null b/tests/out/image.spvasm
new file mode 100644
--- /dev/null
+++ b/tests/out/image.spvasm
@@ -0,0 +1,181 @@
+; SPIR-V
+; Version: 1.1
+; Generator: rspirv
+; Bound: 127
+OpCapability ImageQuery
+OpCapability Image1D
+OpCapability Shader
+OpCapability Sampled1D
+%1 = OpExtInstImport "GLSL.std.450"
+OpMemoryModel Logical GLSL450
+OpEntryPoint GLCompute %43 "main" %40
+OpEntryPoint Vertex %61 "queries" %59
+OpExecutionMode %43 LocalSize 16 1 1
+OpSource GLSL 450
+OpName %21 "image_src"
+OpName %23 "image_dst"
+OpName %25 "image_1d"
+OpName %27 "image_2d"
+OpName %29 "image_2d_array"
+OpName %31 "image_cube"
+OpName %33 "image_cube_array"
+OpName %35 "image_3d"
+OpName %37 "image_aa"
+OpName %40 "local_id"
+OpName %43 "main"
+OpName %61 "queries"
+OpDecorate %21 NonWritable
+OpDecorate %21 DescriptorSet 0
+OpDecorate %21 Binding 1
+OpDecorate %23 NonReadable
+OpDecorate %23 DescriptorSet 0
+OpDecorate %23 Binding 2
+OpDecorate %25 DescriptorSet 0
+OpDecorate %25 Binding 0
+OpDecorate %27 DescriptorSet 0
+OpDecorate %27 Binding 1
+OpDecorate %29 DescriptorSet 0
+OpDecorate %29 Binding 2
+OpDecorate %31 DescriptorSet 0
+OpDecorate %31 Binding 3
+OpDecorate %33 DescriptorSet 0
+OpDecorate %33 Binding 4
+OpDecorate %35 DescriptorSet 0
+OpDecorate %35 Binding 5
+OpDecorate %37 DescriptorSet 0
+OpDecorate %37 Binding 6
+OpDecorate %40 BuiltIn LocalInvocationId
+OpDecorate %59 BuiltIn Position
+%2 = OpTypeVoid
+%4 = OpTypeInt 32 1
+%3 = OpConstant %4 10
+%5 = OpConstant %4 20
+%6 = OpConstant %4 1
+%8 = OpTypeInt 32 0
+%7 = OpTypeImage %8 2D 0 0 0 2 Rgba8ui
+%9 = OpTypeImage %8 1D 0 0 0 2 R32ui
+%10 = OpTypeVector %8 3
+%11 = OpTypeVector %4 2
+%13 = OpTypeFloat 32
+%12 = OpTypeImage %13 1D 0 0 0 1 Unknown
+%14 = OpTypeImage %13 2D 0 0 0 1 Unknown
+%15 = OpTypeImage %13 2D 0 1 0 1 Unknown
+%16 = OpTypeImage %13 Cube 0 0 0 1 Unknown
+%17 = OpTypeImage %13 Cube 0 1 0 1 Unknown
+%18 = OpTypeImage %13 3D 0 0 0 1 Unknown
+%19 = OpTypeImage %13 2D 0 0 1 1 Unknown
+%20 = OpTypeVector %13 4
+%22 = OpTypePointer UniformConstant %7
+%21 = OpVariable %22 UniformConstant
+%24 = OpTypePointer UniformConstant %9
+%23 = OpVariable %24 UniformConstant
+%26 = OpTypePointer UniformConstant %12
+%25 = OpVariable %26 UniformConstant
+%28 = OpTypePointer UniformConstant %14
+%27 = OpVariable %28 UniformConstant
+%30 = OpTypePointer UniformConstant %15
+%29 = OpVariable %30 UniformConstant
+%32 = OpTypePointer UniformConstant %16
+%31 = OpVariable %32 UniformConstant
+%34 = OpTypePointer UniformConstant %17
+%33 = OpVariable %34 UniformConstant
+%36 = OpTypePointer UniformConstant %18
+%35 = OpVariable %36 UniformConstant
+%38 = OpTypePointer UniformConstant %19
+%37 = OpVariable %38 UniformConstant
+%41 = OpTypePointer Input %10
+%40 = OpVariable %41 Input
+%44 = OpTypeFunction %2
+%49 = OpTypeVector %8 2
+%55 = OpTypeVector %8 4
+%60 = OpTypePointer Output %20
+%59 = OpVariable %60 Output
+%70 = OpConstant %4 0
+%75 = OpTypeVector %4 3
+%43 = OpFunction %2 None %44
+%39 = OpLabel
+%42 = OpLoad %10 %40
+%45 = OpLoad %7 %21
+%46 = OpLoad %9 %23
+OpBranch %47
+%47 = OpLabel
+%48 = OpImageQuerySize %11 %45
+%50 = OpVectorShuffle %49 %42 %42 0 1
+%51 = OpBitcast %11 %50
+%52 = OpIMul %11 %48 %51
+%53 = OpCompositeConstruct %11 %3 %5
+%54 = OpSMod %11 %52 %53
+%56 = OpImageRead %55 %45 %54
+%57 = OpCompositeExtract %4 %54 0
+OpImageWrite %46 %57 %56
+OpReturn
+OpFunctionEnd
+%61 = OpFunction %2 None %44
+%58 = OpLabel
+%62 = OpLoad %12 %25
+%63 = OpLoad %14 %27
+%64 = OpLoad %15 %29
+%65 = OpLoad %16 %31
+%66 = OpLoad %17 %33
+%67 = OpLoad %18 %35
+%68 = OpLoad %19 %37
+OpBranch %69
+%69 = OpLabel
+%71 = OpImageQuerySizeLod %4 %62 %70
+%72 = OpImageQuerySizeLod %11 %63 %70
+%73 = OpImageQueryLevels %4 %63
+%74 = OpImageQuerySizeLod %11 %63 %6
+%76 = OpImageQuerySizeLod %75 %64 %70
+%77 = OpVectorShuffle %11 %76 %76 0 1
+%78 = OpImageQueryLevels %4 %64
+%79 = OpImageQuerySizeLod %75 %64 %6
+%80 = OpVectorShuffle %11 %79 %79 0 1
+%81 = OpImageQuerySizeLod %75 %64 %70
+%82 = OpCompositeExtract %4 %81 2
+%83 = OpImageQuerySizeLod %11 %65 %70
+%84 = OpVectorShuffle %75 %83 %83 0 0 0
+%85 = OpImageQueryLevels %4 %65
+%86 = OpImageQuerySizeLod %11 %65 %6
+%87 = OpVectorShuffle %75 %86 %86 0 0 0
+%88 = OpImageQuerySizeLod %75 %66 %70
+%89 = OpImageQueryLevels %4 %66
+%90 = OpImageQuerySizeLod %75 %66 %6
+%91 = OpImageQuerySizeLod %75 %66 %70
+%92 = OpCompositeExtract %4 %91 2
+%93 = OpImageQuerySizeLod %75 %67 %70
+%94 = OpImageQueryLevels %4 %67
+%95 = OpImageQuerySizeLod %75 %67 %6
+%96 = OpImageQuerySamples %4 %68
+%97 = OpCompositeExtract %4 %72 1
+%98 = OpIAdd %4 %71 %97
+%99 = OpCompositeExtract %4 %74 1
+%100 = OpIAdd %4 %98 %99
+%101 = OpCompositeExtract %4 %77 1
+%102 = OpIAdd %4 %100 %101
+%103 = OpCompositeExtract %4 %80 1
+%104 = OpIAdd %4 %102 %103
+%105 = OpIAdd %4 %104 %82
+%106 = OpCompositeExtract %4 %84 1
+%107 = OpIAdd %4 %105 %106
+%108 = OpCompositeExtract %4 %87 1
+%109 = OpIAdd %4 %107 %108
+%110 = OpCompositeExtract %4 %88 1
+%111 = OpIAdd %4 %109 %110
+%112 = OpCompositeExtract %4 %90 1
+%113 = OpIAdd %4 %111 %112
+%114 = OpIAdd %4 %113 %92
+%115 = OpCompositeExtract %4 %93 2
+%116 = OpIAdd %4 %114 %115
+%117 = OpCompositeExtract %4 %95 2
+%118 = OpIAdd %4 %116 %117
+%119 = OpIAdd %4 %118 %96
+%120 = OpIAdd %4 %119 %73
+%121 = OpIAdd %4 %120 %78
+%122 = OpIAdd %4 %121 %94
+%123 = OpIAdd %4 %122 %85
+%124 = OpIAdd %4 %123 %89
+%125 = OpConvertSToF %13 %124
+%126 = OpCompositeConstruct %20 %125 %125 %125 %125
+OpStore %59 %126
+OpReturn
+OpFunctionEnd
\ No newline at end of file
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -235,8 +235,7 @@ fn convert_wgsl() {
Targets::SPIRV | Targets::METAL | Targets::IR | Targets::ANALYSIS,
),
("shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL),
- //SPIR-V is blocked by https://github.com/gfx-rs/naga/issues/646
- ("image-copy", Targets::METAL),
+ ("image", Targets::SPIRV | Targets::METAL),
("texture-array", Targets::SPIRV | Targets::METAL),
("operators", Targets::SPIRV | Targets::METAL | Targets::GLSL),
(
|
Implement image queries in SPIR-V backend
`Expression::ImageQuery { .. }` support is missing
|
2021-04-22T13:42:10Z
|
0.3
|
2021-04-23T16:31:37Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"convert_wgsl"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::spv::test::parse",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::lexer::test_tokens",
"front::wgsl::tests::parse_comment",
"back::msl::writer::test_stack_size",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_pointers",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_expressions",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_struct_instantiation",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_switch",
"front::glsl::parser_tests::textures",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::control_flow",
"function_without_identifier",
"invalid_float",
"invalid_integer",
"invalid_scalar_width",
"parse_glsl",
"convert_glsl_quad",
"convert_spv_quad_vert",
"convert_spv_shadow"
] |
[] |
[] |
|
gfx-rs/naga
| 723
|
gfx-rs__naga-723
|
[
"635"
] |
daf4c82376e10d03488d7c71773b2acc1b9f7de4
|
diff --git a/src/back/spv/instructions.rs b/src/back/spv/instructions.rs
--- a/src/back/spv/instructions.rs
+++ b/src/back/spv/instructions.rs
@@ -433,12 +433,12 @@ impl super::Instruction {
}
pub(super) fn store(
- pointer_type_id: Word,
+ pointer_id: Word,
object_id: Word,
memory_access: Option<spirv::MemoryAccess>,
) -> Self {
let mut instruction = Self::new(Op::Store);
- instruction.add_operand(pointer_type_id);
+ instruction.add_operand(pointer_id);
instruction.add_operand(object_id);
if let Some(memory_access) = memory_access {
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -70,6 +70,7 @@ struct Function {
signature: Option<Instruction>,
parameters: Vec<Instruction>,
variables: crate::FastHashMap<Handle<crate::LocalVariable>, LocalVariable>,
+ internal_variables: Vec<LocalVariable>,
blocks: Vec<Block>,
entry_point_context: Option<EntryPointContext>,
}
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -86,6 +87,9 @@ impl Function {
for local_var in self.variables.values() {
local_var.instruction.to_words(sink);
}
+ for internal_var in self.internal_variables.iter() {
+ internal_var.instruction.to_words(sink);
+ }
}
for instruction in block.body.iter() {
instruction.to_words(sink);
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -339,6 +343,20 @@ impl Writer {
}
}
+ fn get_expression_type_id(
+ &mut self,
+ arena: &Arena<crate::Type>,
+ tr: &TypeResolution,
+ ) -> Result<Word, Error> {
+ let lookup_ty = match *tr {
+ TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle),
+ TypeResolution::Value(ref inner) => {
+ LookupType::Local(self.physical_layout.make_local(inner).unwrap())
+ }
+ };
+ self.get_type_id(arena, lookup_ty)
+ }
+
fn get_pointer_id(
&mut self,
arena: &Arena<crate::Type>,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -649,11 +667,6 @@ impl Writer {
};
self.check(exec_model.required_capabilities())?;
- if self.flags.contains(WriterFlags::DEBUG) {
- self.debugs
- .push(Instruction::name(function_id, &entry_point.name));
- }
-
Ok(Instruction::entry_point(
exec_model,
function_id,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1288,23 +1301,74 @@ impl Writer {
})
}
+ #[allow(clippy::too_many_arguments)]
+ fn promote_access_expression_to_variable(
+ &mut self,
+ ir_types: &Arena<crate::Type>,
+ result_type_id: Word,
+ container_id: Word,
+ container_resolution: &TypeResolution,
+ index_id: Word,
+ element_ty: Handle<crate::Type>,
+ block: &mut Block,
+ ) -> Result<(Word, LocalVariable), Error> {
+ let container_type_id = self.get_expression_type_id(ir_types, container_resolution)?;
+ let pointer_type_id = self.id_gen.next();
+ Instruction::type_pointer(
+ pointer_type_id,
+ spirv::StorageClass::Function,
+ container_type_id,
+ )
+ .to_words(&mut self.logical_layout.declarations);
+
+ let variable = {
+ let id = self.id_gen.next();
+ LocalVariable {
+ id,
+ instruction: Instruction::variable(
+ pointer_type_id,
+ id,
+ spirv::StorageClass::Function,
+ None,
+ ),
+ }
+ };
+ block
+ .body
+ .push(Instruction::store(variable.id, container_id, None));
+
+ let element_pointer_id = self.id_gen.next();
+ let element_pointer_type_id =
+ self.get_pointer_id(ir_types, element_ty, spirv::StorageClass::Function)?;
+ block.body.push(Instruction::access_chain(
+ element_pointer_type_id,
+ element_pointer_id,
+ variable.id,
+ &[index_id],
+ ));
+ let id = self.id_gen.next();
+ block.body.push(Instruction::load(
+ result_type_id,
+ id,
+ element_pointer_id,
+ None,
+ ));
+
+ Ok((id, variable))
+ }
+
/// Cache an expression for a value.
- fn cache_expression_value<'a>(
+ fn cache_expression_value(
&mut self,
- ir_module: &'a crate::Module,
+ ir_module: &crate::Module,
ir_function: &crate::Function,
fun_info: &FunctionInfo,
expr_handle: Handle<crate::Expression>,
block: &mut Block,
function: &mut Function,
) -> Result<(), Error> {
- let result_lookup_ty = match fun_info[expr_handle].ty {
- TypeResolution::Handle(ty_handle) => LookupType::Handle(ty_handle),
- TypeResolution::Value(ref inner) => {
- LookupType::Local(self.physical_layout.make_local(inner).unwrap())
- }
- };
- let result_type_id = self.get_type_id(&ir_module.types, result_lookup_ty)?;
+ let result_type_id =
+ self.get_expression_type_id(&ir_module.types, &fun_info[expr_handle].ty)?;
let id = match ir_function.expressions[expr_handle] {
crate::Expression::Access { base, index } => {
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1318,10 +1382,10 @@ impl Writer {
0
} else {
let index_id = self.cached[index];
+ let base_id = self.cached[base];
match *fun_info[base].ty.inner_with(&ir_module.types) {
crate::TypeInner::Vector { .. } => {
let id = self.id_gen.next();
- let base_id = self.cached[base];
block.body.push(Instruction::vector_extract_dynamic(
result_type_id,
id,
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -1330,7 +1394,21 @@ impl Writer {
));
id
}
- //TODO: support `crate::TypeInner::Array { .. }` ?
+ crate::TypeInner::Array {
+ base: ty_element, ..
+ } => {
+ let (id, variable) = self.promote_access_expression_to_variable(
+ &ir_module.types,
+ result_type_id,
+ base_id,
+ &fun_info[base].ty,
+ index_id,
+ ty_element,
+ block,
+ )?;
+ function.internal_variables.push(variable);
+ id
+ }
ref other => {
log::error!("Unable to access {:?}", other);
return Err(Error::FeatureNotImplemented("access for type"));
|
diff --git /dev/null b/tests/in/access.param.ron
new file mode 100644
--- /dev/null
+++ b/tests/in/access.param.ron
@@ -0,0 +1,7 @@
+(
+ spv_version: (1, 1),
+ spv_capabilities: [ Shader, Image1D, Sampled1D ],
+ spv_debug: true,
+ spv_adjust_coordinate_space: false,
+ msl_custom: false,
+)
diff --git /dev/null b/tests/in/access.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/in/access.wgsl
@@ -0,0 +1,8 @@
+// This snapshot tests accessing various containers, dereferencing pointers.
+
+[[stage(vertex)]]
+fn foo([[builtin(vertex_index)]] vi: u32) -> [[builtin(position)]] vec4<f32> {
+ let array = array<i32, 5>(1, 2, 3, 4, 5);
+ let value = array[vi];
+ return vec4<f32>(vec4<i32>(value));
+}
diff --git a/tests/in/interpolate.param.ron b/tests/in/interpolate.param.ron
--- a/tests/in/interpolate.param.ron
+++ b/tests/in/interpolate.param.ron
@@ -4,5 +4,5 @@
spv_debug: true,
spv_adjust_coordinate_space: true,
msl_custom: false,
- glsl_desktop_version: Some(400)
+ glsl_desktop_version: Some(400)
)
diff --git a/tests/in/operators.wgsl b/tests/in/operators.wgsl
--- a/tests/in/operators.wgsl
+++ b/tests/in/operators.wgsl
@@ -1,6 +1,6 @@
[[stage(vertex)]]
fn splat() -> [[builtin(position)]] vec4<f32> {
- let a = (1.0 + vec2<f32>(2.0) - 3.0) / 4.0;
- let b = vec4<i32>(5) % 2;
- return a.xyxy + vec4<f32>(b);
+ let a = (1.0 + vec2<f32>(2.0) - 3.0) / 4.0;
+ let b = vec4<i32>(5) % 2;
+ return a.xyxy + vec4<f32>(b);
}
diff --git a/tests/in/shadow.param.ron b/tests/in/shadow.param.ron
--- a/tests/in/shadow.param.ron
+++ b/tests/in/shadow.param.ron
@@ -1,8 +1,8 @@
(
- spv_flow_dump_prefix: "",
- spv_version: (1, 2),
- spv_capabilities: [ Shader ],
- spv_debug: true,
- spv_adjust_coordinate_space: true,
- msl_custom: false,
+ spv_flow_dump_prefix: "",
+ spv_version: (1, 2),
+ spv_capabilities: [ Shader ],
+ spv_debug: true,
+ spv_adjust_coordinate_space: true,
+ msl_custom: false,
)
diff --git /dev/null b/tests/out/access.msl
new file mode 100644
--- /dev/null
+++ b/tests/out/access.msl
@@ -0,0 +1,15 @@
+#include <metal_stdlib>
+#include <simd/simd.h>
+
+typedef int type3[5];
+
+struct fooInput {
+};
+struct fooOutput {
+ metal::float4 member [[position]];
+};
+vertex fooOutput foo(
+ metal::uint vi [[vertex_id]]
+) {
+ return fooOutput { static_cast<float4>(type3 {1, 2, 3, 4, 5}[vi]) };
+}
diff --git /dev/null b/tests/out/access.spvasm
new file mode 100644
--- /dev/null
+++ b/tests/out/access.spvasm
@@ -0,0 +1,50 @@
+; SPIR-V
+; Version: 1.1
+; Generator: rspirv
+; Bound: 31
+OpCapability Image1D
+OpCapability Shader
+OpCapability Sampled1D
+%1 = OpExtInstImport "GLSL.std.450"
+OpMemoryModel Logical GLSL450
+OpEntryPoint Vertex %19 "foo" %14 %17
+OpSource GLSL 450
+OpName %14 "vi"
+OpName %19 "foo"
+OpDecorate %12 ArrayStride 4
+OpDecorate %14 BuiltIn VertexIndex
+OpDecorate %17 BuiltIn Position
+%2 = OpTypeVoid
+%4 = OpTypeInt 32 1
+%3 = OpConstant %4 5
+%5 = OpConstant %4 1
+%6 = OpConstant %4 2
+%7 = OpConstant %4 3
+%8 = OpConstant %4 4
+%9 = OpTypeInt 32 0
+%11 = OpTypeFloat 32
+%10 = OpTypeVector %11 4
+%12 = OpTypeArray %4 %3
+%15 = OpTypePointer Input %9
+%14 = OpVariable %15 Input
+%18 = OpTypePointer Output %10
+%17 = OpVariable %18 Output
+%20 = OpTypeFunction %2
+%23 = OpTypePointer Function %12
+%26 = OpTypePointer Function %4
+%28 = OpTypeVector %4 4
+%19 = OpFunction %2 None %20
+%13 = OpLabel
+%24 = OpVariable %23 Function
+%16 = OpLoad %9 %14
+OpBranch %21
+%21 = OpLabel
+%22 = OpCompositeConstruct %12 %5 %6 %7 %8 %3
+OpStore %24 %22
+%25 = OpAccessChain %26 %24 %16
+%27 = OpLoad %4 %25
+%29 = OpCompositeConstruct %28 %27 %27 %27 %27
+%30 = OpConvertSToF %10 %29
+OpStore %17 %30
+OpReturn
+OpFunctionEnd
\ No newline at end of file
diff --git a/tests/out/boids.spvasm b/tests/out/boids.spvasm
--- a/tests/out/boids.spvasm
+++ b/tests/out/boids.spvasm
@@ -38,7 +38,6 @@ OpName %36 "vel"
OpName %37 "i"
OpName %40 "global_invocation_id"
OpName %43 "main"
-OpName %43 "main"
OpMemberDecorate %16 0 Offset 0
OpMemberDecorate %16 1 Offset 8
OpDecorate %17 Block
diff --git a/tests/out/collatz.spvasm b/tests/out/collatz.spvasm
--- a/tests/out/collatz.spvasm
+++ b/tests/out/collatz.spvasm
@@ -17,7 +17,6 @@ OpName %15 "i"
OpName %18 "collatz_iterations"
OpName %45 "global_id"
OpName %48 "main"
-OpName %48 "main"
OpDecorate %8 ArrayStride 4
OpDecorate %9 Block
OpMemberDecorate %9 0 Offset 0
diff --git a/tests/out/interpolate.spvasm b/tests/out/interpolate.spvasm
--- a/tests/out/interpolate.spvasm
+++ b/tests/out/interpolate.spvasm
@@ -25,7 +25,6 @@ OpName %33 "centroid"
OpName %35 "sample"
OpName %37 "perspective"
OpName %38 "main"
-OpName %38 "main"
OpName %76 "position"
OpName %79 "flat"
OpName %82 "linear"
diff --git a/tests/out/interpolate.spvasm b/tests/out/interpolate.spvasm
--- a/tests/out/interpolate.spvasm
+++ b/tests/out/interpolate.spvasm
@@ -33,7 +32,6 @@ OpName %85 "centroid"
OpName %88 "sample"
OpName %91 "perspective"
OpName %93 "main"
-OpName %93 "main"
OpMemberDecorate %23 0 Offset 0
OpMemberDecorate %23 1 Offset 16
OpMemberDecorate %23 2 Offset 20
diff --git a/tests/out/quad.spvasm b/tests/out/quad.spvasm
--- a/tests/out/quad.spvasm
+++ b/tests/out/quad.spvasm
@@ -21,10 +21,8 @@ OpName %22 "uv"
OpName %24 "uv"
OpName %26 "position"
OpName %28 "main"
-OpName %28 "main"
OpName %48 "uv"
OpName %51 "main"
-OpName %51 "main"
OpMemberDecorate %9 0 Offset 0
OpMemberDecorate %9 1 Offset 16
OpDecorate %12 DescriptorSet 0
diff --git a/tests/out/shadow.spvasm b/tests/out/shadow.spvasm
--- a/tests/out/shadow.spvasm
+++ b/tests/out/shadow.spvasm
@@ -29,7 +29,6 @@ OpName %71 "i"
OpName %74 "raw_normal"
OpName %77 "position"
OpName %82 "fs_main"
-OpName %82 "fs_main"
OpDecorate %14 Block
OpMemberDecorate %14 0 Offset 0
OpMemberDecorate %17 0 Offset 0
diff --git a/tests/out/texture-array.spvasm b/tests/out/texture-array.spvasm
--- a/tests/out/texture-array.spvasm
+++ b/tests/out/texture-array.spvasm
@@ -16,7 +16,6 @@ OpName %14 "sampler"
OpName %16 "pc"
OpName %19 "tex_coord"
OpName %24 "main"
-OpName %24 "main"
OpDecorate %8 Block
OpMemberDecorate %8 0 Offset 0
OpDecorate %11 DescriptorSet 0
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -229,6 +229,7 @@ fn convert_wgsl() {
"interpolate",
Targets::SPIRV | Targets::METAL | Targets::GLSL,
),
+ ("access", Targets::SPIRV | Targets::METAL),
];
for &(name, targets) in inputs.iter() {
|
Indexing constant arrays in SPIR-V
```rust
struct VertexOutput {
[[builtin(position)]] position: vec4<f32>;
[[location(0)]] tex_coords: vec2<f32>;
};
[[stage(vertex)]]
fn vs_main([[builtin(vertex_index)]] index: u32) -> VertexOutput {
const triangle = array<vec2<f32>, 3u>(
vec2<f32>(-1.0, -1.0),
vec2<f32>( 3.0, -1.0),
vec2<f32>(-1.0, 3.0)
);
var out: VertexOutput;
out.position = vec4<f32>(triangle[index], 0.0, 1.0);
out.tex_coords = 0.5 * triangle[index] + vec2<f32>(0.5, 0.5);
return out;
}
[[group(0), binding(0)]]
var r_color: texture_2d<f32>;
[[group(0), binding(1)]]
var r_sampler: sampler;
[[stage(fragment)]]
fn fs_main(in: VertexOutput) -> [[location(0)]] vec4<f32> {
return textureSample(r_color, r_sampler, in.tex_coords);
}
```
See https://github.com/gfx-rs/wgpu/issues/1295
|
2021-04-16T11:12:42Z
|
0.3
|
2021-04-16T21:11:22Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"convert_wgsl"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::msl::test_error_size",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::layout::test_logical_layout_in_words",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"back::msl::writer::test_stack_size",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_pointers",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::functions",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_store",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::control_flow",
"function_without_identifier",
"invalid_integer",
"invalid_scalar_width",
"invalid_float",
"invalid_accessor",
"parse_glsl",
"convert_glsl_quad",
"convert_spv_quad_vert",
"convert_spv_shadow"
] |
[] |
[] |
|
gfx-rs/naga
| 714
|
gfx-rs__naga-714
|
[
"713"
] |
9cd2b04c04c9211488dbd7850ceb394c40599c3c
|
diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs
--- a/src/back/msl/mod.rs
+++ b/src/back/msl/mod.rs
@@ -36,10 +36,12 @@ mod writer;
pub use writer::Writer;
+pub type Slot = u8;
+
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub enum BindSamplerTarget {
- Resource(u8),
+ Resource(Slot),
Inline(Handle<sampler::InlineSampler>),
}
diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs
--- a/src/back/msl/mod.rs
+++ b/src/back/msl/mod.rs
@@ -47,9 +49,9 @@ pub enum BindSamplerTarget {
#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
pub struct BindTarget {
#[cfg_attr(feature = "deserialize", serde(default))]
- pub buffer: Option<u8>,
+ pub buffer: Option<Slot>,
#[cfg_attr(feature = "deserialize", serde(default))]
- pub texture: Option<u8>,
+ pub texture: Option<Slot>,
#[cfg_attr(feature = "deserialize", serde(default))]
pub sampler: Option<BindSamplerTarget>,
#[cfg_attr(feature = "deserialize", serde(default))]
diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs
--- a/src/back/msl/mod.rs
+++ b/src/back/msl/mod.rs
@@ -67,6 +69,18 @@ pub struct BindSource {
pub type BindingMap = FastHashMap<BindSource, BindTarget>;
+#[derive(Clone, Debug, Default, Hash, Eq, Ord, PartialEq, PartialOrd)]
+#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
+#[cfg_attr(feature = "deserialize", derive(serde::Deserialize))]
+pub struct PushConstantsMap {
+ #[cfg_attr(feature = "deserialize", serde(default))]
+ pub vs_buffer: Option<Slot>,
+ #[cfg_attr(feature = "deserialize", serde(default))]
+ pub fs_buffer: Option<Slot>,
+ #[cfg_attr(feature = "deserialize", serde(default))]
+ pub cs_buffer: Option<Slot>,
+}
+
enum ResolvedBinding {
BuiltIn(crate::BuiltIn),
Attribute(u32),
diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs
--- a/src/back/msl/mod.rs
+++ b/src/back/msl/mod.rs
@@ -101,6 +115,8 @@ pub enum Error {
pub enum EntryPointError {
#[error("mapping of {0:?} is missing")]
MissingBinding(BindSource),
+ #[error("mapping for push constants at stage {0:?} is missing")]
+ MissingPushConstants(crate::ShaderStage),
}
#[derive(Clone, Copy, Debug)]
diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs
--- a/src/back/msl/mod.rs
+++ b/src/back/msl/mod.rs
@@ -118,6 +134,8 @@ pub struct Options {
pub lang_version: (u8, u8),
/// Binding model mapping to Metal.
pub binding_map: BindingMap,
+ /// Push constants mapping to Metal.
+ pub push_constants_map: PushConstantsMap,
/// Samplers to be inlined into the code.
pub inline_samplers: Arena<sampler::InlineSampler>,
/// Make it possible to link different stages via SPIRV-Cross.
diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs
--- a/src/back/msl/mod.rs
+++ b/src/back/msl/mod.rs
@@ -131,6 +149,7 @@ impl Default for Options {
Options {
lang_version: (1, 0),
binding_map: BindingMap::default(),
+ push_constants_map: PushConstantsMap::default(),
inline_samplers: Arena::new(),
spirv_cross_compatibility: false,
fake_missing_bindings: true,
diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs
--- a/src/back/msl/mod.rs
+++ b/src/back/msl/mod.rs
@@ -185,7 +204,7 @@ impl Options {
}
}
- fn resolve_global_binding(
+ fn resolve_resource_binding(
&self,
stage: crate::ShaderStage,
res_binding: &crate::ResourceBinding,
diff --git a/src/back/msl/mod.rs b/src/back/msl/mod.rs
--- a/src/back/msl/mod.rs
+++ b/src/back/msl/mod.rs
@@ -204,6 +223,30 @@ impl Options {
None => Err(EntryPointError::MissingBinding(source)),
}
}
+
+ fn resolve_push_constants(
+ &self,
+ stage: crate::ShaderStage,
+ ) -> Result<ResolvedBinding, EntryPointError> {
+ let slot = match stage {
+ crate::ShaderStage::Vertex => self.push_constants_map.vs_buffer,
+ crate::ShaderStage::Fragment => self.push_constants_map.fs_buffer,
+ crate::ShaderStage::Compute => self.push_constants_map.cs_buffer,
+ };
+ match slot {
+ Some(slot) => Ok(ResolvedBinding::Resource(BindTarget {
+ buffer: Some(slot),
+ texture: None,
+ sampler: None,
+ mutable: false,
+ })),
+ None if self.fake_missing_bindings => Ok(ResolvedBinding::User {
+ prefix: "fake",
+ index: 0,
+ }),
+ None => Err(EntryPointError::MissingPushConstants(stage)),
+ }
+ }
}
impl ResolvedBinding {
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -321,6 +321,7 @@ impl crate::StorageClass {
crate::StorageClass::Uniform
| crate::StorageClass::Storage
| crate::StorageClass::Private
+ | crate::StorageClass::PushConstant
| crate::StorageClass::Handle => true,
_ => false,
}
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -1751,7 +1752,12 @@ impl<W: Write> Writer<W> {
.find_map(|(var_handle, var)| {
if !fun_info[var_handle].is_empty() {
if let Some(ref br) = var.binding {
- if let Err(e) = options.resolve_global_binding(ep.stage, br) {
+ if let Err(e) = options.resolve_resource_binding(ep.stage, br) {
+ return Some(e);
+ }
+ }
+ if var.class == crate::StorageClass::PushConstant {
+ if let Err(e) = options.resolve_push_constants(ep.stage) {
return Some(e);
}
}
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -1920,10 +1926,16 @@ impl<W: Write> Writer<W> {
if usage.is_empty() || var.class == crate::StorageClass::Private {
continue;
}
- let resolved = var
- .binding
- .as_ref()
- .map(|binding| options.resolve_global_binding(ep.stage, binding).unwrap());
+ // the resolves have already been checked for `!fake_missing_bindings` case
+ let resolved = match var.class {
+ crate::StorageClass::PushConstant => {
+ options.resolve_push_constants(ep.stage).ok()
+ }
+ crate::StorageClass::WorkGroup => None,
+ _ => options
+ .resolve_resource_binding(ep.stage, var.binding.as_ref().unwrap())
+ .ok(),
+ };
if let Some(ref resolved) = resolved {
// Inline samplers are be defined in the EP body
if resolved.as_inline_sampler(options).is_some() {
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -1997,7 +2009,7 @@ impl<W: Write> Writer<W> {
};
} else if let Some(ref binding) = var.binding {
// write an inline sampler
- let resolved = options.resolve_global_binding(ep.stage, binding).unwrap();
+ let resolved = options.resolve_resource_binding(ep.stage, binding).unwrap();
if let Some(sampler) = resolved.as_inline_sampler(options) {
let name = &self.names[&NameKey::GlobalVariable(handle)];
writeln!(
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -48,6 +48,7 @@ use std::{convert::TryInto, num::NonZeroU32, path::PathBuf};
pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[
spirv::Capability::Shader,
+ spirv::Capability::VulkanMemoryModel,
spirv::Capability::ClipDistance,
spirv::Capability::CullDistance,
spirv::Capability::SampleRateShading,
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -67,7 +68,7 @@ pub const SUPPORTED_CAPABILITIES: &[spirv::Capability] = &[
spirv::Capability::UniformBufferArrayDynamicIndexing,
spirv::Capability::StorageBufferArrayDynamicIndexing,
];
-pub const SUPPORTED_EXTENSIONS: &[&str] = &[];
+pub const SUPPORTED_EXTENSIONS: &[&str] = &["SPV_KHR_vulkan_memory_model"];
pub const SUPPORTED_EXT_SETS: &[&str] = &["GLSL.std.450"];
#[derive(Copy, Clone)]
|
diff --git a/tests/in/boids.param.ron b/tests/in/boids.param.ron
--- a/tests/in/boids.param.ron
+++ b/tests/in/boids.param.ron
@@ -12,6 +12,8 @@
(stage: Compute, group: 0, binding: 1): (buffer: Some(1), mutable: true),
(stage: Compute, group: 0, binding: 2): (buffer: Some(2), mutable: true),
},
+ push_constants_map: (
+ ),
inline_samplers: [],
spirv_cross_compatibility: false,
fake_missing_bindings: false,
diff --git a/tests/in/skybox.param.ron b/tests/in/skybox.param.ron
--- a/tests/in/skybox.param.ron
+++ b/tests/in/skybox.param.ron
@@ -12,6 +12,8 @@
(stage: Fragment, group: 0, binding: 1): (texture: Some(0)),
(stage: Fragment, group: 0, binding: 2): (sampler: Some(Inline(1))),
},
+ push_constants_map: (
+ ),
inline_samplers: [
(
coord: Normalized,
diff --git /dev/null b/tests/out/texture-array.msl.snap
new file mode 100644
--- /dev/null
+++ b/tests/out/texture-array.msl.snap
@@ -0,0 +1,34 @@
+---
+source: tests/snapshots.rs
+expression: msl
+---
+#include <metal_stdlib>
+#include <simd/simd.h>
+
+struct PushConstants {
+ metal::uint index;
+};
+
+struct main1Input {
+ metal::float2 tex_coord [[user(loc0)]];
+};
+struct main1Output {
+ metal::float4 member [[color(1)]];
+};
+fragment main1Output main1(
+ main1Input varyings [[stage_in]]
+, metal::texture2d<float, metal::access::sample> texture0_ [[user(fake0)]]
+, metal::texture2d<float, metal::access::sample> texture1_ [[user(fake0)]]
+, metal::sampler sampler [[user(fake0)]]
+, constant PushConstants& pc [[user(fake0)]]
+) {
+ const auto tex_coord = varyings.tex_coord;
+ if (pc.index == 0u) {
+ metal::float4 _e9 = texture0_.sample(sampler, tex_coord);
+ return main1Output { _e9 };
+ } else {
+ metal::float4 _e10 = texture1_.sample(sampler, tex_coord);
+ return main1Output { _e10 };
+ }
+}
+
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -267,7 +267,7 @@ fn convert_wgsl_image_copy() {
#[cfg(feature = "wgsl-in")]
#[test]
fn convert_wgsl_texture_array() {
- convert_wgsl("texture-array", Targets::SPIRV);
+ convert_wgsl("texture-array", Targets::SPIRV | Targets::METAL);
}
#[cfg(feature = "spv-in")]
|
Support the Vulkan Memory Model
Naga doesn't currently support compiling or validating shaders that require the `VulkanMemoryModel` capability. To replace spirv-cross, this is necessary. I believe the `VariablePointer` capability isn't actually necessary and has been removed from upstream rust-gpu.
I've attached the spirv of such a shader and the rust code and spirv disassembly are in the dropdown.
[blitfragment.spv.zip](https://github.com/gfx-rs/naga/files/6301151/blitfragment.spv.zip)
<details>
<summary>Rust code and SPIRV disassembly</summary>
```rust
#[spirv(fragment)]
pub fn fragment(
#[spirv(frag_coord)] frag_coord: Vec4,
#[spirv(push_constant)] resolution: &UVec2,
#[spirv(descriptor_set = 0, binding = 0)] input_texture: &Image2d,
#[spirv(descriptor_set = 0, binding = 1)] sampler: &Sampler,
output: &mut Vec4,
) {
*output = input_texture.sample(*sampler, frag_coord.xy() / resolution.as_f32());
}
```
```
; SPIR-V
; Version: 1.0
; Generator: Google rspirv; 0
; Bound: 72
; Schema: 0
OpCapability Shader
OpCapability VulkanMemoryModel
OpCapability VariablePointers
OpExtension "SPV_KHR_vulkan_memory_model"
OpExtension "SPV_KHR_variable_pointers"
OpMemoryModel Logical Vulkan
OpEntryPoint Fragment %1 "blit::fragment" %gl_FragCoord %3
OpExecutionMode %1 OriginUpperLeft
OpDecorate %gl_FragCoord BuiltIn FragCoord
OpDecorate %_struct_8 Block
OpMemberDecorate %_struct_8 0 Offset 0
OpDecorate %6 DescriptorSet 0
OpDecorate %6 Binding 0
OpDecorate %7 DescriptorSet 0
OpDecorate %7 Binding 1
OpDecorate %3 Location 0
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%11 = OpTypeImage %float 2D 0 0 0 1 Unknown
%_ptr_UniformConstant_11 = OpTypePointer UniformConstant %11
%13 = OpTypeSampler
%v2float = OpTypeVector %float 2
%15 = OpTypeFunction %v4float %_ptr_UniformConstant_11 %13 %v2float
%_ptr_UniformConstant_13 = OpTypePointer UniformConstant %13
%_ptr_Input_v4float = OpTypePointer Input %v4float
%_ptr_Output_v4float = OpTypePointer Output %v4float
%_ptr_Function_v4float = OpTypePointer Function %v4float
%20 = OpTypeSampledImage %11
%uint = OpTypeInt 32 0
%v2uint = OpTypeVector %uint 2
%_ptr_PushConstant_v2uint = OpTypePointer PushConstant %v2uint
%void = OpTypeVoid
%25 = OpTypeFunction %void
%gl_FragCoord = OpVariable %_ptr_Input_v4float Input
%_struct_8 = OpTypeStruct %v2uint
%_ptr_PushConstant__struct_8 = OpTypePointer PushConstant %_struct_8
%uint_0 = OpConstant %uint 0
%5 = OpVariable %_ptr_PushConstant__struct_8 PushConstant
%6 = OpVariable %_ptr_UniformConstant_11 UniformConstant
%7 = OpVariable %_ptr_UniformConstant_13 UniformConstant
%3 = OpVariable %_ptr_Output_v4float Output
%_ptr_PushConstant_uint = OpTypePointer PushConstant %uint
%uint_1 = OpConstant %uint 1
%_ptr_Function_float = OpTypePointer Function %float
%31 = OpUndef %v2float
%1 = OpFunction %void None %25
%39 = OpLabel
%67 = OpVariable %_ptr_Function_v4float Function
%40 = OpVariable %_ptr_Function_v4float Function
%41 = OpLoad %v4float %gl_FragCoord
%42 = OpAccessChain %_ptr_PushConstant_v2uint %5 %uint_0
%43 = OpLoad %13 %7
OpStore %40 %41
%44 = OpAccessChain %_ptr_Function_float %40 %uint_0
%45 = OpLoad %float %44
%46 = OpAccessChain %_ptr_Function_float %40 %uint_1
%47 = OpLoad %float %46
%50 = OpAccessChain %_ptr_PushConstant_uint %5 %uint_0 %uint_0
%51 = OpLoad %uint %50
%52 = OpConvertUToF %float %51
%53 = OpAccessChain %_ptr_PushConstant_uint %5 %uint_0 %uint_1
%54 = OpLoad %uint %53
%55 = OpConvertUToF %float %54
%60 = OpFDiv %float %45 %52
%63 = OpFDiv %float %47 %55
%64 = OpCompositeInsert %v2float %60 %31 0
%65 = OpCompositeInsert %v2float %63 %64 1
%69 = OpLoad %11 %6
%70 = OpSampledImage %20 %69 %43
%71 = OpImageSampleImplicitLod %v4float %70 %65
OpStore %67 %71
OpStore %3 %71
OpReturn
OpFunctionEnd
```
</details>
|
Filed https://github.com/EmbarkStudios/rust-gpu/issues/593 to rust-gpu, continuing with a modified shader that doesn't require at least the "VariablePointers" stuff.
|
2021-04-13T13:24:16Z
|
0.3
|
2021-04-13T05:32:02Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"convert_wgsl_texture_array"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"back::msl::test_error_size",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout::test_physical_layout_in_words",
"arena::tests::fetch_or_append_unique",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::lex::tests::lex_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::wgsl::tests::parse_comment",
"back::msl::writer::test_stack_size",
"front::wgsl::tests::parse_pointers",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_store",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_types",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_type_cast",
"front::wgsl::tests::parse_texture_load",
"front::glsl::parser_tests::control_flow",
"invalid_integer",
"function_without_identifier",
"invalid_float",
"invalid_scalar_width",
"invalid_accessor",
"parse_glsl",
"convert_glsl_quad",
"convert_wgsl_image_copy",
"convert_spv_quad_vert",
"convert_wgsl_shadow",
"convert_wgsl_skybox",
"convert_wgsl_empty",
"convert_wgsl_boids",
"convert_wgsl_quad",
"convert_wgsl_collatz",
"convert_spv_shadow"
] |
[] |
[] |
gfx-rs/naga
| 647
|
gfx-rs__naga-647
|
[
"642"
] |
af4d989f556fc810afcf4af1dfd5080ddcb3dbb5
|
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -212,6 +212,23 @@ impl<W: Write> Writer<W> {
Ok(())
}
+ fn put_storage_image_coordinate(
+ &mut self,
+ expr: Handle<crate::Expression>,
+ context: &ExpressionContext,
+ ) -> Result<(), Error> {
+ // coordinates in IR are int, but Metal expects uint
+ let size_str = match *context.info[expr].ty.inner_with(&context.module.types) {
+ crate::TypeInner::Scalar { .. } => "",
+ crate::TypeInner::Vector { size, .. } => vector_size_string(size),
+ _ => return Err(Error::Validation),
+ };
+ write!(self.out, "{}::uint{}(", NAMESPACE, size_str)?;
+ self.put_expression(expr, context, true)?;
+ write!(self.out, ")")?;
+ Ok(())
+ }
+
fn put_initialization_component(
&mut self,
component: Handle<crate::Expression>,
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -441,7 +458,7 @@ impl<W: Write> Writer<W> {
} => {
self.put_expression(image, context, false)?;
write!(self.out, ".read(")?;
- self.put_expression(coordinate, context, true)?;
+ self.put_storage_image_coordinate(coordinate, context)?;
if let Some(expr) = array_index {
write!(self.out, ", ")?;
self.put_expression(expr, context, true)?;
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -953,7 +970,7 @@ impl<W: Write> Writer<W> {
write!(self.out, ".write(")?;
self.put_expression(value, &context.expression, true)?;
write!(self.out, ", ")?;
- self.put_expression(coordinate, &context.expression, true)?;
+ self.put_storage_image_coordinate(coordinate, &context.expression)?;
if let Some(expr) = array_index {
write!(self.out, ", ")?;
self.put_expression(expr, &context.expression, true)?;
|
diff --git /dev/null b/tests/in/image-copy.param.ron
new file mode 100644
--- /dev/null
+++ b/tests/in/image-copy.param.ron
@@ -0,0 +1,8 @@
+(
+ spv_version: (1, 1),
+ spv_capabilities: [ Shader, Image1D, Sampled1D ],
+ mtl_bindings: {
+ (stage: Compute, group: 0, binding: 1): (texture: Some(0), mutable: false),
+ (stage: Compute, group: 0, binding: 2): (texture: Some(1), mutable: true),
+ }
+)
diff --git /dev/null b/tests/in/image-copy.wgsl
new file mode 100644
--- /dev/null
+++ b/tests/in/image-copy.wgsl
@@ -0,0 +1,16 @@
+[[group(0), binding(1)]]
+var image_src: [[access(read)]] texture_storage_2d<rgba8uint>;
+[[group(0), binding(2)]]
+var image_dst: [[access(write)]] texture_storage_1d<r32uint>;
+
+[[stage(compute), workgroup_size(16)]]
+fn main(
+ [[builtin(local_invocation_id)]] local_id: vec3<u32>,
+ //TODO: https://github.com/gpuweb/gpuweb/issues/1590
+ //[[builtin(workgroup_size)]] wg_size: vec3<u32>
+) {
+ const dim = textureDimensions(image_src);
+ const itc = dim * vec2<i32>(local_id.xy) % vec2<i32>(10, 20);
+ const value = textureLoad(image_src, itc);
+ textureStore(image_dst, itc.x, value);
+}
diff --git /dev/null b/tests/out/image-copy.msl.snap
new file mode 100644
--- /dev/null
+++ b/tests/out/image-copy.msl.snap
@@ -0,0 +1,27 @@
+---
+source: tests/snapshots.rs
+expression: msl
+---
+#include <metal_stdlib>
+#include <simd/simd.h>
+
+constexpr constant int const_10i = 10;
+constexpr constant int const_20i = 20;
+typedef metal::texture2d<uint, metal::access::read> type;
+typedef metal::texture1d<uint, metal::access::write> type1;
+typedef metal::uint3 type2;
+typedef metal::uint2 type3;
+typedef metal::int2 type4;
+struct main1Input {
+};
+kernel void main1(
+ type2 local_id [[thread_position_in_threadgroup]]
+, type image_src [[texture(0)]]
+, type1 image_dst [[texture(1)]]
+) {
+ metal::int2 _expr12 = (int2(image_src.get_width(), image_src.get_height()) * static_cast<int2>(metal::uint2(local_id.x, local_id.y))) % metal::int2(const_10i, const_20i);
+ metal::uint4 _expr13 = image_src.read(metal::uint2(_expr12));
+ image_dst.write(_expr13, metal::uint(_expr12.x));
+ return;
+}
+
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -264,6 +264,13 @@ fn convert_wgsl_shadow() {
convert_wgsl("shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL);
}
+#[cfg(feature = "wgsl-in")]
+#[test]
+fn convert_wgsl_image_copy() {
+ //SPIR-V is blocked by https://github.com/gfx-rs/naga/issues/646
+ convert_wgsl("image-copy", Targets::METAL);
+}
+
#[cfg(feature = "wgsl-in")]
#[test]
fn convert_wgsl_texture_array() {
|
MSL storage reads need to have unsigned coordiantes
```
program_source:218:38: error: no matching member function for call to 'read'
metal::float4 _expr274 = global3.read(metal::int2(_expr269.x, _expr269.y), _expr269.z);
~~~~~~~~^~~~
/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/31001/Libraries/lib/clang/31001.184/include/metal/metal_texture:2766:24: note: candidate function not viable: no known conversion from 'metal::int2' (aka 'int2') to 'metal::ushort2' (aka 'ushort2') for 1st argument
METAL_FUNC vec<T, 4> read(ushort2 coord, ushort lod = 0) const thread
^
/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/31001/Libraries/lib/clang/31001.184/include/metal/metal_texture:2781:24: note: candidate function not viable: no known conversion from 'metal::int2' (aka 'int2') to 'metal::uint2' (aka 'uint2') for 1st argument
METAL_FUNC vec<T, 4> read(uint2 coord, uint lod = 0) const thread
```
|
2021-04-01T22:36:34Z
|
0.3
|
2021-04-01T14:47:32Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"convert_wgsl_image_copy"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::fetch_or_append_unique",
"back::msl::test_error_size",
"front::glsl::constants::tests::access",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::cast",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::lexer::test_tokens",
"front::spv::test::parse",
"front::wgsl::tests::parse_comment",
"back::msl::writer::test_stack_size",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_pointers",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_postfix",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_expressions",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_switch",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_texture_store",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::control_flow",
"invalid_scalar_width",
"invalid_integer",
"function_without_identifier",
"invalid_float",
"invalid_accessor",
"parse_glsl",
"convert_glsl_quad",
"convert_wgsl_texture_array",
"convert_spv_quad_vert",
"convert_wgsl_empty",
"convert_wgsl_boids",
"convert_wgsl_shadow",
"convert_wgsl_skybox",
"convert_wgsl_quad",
"convert_wgsl_collatz",
"convert_spv_shadow"
] |
[] |
[] |
|
gfx-rs/naga
| 619
|
gfx-rs__naga-619
|
[
"614"
] |
e47ff2dc26a049bc2830f468f0acf6d0214ff8a2
|
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -205,6 +205,39 @@ impl<W: Write> Writer<W> {
Ok(())
}
+ fn put_initialization_component(
+ &mut self,
+ component: Handle<crate::Expression>,
+ context: &ExpressionContext,
+ ) -> Result<(), Error> {
+ // we can't initialize the array members just like other members,
+ // we have to unwrap them one level deeper...
+ let component_res = &context.info[component].ty;
+ if let crate::TypeInner::Array {
+ size: crate::ArraySize::Constant(const_handle),
+ ..
+ } = *component_res.inner_with(&context.module.types)
+ {
+ //HACK: we are forcefully duplicating the expression here,
+ // it would be nice to find a more C++ idiomatic solution for initializing array members
+ let size = context.module.constants[const_handle]
+ .to_array_length()
+ .unwrap();
+ write!(self.out, "{{")?;
+ for j in 0..size {
+ if j != 0 {
+ write!(self.out, ",")?;
+ }
+ self.put_expression(component, context, false)?;
+ write!(self.out, "[{}]", j)?;
+ }
+ write!(self.out, "}}")?;
+ } else {
+ self.put_expression(component, context, true)?;
+ }
+ Ok(())
+ }
+
fn put_expression(
&mut self,
expr_handle: Handle<crate::Expression>,
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -301,7 +334,7 @@ impl<W: Write> Writer<W> {
if i != 0 {
write!(self.out, ", ")?;
}
- self.put_expression(component, context, true)?;
+ self.put_initialization_component(component, context)?;
}
write!(self.out, "}}")?;
}
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -370,17 +403,17 @@ impl<W: Write> Writer<W> {
//TODO: do we support Zero on `Sampled` image classes?
}
crate::SampleLevel::Exact(h) => {
- write!(self.out, ", level(")?;
+ write!(self.out, ", {}::level(", NAMESPACE)?;
self.put_expression(h, context, true)?;
write!(self.out, ")")?;
}
crate::SampleLevel::Bias(h) => {
- write!(self.out, ", bias(")?;
+ write!(self.out, ", {}::bias(", NAMESPACE)?;
self.put_expression(h, context, true)?;
write!(self.out, ")")?;
}
crate::SampleLevel::Gradient { x, y } => {
- write!(self.out, ", gradient(")?;
+ write!(self.out, ", {}::gradient(", NAMESPACE)?;
self.put_expression(x, context, true)?;
write!(self.out, ", ")?;
self.put_expression(y, context, true)?;
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -819,11 +852,31 @@ impl<W: Write> Writer<W> {
self.put_expression(expr_handle, &context.expression, true)?;
writeln!(self.out, ";")?;
write!(self.out, "{}return {} {{", level, struct_name)?;
- for index in 0..members.len() as u32 {
+ for (index, member) in members.iter().enumerate() {
let comma = if index == 0 { "" } else { "," };
- let name =
- &self.names[&NameKey::StructMember(result_ty, index)];
- write!(self.out, "{} {}.{}", comma, tmp, name)?;
+ let name = &self.names
+ [&NameKey::StructMember(result_ty, index as u32)];
+ // logic similar to `put_initialization_component`
+ if let crate::TypeInner::Array {
+ size: crate::ArraySize::Constant(const_handle),
+ ..
+ } = context.expression.module.types[member.ty].inner
+ {
+ let size = context.expression.module.constants
+ [const_handle]
+ .to_array_length()
+ .unwrap();
+ write!(self.out, "{} {{", comma)?;
+ for j in 0..size {
+ if j != 0 {
+ write!(self.out, ",")?;
+ }
+ write!(self.out, "{}.{}[{}]", tmp, name, j)?;
+ }
+ write!(self.out, "}}")?;
+ } else {
+ write!(self.out, "{} {}.{}", comma, tmp, name)?;
+ }
}
}
_ => {
|
diff --git a/src/back/msl/writer.rs b/src/back/msl/writer.rs
--- a/src/back/msl/writer.rs
+++ b/src/back/msl/writer.rs
@@ -1558,8 +1611,8 @@ fn test_stack_size() {
}
let stack_size = max_addr - min_addr;
// check the size (in debug only)
- // last observed macOS value: 21920
- if stack_size > 22000 {
+ // last observed macOS value: 22112
+ if stack_size > 22200 {
panic!("`put_expression` stack size {} is too large!", stack_size);
}
}
diff --git /dev/null b/tests/out/quad-vert.msl.snap
new file mode 100644
--- /dev/null
+++ b/tests/out/quad-vert.msl.snap
@@ -0,0 +1,75 @@
+---
+source: tests/snapshots.rs
+expression: msl
+---
+#include <metal_stdlib>
+#include <simd/simd.h>
+
+constexpr constant unsigned const_0u = 0u;
+constexpr constant unsigned const_1u = 1u;
+constexpr constant unsigned const_2u = 2u;
+constexpr constant unsigned const_3u = 3u;
+constexpr constant unsigned const_1u1 = 1u;
+constexpr constant int const_0i = 0;
+constexpr constant float const_0f = 0.0;
+constexpr constant float const_1f = 1.0;
+typedef float type;
+typedef metal::float2 type1;
+typedef thread type1 *type2;
+typedef thread type1 *type3;
+typedef metal::float4 type4;
+typedef uint type5;
+typedef type type6[const_1u1];
+struct gl_PerVertex {
+ type4 gl_Position;
+ type gl_PointSize;
+ type6 gl_ClipDistance;
+ type6 gl_CullDistance;
+};
+typedef thread gl_PerVertex *type7;
+typedef int type8;
+typedef thread type4 *type9;
+struct type10 {
+ type1 member;
+ type4 gl_Position1;
+ type gl_PointSize1;
+ type6 gl_ClipDistance1;
+};
+void main1(
+ type1 v_uv,
+ type1 a_uv,
+ gl_PerVertex _,
+ type1 a_pos
+) {
+ v_uv = a_uv;
+ type1 _expr9 = a_pos;
+ _.gl_Position = metal::float4(_expr9.x, _expr9.y, const_0f, const_1f);
+ return;
+}
+
+struct main2Input {
+ type1 a_uv1 [[attribute(1)]];
+ type1 a_pos1 [[attribute(0)]];
+};
+struct main2Output {
+ type1 member [[user(loc0)]];
+ type4 gl_Position1 [[position]];
+ type gl_PointSize1 [[point_size]];
+ type6 gl_ClipDistance1 [[clip_distance]];
+};
+vertex main2Output main2(
+ main2Input varyings [[stage_in]]
+) {
+ type1 v_uv = {};
+ type1 a_uv = {};
+ gl_PerVertex _ = {};
+ type1 a_pos = {};
+ const auto a_uv1 = varyings.a_uv1;
+ const auto a_pos1 = varyings.a_pos1;
+ a_uv = a_uv1;
+ a_pos = a_pos1;
+ main1(v_uv, a_uv, _, a_pos);
+ const auto _tmp = type10 {v_uv, _.gl_Position, _.gl_PointSize, {_.gl_ClipDistance[0]}};
+ return main2Output { _tmp.member, _tmp.gl_Position1, _tmp.gl_PointSize1, {_tmp.gl_ClipDistance1[0]} };
+}
+
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -286,7 +286,7 @@ fn convert_spv(name: &str, targets: Targets) {
#[cfg(feature = "spv-in")]
#[test]
fn convert_spv_quad_vert() {
- convert_spv("quad-vert", Targets::empty());
+ convert_spv("quad-vert", Targets::METAL);
}
#[cfg(feature = "spv-in")]
|
MSL struct initialization fails on array types
> program_source:1114:90: error: cannot initialize an array element of type 'type1' (aka 'float') with an lvalue of type 'type29' (aka 'type1 [1]')
Code:
```rust
typedef type1 type29[const_1u1];
typedef thread type29 *type30;
typedef thread type1 *type31;
typedef metal::bool3 type32;
struct type33 {
type2 member14;
type2 member15;
type2 member16;
type3 member17;
type2 member18;
type2 member19;
type29 member20;
};
...
type29 global15 = {};
const auto _tmp = type33 {global9, global10, global11, global12, global13, global14, global15};
```
|
2021-03-27T11:55:36Z
|
0.3
|
2021-03-27T14:58:04Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"convert_spv_quad_vert"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::msl::test_error_size",
"arena::tests::fetch_or_append_unique",
"back::spv::writer::test_write_physical_layout",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::unary_op",
"front::glsl::lex::tests::lex_tokens",
"back::msl::writer::test_stack_size",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_standard_fun",
"front::wgsl::tests::parse_if",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_struct",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_statement",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_postfix",
"proc::typifier::test_error_size",
"valid::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_switch",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::control_flow",
"function_without_identifier",
"invalid_integer",
"invalid_float",
"invalid_scalar_width",
"invalid_accessor",
"parse_glsl",
"convert_glsl_quad",
"convert_wgsl_texture_array",
"convert_wgsl_empty",
"convert_wgsl_boids",
"convert_wgsl_skybox",
"convert_wgsl_shadow",
"convert_wgsl_quad",
"convert_wgsl_collatz",
"convert_spv_shadow"
] |
[] |
[] |
|
gfx-rs/naga
| 581
|
gfx-rs__naga-581
|
[
"567"
] |
889e487b629bc6499999f8d6485af9020b16f0e4
|
diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs
--- a/src/back/spv/writer.rs
+++ b/src/back/spv/writer.rs
@@ -858,18 +858,14 @@ impl Writer {
let mut current_offset = 0;
let mut member_ids = Vec::with_capacity(members.len());
for (index, member) in members.iter().enumerate() {
- let layout = self.layouter.resolve(member.ty);
- current_offset += layout.pad(current_offset);
+ let (placement, _) = self.layouter.member_placement(current_offset, member);
self.annotations.push(Instruction::member_decorate(
id,
index as u32,
spirv::Decoration::Offset,
- &[current_offset],
+ &[placement.start],
));
- current_offset += match member.span {
- Some(span) => span.get(),
- None => layout.size,
- };
+ current_offset = placement.end;
if self.flags.contains(WriterFlags::DEBUG) {
if let Some(ref name) = member.name {
diff --git a/src/front/glsl/parser.rs b/src/front/glsl/parser.rs
--- a/src/front/glsl/parser.rs
+++ b/src/front/glsl/parser.rs
@@ -725,9 +725,12 @@ pomelo! {
if let Some(ty) = t {
sdl.iter().map(|name| StructMember {
name: Some(name.clone()),
- span: None,
ty,
binding: None, //TODO
+ //TODO: if the struct is a uniform struct, these values have to reflect
+ // std140 layout. Otherwise, std430.
+ size: None,
+ align: None,
}).collect()
} else {
return Err(ErrorKind::SemanticError("Struct member can't be void".into()))
diff --git a/src/front/spv/function.rs b/src/front/spv/function.rs
--- a/src/front/spv/function.rs
+++ b/src/front/spv/function.rs
@@ -237,9 +237,10 @@ impl<I: Iterator<Item = u32>> super::Parser<I> {
if let super::Variable::Output(ref result) = lvar.inner {
members.push(crate::StructMember {
name: None,
- span: None,
ty: result.ty,
binding: result.binding.clone(),
+ size: None,
+ align: None,
});
// populate just the globals first, then do `Load` in a
// separate step, so that we can get a range.
diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs
--- a/src/front/spv/mod.rs
+++ b/src/front/spv/mod.rs
@@ -2369,9 +2369,10 @@ impl<I: Iterator<Item = u32>> Parser<I> {
host_shared |= decor.offset.is_some();
members.push(crate::StructMember {
name: decor.name,
- span: None, //TODO
ty,
binding: None,
+ size: None, //TODO
+ align: None,
});
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -107,6 +107,8 @@ pub enum Error<'a> {
UnknownConservativeDepth(&'a str),
#[error("array stride must not be 0")]
ZeroStride,
+ #[error("struct member size or array must not be 0")]
+ ZeroSizeOrAlign,
#[error("not a composite type: {0:?}")]
NotCompositeType(Handle<crate::Type>),
#[error("Input/output binding is not consistent: location {0:?}, built-in {1:?} and interpolation {2:?}")]
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1502,7 +1504,7 @@ impl Parser {
let mut members = Vec::new();
lexer.expect(Token::Paren('{'))?;
loop {
- let mut span = 0;
+ let (mut size, mut align) = (None, None);
let mut bind_parser = BindingParser::default();
if lexer.skip(Token::DoubleParen('[')) {
self.scopes.push(Scope::Decoration);
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1517,17 +1519,19 @@ impl Parser {
}
(Token::Word(word), _) if ready => {
match word {
- "span" => {
+ "size" => {
lexer.expect(Token::Paren('('))?;
- //Note: 0 is not handled
- span = lexer.next_uint_literal()?;
+ let value = lexer.next_uint_literal()?;
lexer.expect(Token::Paren(')'))?;
+ size =
+ Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign)?);
}
- "offset" => {
- // skip - only here for parsing compatibility
+ "align" => {
lexer.expect(Token::Paren('('))?;
- let _offset = lexer.next_uint_literal()?;
+ let value = lexer.next_uint_literal()?;
lexer.expect(Token::Paren(')'))?;
+ align =
+ Some(NonZeroU32::new(value).ok_or(Error::ZeroSizeOrAlign)?);
}
_ => bind_parser.parse(lexer, word)?,
}
diff --git a/src/front/wgsl/mod.rs b/src/front/wgsl/mod.rs
--- a/src/front/wgsl/mod.rs
+++ b/src/front/wgsl/mod.rs
@@ -1550,9 +1554,10 @@ impl Parser {
members.push(crate::StructMember {
name: Some(name.to_owned()),
- span: NonZeroU32::new(span),
ty,
binding: bind_parser.finish()?,
+ size,
+ align,
});
}
}
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -238,10 +238,14 @@ pub enum Interpolation {
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
pub struct StructMember {
pub name: Option<String>,
- pub span: Option<NonZeroU32>,
+ /// Type of the field.
pub ty: Handle<Type>,
/// For I/O structs, defines the binding.
pub binding: Option<Binding>,
+ /// Overrides the size computed off the type.
+ pub size: Option<NonZeroU32>,
+ /// Overrides the alignment computed off the type.
+ pub align: Option<NonZeroU32>,
}
/// The number of dimensions an image has.
diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs
--- a/src/proc/layouter.rs
+++ b/src/proc/layouter.rs
@@ -1,5 +1,5 @@
use crate::arena::Arena;
-use std::num::NonZeroU32;
+use std::{num::NonZeroU32, ops};
pub type Alignment = NonZeroU32;
diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs
--- a/src/proc/layouter.rs
+++ b/src/proc/layouter.rs
@@ -10,17 +10,9 @@ pub struct TypeLayout {
pub alignment: Alignment,
}
-impl TypeLayout {
- /// Return padding to this type given an offset.
- pub fn pad(&self, offset: u32) -> u32 {
- match offset & self.alignment.get() {
- 0 => 0,
- other => self.alignment.get() - other,
- }
- }
-}
-
/// Helper processor that derives the sizes of all types.
+/// It uses the default layout algorithm/table, described in
+/// https://github.com/gpuweb/gpuweb/issues/1393
#[derive(Debug, Default)]
pub struct Layouter {
layouts: Vec<TypeLayout>,
diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs
--- a/src/proc/layouter.rs
+++ b/src/proc/layouter.rs
@@ -33,6 +25,29 @@ impl Layouter {
this
}
+ pub fn round_up(alignment: NonZeroU32, offset: u32) -> u32 {
+ match offset & alignment.get() {
+ 0 => offset,
+ other => offset + alignment.get() - other,
+ }
+ }
+
+ pub fn member_placement(
+ &self,
+ offset: u32,
+ member: &crate::StructMember,
+ ) -> (ops::Range<u32>, NonZeroU32) {
+ let layout = self.layouts[member.ty.index()];
+ let alignment = member.align.unwrap_or(layout.alignment);
+ let start = Self::round_up(alignment, offset);
+ let end = start
+ + match member.size {
+ Some(size) => size.get(),
+ None => layout.size,
+ };
+ (start..end, alignment)
+ }
+
pub fn initialize(&mut self, types: &Arena<crate::Type>, constants: &Arena<crate::Constant>) {
use crate::TypeInner as Ti;
diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs
--- a/src/proc/layouter.rs
+++ b/src/proc/layouter.rs
@@ -51,8 +66,10 @@ impl Layouter {
width,
} => TypeLayout {
size: (size as u8 * width) as u32,
- //TODO: reconsider if this needs to match the size
- alignment: Alignment::new(width as u32).unwrap(),
+ alignment: {
+ let count = if size >= crate::VectorSize::Tri { 4 } else { 2 };
+ Alignment::new((count * width) as u32).unwrap()
+ },
},
Ti::Matrix {
columns,
diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs
--- a/src/proc/layouter.rs
+++ b/src/proc/layouter.rs
@@ -60,7 +77,10 @@ impl Layouter {
width,
} => TypeLayout {
size: (columns as u8 * rows as u8 * width) as u32,
- alignment: Alignment::new((columns as u8 * width) as u32).unwrap(),
+ alignment: {
+ let count = if rows >= crate::VectorSize::Tri { 4 } else { 2 };
+ Alignment::new((count * width) as u32).unwrap()
+ },
},
Ti::Pointer { .. } | Ti::ValuePointer { .. } => TypeLayout {
size: 4,
diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs
--- a/src/proc/layouter.rs
+++ b/src/proc/layouter.rs
@@ -83,11 +103,15 @@ impl Layouter {
} => value as u32,
ref other => unreachable!("Unexpected array size {:?}", other),
},
- crate::ArraySize::Dynamic => 1,
+ crate::ArraySize::Dynamic => 0,
};
let stride = match stride {
Some(value) => value,
- None => Alignment::new(self.layouts[base.index()].size.max(1)).unwrap(),
+ None => {
+ let layout = &self.layouts[base.index()];
+ let stride = Self::round_up(layout.alignment, layout.size);
+ Alignment::new(stride).unwrap()
+ }
};
TypeLayout {
size: count * stride.get(),
diff --git a/src/proc/layouter.rs b/src/proc/layouter.rs
--- a/src/proc/layouter.rs
+++ b/src/proc/layouter.rs
@@ -101,18 +125,12 @@ impl Layouter {
let mut total = 0;
let mut biggest_alignment = Alignment::new(1).unwrap();
for member in members {
- let member_layout = self.layouts[member.ty.index()];
- biggest_alignment = biggest_alignment.max(member_layout.alignment);
- // align up first
- total += member_layout.pad(total);
- // then add the size
- total += match member.span {
- Some(span) => span.get(),
- None => member_layout.size,
- };
+ let (placement, alignment) = self.member_placement(total, member);
+ biggest_alignment = biggest_alignment.max(alignment);
+ total = placement.end;
}
TypeLayout {
- size: total,
+ size: Self::round_up(biggest_alignment, total),
alignment: biggest_alignment,
}
}
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -555,7 +555,11 @@ impl Validator {
}
TypeFlags::SIZED //TODO: `DATA`?
}
- Ti::Array { base, size, stride } => {
+ Ti::Array {
+ base,
+ size,
+ stride: _,
+ } => {
if base >= handle {
return Err(TypeError::UnresolvedBase(base));
}
diff --git a/src/proc/validator.rs b/src/proc/validator.rs
--- a/src/proc/validator.rs
+++ b/src/proc/validator.rs
@@ -596,11 +600,7 @@ impl Validator {
}
crate::ArraySize::Dynamic => TypeFlags::empty(),
};
- let base_mask = if stride.is_none() {
- TypeFlags::INTERFACE
- } else {
- TypeFlags::HOST_SHARED | TypeFlags::INTERFACE
- };
+ let base_mask = TypeFlags::HOST_SHARED | TypeFlags::INTERFACE;
TypeFlags::DATA | (base_flags & base_mask) | sized_flag
}
Ti::Struct { block, ref members } => {
|
diff --git a/src/front/wgsl/tests.rs b/src/front/wgsl/tests.rs
--- a/src/front/wgsl/tests.rs
+++ b/src/front/wgsl/tests.rs
@@ -70,7 +70,11 @@ fn parse_struct() {
parse_str(
"
[[block]] struct Foo { x: i32; };
- struct Bar { [[span(16)]] x: vec2<i32>; };
+ struct Bar {
+ [[size(16)]] x: vec2<i32>;
+ [[align(16)]] y: f32;
+ [[size(32), align(8)]] z: vec3<f32>;
+ };
struct Empty {};
var s: [[access(read_write)]] Foo;
",
diff --git a/tests/out/collatz.ron.snap b/tests/out/collatz.ron.snap
--- a/tests/out/collatz.ron.snap
+++ b/tests/out/collatz.ron.snap
@@ -26,9 +26,10 @@ expression: output
members: [
(
name: Some("data"),
- span: None,
ty: 2,
binding: None,
+ size: None,
+ align: None,
),
],
),
diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap
--- a/tests/out/shadow.ron.snap
+++ b/tests/out/shadow.ron.snap
@@ -110,9 +110,10 @@ expression: output
members: [
(
name: Some("num_lights"),
- span: None,
ty: 13,
binding: None,
+ size: None,
+ align: None,
),
],
),
diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap
--- a/tests/out/shadow.ron.snap
+++ b/tests/out/shadow.ron.snap
@@ -153,21 +154,24 @@ expression: output
members: [
(
name: Some("proj"),
- span: None,
ty: 18,
binding: None,
+ size: None,
+ align: None,
),
(
name: Some("pos"),
- span: None,
ty: 4,
binding: None,
+ size: None,
+ align: None,
),
(
name: Some("color"),
- span: None,
ty: 4,
binding: None,
+ size: None,
+ align: None,
),
],
),
diff --git a/tests/out/shadow.ron.snap b/tests/out/shadow.ron.snap
--- a/tests/out/shadow.ron.snap
+++ b/tests/out/shadow.ron.snap
@@ -187,9 +191,10 @@ expression: output
members: [
(
name: Some("data"),
- span: None,
ty: 20,
binding: None,
+ size: None,
+ align: None,
),
],
),
|
Support fixed-size arrays in uniform structures
See [shader](https://pastebin.com/vwzvAvwB) from https://github.com/gfx-rs/wgpu-rs/issues/788:
> Caused by:
In Device::create_shader_module
note: label = `Default Vertex Shader`
Global variable Handle(7) 'fragment_directional_lights_color' is invalid: InvalidType
|
2021-03-16T10:10:12Z
|
0.3
|
2021-03-16T02:27:39Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"front::wgsl::tests::parse_struct",
"convert_wgsl_collatz",
"convert_spv_shadow"
] |
[
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"arena::tests::fetch_or_append_unique",
"arena::tests::fetch_or_append_non_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::writer::test_writer_generate_id",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::cast",
"front::glsl::constants::tests::access",
"front::glsl::constants::tests::unary_op",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::lex::tests::lex_tokens",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_statement",
"front::wgsl::tests::parse_standard_fun",
"front::glsl::parser_tests::constants",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_switch",
"proc::analyzer::uniform_control_flow",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_loop",
"front::glsl::parser_tests::textures",
"front::wgsl::tests::parse_type_inference",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::control_flow",
"function_without_identifier",
"invalid_integer",
"invalid_float",
"invalid_scalar_width",
"invalid_accessor",
"parse_glsl",
"convert_glsl_quad",
"convert_wgsl_texture_array",
"convert_wgsl_empty",
"convert_wgsl_shadow",
"convert_wgsl_quad",
"convert_wgsl_boids",
"convert_wgsl_skybox"
] |
[] |
[] |
|
gfx-rs/naga
| 561
|
gfx-rs__naga-561
|
[
"560"
] |
f5ee79191223e4ebe323a728f4de40830b8d10f6
|
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -416,7 +416,16 @@ impl<'a, W: Write> Writer<'a, W> {
ref members,
} = ty.inner
{
- self.write_struct(handle, members)?
+ // No needed to write a struct that also should be written as a global variable
+ let is_global_struct = self
+ .module
+ .global_variables
+ .iter()
+ .any(|e| e.1.ty == handle);
+
+ if !is_global_struct {
+ self.write_struct(false, handle, members)?
+ }
}
}
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -571,11 +580,10 @@ impl<'a, W: Write> Writer<'a, W> {
)?,
// glsl has no pointer types so just write types as normal and loads are skipped
TypeInner::Pointer { base, .. } => self.write_type(base)?,
- // Arrays are written as `base[size]`
- TypeInner::Array { base, size, .. } => {
- let ty_name = &self.names[&NameKey::Type(base)];
-
- write!(self.out, "{}", ty_name)?;
+ // GLSL arrays are written as `type name[size]`
+ // Current code is written arrays only as `[size]`
+ // Base `type` and `name` should be written outside
+ TypeInner::Array { base: _, size, .. } => {
write!(self.out, "[")?;
// Write the array size
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -596,41 +604,15 @@ impl<'a, W: Write> Writer<'a, W> {
write!(self.out, "]")?
}
+ TypeInner::Struct {
+ block: true,
+ ref members,
+ } => self.write_struct(true, ty, members)?,
// glsl structs are written as just the struct name if it isn't a block
- //
- // If it's a block we need to write `block_name { members }` where `block_name` must be
- // unique between blocks and structs so we add `_block_ID` where `ID` is a `IdGenerator`
- // generated number so it's unique and `members` are the same as in a struct
- TypeInner::Struct { block, ref members } => {
+ TypeInner::Struct { block: false, .. } => {
// Get the struct name
let name = &self.names[&NameKey::Type(ty)];
-
- if block {
- // Write the block name, it's just the struct name appended with `_block_ID`
- writeln!(self.out, "{}_block_{} {{", name, self.block_id.generate())?;
-
- // Write the block members
- for (idx, member) in members.iter().enumerate() {
- // Add a tab for indentation (readability only)
- write!(self.out, "{}", INDENT)?;
- // Write the member type
- self.write_type(member.ty)?;
-
- // Finish the member with the name, a semicolon and a newline
- // The leading space is important
- writeln!(
- self.out,
- " {};",
- &self.names[&NameKey::StructMember(ty, idx as u32)]
- )?;
- }
-
- // Close braces
- write!(self.out, "}}")?
- } else {
- // Write the struct name
- write!(self.out, "{}", name)?
- }
+ write!(self.out, "{}", name)?
}
// Panic if either Image or Sampler is being written
//
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -960,7 +942,12 @@ impl<'a, W: Write> Writer<'a, W> {
///
/// # Notes
/// Ends in a newline
- fn write_struct(&mut self, handle: Handle<Type>, members: &[StructMember]) -> BackendResult {
+ fn write_struct(
+ &mut self,
+ block: bool,
+ handle: Handle<Type>,
+ members: &[StructMember],
+ ) -> BackendResult {
// glsl structs are written as in C
// `struct name() { members };`
// | `struct` is a keyword
diff --git a/src/back/glsl/mod.rs b/src/back/glsl/mod.rs
--- a/src/back/glsl/mod.rs
+++ b/src/back/glsl/mod.rs
@@ -968,29 +955,62 @@ impl<'a, W: Write> Writer<'a, W> {
// | `members` is a semicolon separated list of `type name`
// | `type` is the member type
// | `name` is the member name
-
- writeln!(self.out, "struct {} {{", self.names[&NameKey::Type(handle)])?;
+ let name = &self.names[&NameKey::Type(handle)];
+
+ // If struct is a block we need to write `block_name { members }` where `block_name` must be
+ // unique between blocks and structs so we add `_block_ID` where `ID` is a `IdGenerator`
+ // generated number so it's unique and `members` are the same as in a struct
+ if block {
+ // Write the block name, it's just the struct name appended with `_block_ID`
+ writeln!(self.out, "{}_block_{} {{", name, self.block_id.generate())?;
+ } else {
+ writeln!(self.out, "struct {} {{", name)?;
+ }
for (idx, member) in members.iter().enumerate() {
// The indentation is only for readability
write!(self.out, "{}", INDENT)?;
- // Write the member type
- // Adds no trailing space
- self.write_type(member.ty)?;
+ match self.module.types[member.ty].inner {
+ TypeInner::Array { base, .. } => {
+ // GLSL arrays are written as `type name[size]`
+ // Write `type` and `name`
+ let ty_name = &self.names[&NameKey::Type(base)];
+ write!(self.out, "{}", ty_name)?;
+ write!(
+ self.out,
+ " {}",
+ &self.names[&NameKey::StructMember(handle, idx as u32)]
+ )?;
+ // Write [size]
+ self.write_type(member.ty)?;
+ // Newline is important
+ writeln!(self.out, ";")?;
+ }
+ _ => {
+ // Write the member type
+ // Adds no trailing space
+ self.write_type(member.ty)?;
- // Write the member name and put a semicolon
- // The leading space is important
- // All members must have a semicolon even the last one
- writeln!(
- self.out,
- " {};",
- self.names[&NameKey::StructMember(handle, idx as u32)]
- )?;
+ // Write the member name and put a semicolon
+ // The leading space is important
+ // All members must have a semicolon even the last one
+ writeln!(
+ self.out,
+ " {};",
+ &self.names[&NameKey::StructMember(handle, idx as u32)]
+ )?;
+ }
+ }
}
- writeln!(self.out, "}};")?;
- writeln!(self.out)?;
+ write!(self.out, "}}")?;
+
+ if !block {
+ writeln!(self.out, ";")?;
+ // Add a newline for readability
+ writeln!(self.out)?;
+ }
Ok(())
}
|
diff --git /dev/null b/tests/out/shadow-Fragment.glsl.snap
new file mode 100644
--- /dev/null
+++ b/tests/out/shadow-Fragment.glsl.snap
@@ -0,0 +1,53 @@
+---
+source: tests/snapshots.rs
+expression: string
+---
+#version 310 es
+
+precision highp float;
+
+struct Light {
+ mat4x4 proj;
+ vec4 pos;
+ vec4 color;
+};
+
+uniform Globals_block_0 {
+ uvec4 num_lights;
+} _group_0_binding_0;
+
+readonly buffer Lights_block_1 {
+ Light data[];
+} _group_0_binding_1;
+
+uniform highp sampler2DArrayShadow _group_0_binding_2;
+
+in vec3 _location_0_vs;
+
+in vec4 _location_1_vs;
+
+out vec4 _location_0;
+
+float fetch_shadow(uint light_id, vec4 homogeneous_coords) {
+ if((homogeneous_coords[3] <= 0.0)) {
+ return 1.0;
+ }
+ return textureGrad(_group_0_binding_2, vec4((((vec2(homogeneous_coords[0], homogeneous_coords[1]) * vec2(0.5, -0.5)) * (1.0 / homogeneous_coords[3])) + vec2(0.5, 0.5)), int(light_id), (homogeneous_coords[2] * (1.0 / homogeneous_coords[3]))), vec2(0, 0), vec2(0,0));
+}
+
+void main() {
+ vec3 color1 = vec3(0.05, 0.05, 0.05);
+ uint i = 0u;
+ while(true) {
+ if((i >= min(_group_0_binding_0.num_lights[0], 10u))) {
+ break;
+ }
+ Light _expr23 = _group_0_binding_1.data[i];
+ float _expr28 = fetch_shadow(i, (_expr23.proj * _location_1_vs));
+ vec4 _expr34 = _location_1_vs;
+ color1 = (color1 + ((_expr28 * max(0.0, dot(normalize(_location_0_vs), normalize((vec3(_expr23.pos[0], _expr23.pos[1], _expr23.pos[2]) - vec3(_expr34[0], _expr34[1], _expr34[2])))))) * vec3(_expr23.color[0], _expr23.color[1], _expr23.color[2])));
+ i = (i + 1u);
+ }
+ _location_0 = vec4(color1, 1.0);
+ return;
+}
diff --git a/tests/out/skybox-Fragment.glsl.snap b/tests/out/skybox-Fragment.glsl.snap
--- a/tests/out/skybox-Fragment.glsl.snap
+++ b/tests/out/skybox-Fragment.glsl.snap
@@ -6,11 +6,6 @@ expression: string
precision highp float;
-struct Data {
- mat4x4 proj_inv;
- mat4x4 view;
-};
-
uniform highp samplerCube _group_0_binding_1;
in vec3 _location_0_vs;
diff --git a/tests/out/skybox-Vertex.glsl.snap b/tests/out/skybox-Vertex.glsl.snap
--- a/tests/out/skybox-Vertex.glsl.snap
+++ b/tests/out/skybox-Vertex.glsl.snap
@@ -6,11 +6,6 @@ expression: string
precision highp float;
-struct Data {
- mat4x4 proj_inv;
- mat4x4 view;
-};
-
out vec3 _location_0_vs;
uniform Data_block_0 {
diff --git a/tests/snapshots.rs b/tests/snapshots.rs
--- a/tests/snapshots.rs
+++ b/tests/snapshots.rs
@@ -259,7 +259,7 @@ fn convert_wgsl_collatz() {
#[cfg(feature = "wgsl-in")]
#[test]
fn convert_wgsl_shadow() {
- convert_wgsl("shadow", Targets::SPIRV | Targets::METAL);
+ convert_wgsl("shadow", Targets::SPIRV | Targets::METAL | Targets::GLSL);
}
#[cfg(feature = "wgsl-in")]
|
[glsl-out] Properly write array type
Current implementation caused validation error with `glslangValidator`.
```glsl
readonly buffer Lights_block_1 {
Light[] data;
} _group_0_binding_1;
```
Should be: `Light data[];`
|
2021-03-10T20:58:12Z
|
0.3
|
2021-03-10T20:41:19Z
|
77a64da189e6ed2c4631ca03cb01b8d8124c4dad
|
[
"convert_wgsl_skybox",
"convert_wgsl_shadow"
] |
[
"arena::tests::fetch_or_append_unique",
"arena::tests::fetch_or_append_non_unique",
"arena::tests::append_non_unique",
"arena::tests::append_unique",
"back::spv::layout::test_physical_layout_in_words",
"back::spv::layout::test_logical_layout_in_words",
"front::glsl::constants::tests::access",
"back::spv::writer::test_writer_generate_id",
"back::spv::writer::test_write_physical_layout",
"front::glsl::constants::tests::cast",
"front::glsl::lex::tests::lex_tokens",
"front::glsl::constants::tests::unary_op",
"front::spv::test::parse",
"front::wgsl::lexer::test_tokens",
"front::wgsl::lexer::test_variable_decl",
"front::wgsl::tests::parse_comment",
"front::wgsl::tests::parse_statement",
"front::glsl::parser_tests::constants",
"front::wgsl::tests::parse_if",
"front::wgsl::tests::parse_struct",
"front::glsl::parser_tests::version",
"front::wgsl::tests::parse_standard_fun",
"proc::analyzer::uniform_control_flow",
"front::wgsl::tests::parse_expressions",
"front::wgsl::tests::parse_postfix",
"front::wgsl::tests::parse_loop",
"front::wgsl::tests::parse_types",
"front::wgsl::tests::parse_switch",
"front::glsl::parser_tests::textures",
"front::glsl::parser_tests::functions",
"front::wgsl::tests::parse_texture_query",
"front::wgsl::tests::parse_texture_load",
"front::wgsl::tests::parse_type_cast",
"front::glsl::parser_tests::control_flow",
"invalid_integer",
"invalid_scalar_width",
"function_without_identifier",
"invalid_float",
"invalid_accessor",
"parse_glsl",
"convert_glsl_quad",
"convert_wgsl_texture_array",
"convert_wgsl_empty",
"convert_wgsl_quad",
"convert_wgsl_boids",
"convert_wgsl_collatz",
"convert_spv_shadow"
] |
[] |
[] |
|
dtolnay/anyhow
| 34
|
dtolnay__anyhow-34
|
[
"32"
] |
5e04e776efae33b311a850a0b6bae3104b90e1d4
|
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -5,7 +5,7 @@ use std::error::Error as StdError;
use std::fmt::{self, Debug, Display};
use std::mem::{self, ManuallyDrop};
use std::ops::{Deref, DerefMut};
-use std::ptr;
+use std::ptr::{self, NonNull};
impl Error {
/// Create a new error object from any error type.
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -29,11 +29,11 @@ impl Error {
{
let vtable = &ErrorVTable {
object_drop: object_drop::<E>,
- object_drop_front: object_drop_front::<E>,
object_ref: object_ref::<E>,
object_mut: object_mut::<E>,
object_boxed: object_boxed::<E>,
- object_is: object_is::<E>,
+ object_downcast: object_downcast::<E>,
+ object_drop_rest: object_drop_front::<E>,
};
// Safety: passing vtable that operates on the right type E.
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -47,11 +47,11 @@ impl Error {
let error: MessageError<M> = MessageError(message);
let vtable = &ErrorVTable {
object_drop: object_drop::<MessageError<M>>,
- object_drop_front: object_drop_front::<MessageError<M>>,
object_ref: object_ref::<MessageError<M>>,
object_mut: object_mut::<MessageError<M>>,
object_boxed: object_boxed::<MessageError<M>>,
- object_is: object_is::<M>,
+ object_downcast: object_downcast::<M>,
+ object_drop_rest: object_drop_front::<M>,
};
// Safety: MessageError is repr(transparent) so it is okay for the
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -66,11 +66,11 @@ impl Error {
let error: DisplayError<M> = DisplayError(message);
let vtable = &ErrorVTable {
object_drop: object_drop::<DisplayError<M>>,
- object_drop_front: object_drop_front::<DisplayError<M>>,
object_ref: object_ref::<DisplayError<M>>,
object_mut: object_mut::<DisplayError<M>>,
object_boxed: object_boxed::<DisplayError<M>>,
- object_is: object_is::<M>,
+ object_downcast: object_downcast::<M>,
+ object_drop_rest: object_drop_front::<M>,
};
// Safety: DisplayError is repr(transparent) so it is okay for the
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -87,11 +87,11 @@ impl Error {
let vtable = &ErrorVTable {
object_drop: object_drop::<ContextError<C, E>>,
- object_drop_front: object_drop_front::<ContextError<C, E>>,
object_ref: object_ref::<ContextError<C, E>>,
object_mut: object_mut::<ContextError<C, E>>,
object_boxed: object_boxed::<ContextError<C, E>>,
- object_is: object_is::<ContextError<C, E>>,
+ object_downcast: context_downcast::<C, E>,
+ object_drop_rest: context_drop_rest::<C, E>,
};
// Safety: passing vtable that operates on the right type.
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -114,7 +114,7 @@ impl Error {
let inner = Box::new(ErrorImpl {
vtable,
backtrace,
- _error: error,
+ _object: error,
});
let erased = mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner);
let inner = ManuallyDrop::new(erased);
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -186,11 +186,11 @@ impl Error {
let vtable = &ErrorVTable {
object_drop: object_drop::<ContextError<C, Error>>,
- object_drop_front: object_drop_front::<ContextError<C, Error>>,
object_ref: object_ref::<ContextError<C, Error>>,
object_mut: object_mut::<ContextError<C, Error>>,
object_boxed: object_boxed::<ContextError<C, Error>>,
- object_is: object_is::<ContextError<C, Error>>,
+ object_downcast: context_chain_downcast::<C>,
+ object_drop_rest: context_chain_drop_rest::<C>,
};
// As the cause is anyhow::Error, we already have a backtrace for it.
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -255,13 +255,19 @@ impl Error {
root_cause
}
- /// Returns `true` if `E` is the type wrapped by this error object.
+ /// Returns true if `E` is the type held by this error object.
+ ///
+ /// For errors with context, this method returns true if `E` matches the
+ /// type of the context `C` **or** the type of the error on which the
+ /// context has been attached. For details about the interaction between
+ /// context and downcasting, [see here].
+ ///
+ /// [see here]: trait.Context.html#effect-on-downcasting
pub fn is<E>(&self) -> bool
where
E: Display + Debug + Send + Sync + 'static,
{
- let target = TypeId::of::<E>();
- unsafe { (self.inner.vtable.object_is)(target) }
+ self.downcast_ref::<E>().is_some()
}
/// Attempt to downcast the error object to a concrete type.
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -269,19 +275,18 @@ impl Error {
where
E: Display + Debug + Send + Sync + 'static,
{
- if self.is::<E>() {
+ let target = TypeId::of::<E>();
+ unsafe {
+ let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {
+ Some(addr) => addr,
+ None => return Err(self),
+ };
let outer = ManuallyDrop::new(self);
- unsafe {
- let error = ptr::read(
- outer.inner.error() as *const (dyn StdError + Send + Sync) as *const E
- );
- let inner = ptr::read(&outer.inner);
- let erased = ManuallyDrop::into_inner(inner);
- (erased.vtable.object_drop_front)(erased);
- Ok(error)
- }
- } else {
- Err(self)
+ let error = ptr::read(addr.cast::<E>().as_ptr());
+ let inner = ptr::read(&outer.inner);
+ let erased = ManuallyDrop::into_inner(inner);
+ (erased.vtable.object_drop_rest)(erased, target);
+ Ok(error)
}
}
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -325,12 +330,10 @@ impl Error {
where
E: Display + Debug + Send + Sync + 'static,
{
- if self.is::<E>() {
- Some(unsafe {
- &*(self.inner.error() as *const (dyn StdError + Send + Sync) as *const E)
- })
- } else {
- None
+ let target = TypeId::of::<E>();
+ unsafe {
+ let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;
+ Some(&*addr.cast::<E>().as_ptr())
}
}
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -339,12 +342,10 @@ impl Error {
where
E: Display + Debug + Send + Sync + 'static,
{
- if self.is::<E>() {
- Some(unsafe {
- &mut *(self.inner.error_mut() as *mut (dyn StdError + Send + Sync) as *mut E)
- })
- } else {
- None
+ let target = TypeId::of::<E>();
+ unsafe {
+ let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;
+ Some(&mut *addr.cast::<E>().as_ptr())
}
}
}
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -400,11 +401,11 @@ impl Drop for Error {
struct ErrorVTable {
object_drop: unsafe fn(Box<ErrorImpl<()>>),
- object_drop_front: unsafe fn(Box<ErrorImpl<()>>),
object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),
object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),
object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,
- object_is: unsafe fn(TypeId) -> bool,
+ object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,
+ object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),
}
unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -414,10 +415,11 @@ unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {
drop(unerased);
}
-unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>) {
+unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {
// Drop the fields of ErrorImpl other than E as well as the Box allocation,
// without dropping E itself. This is used by downcast after doing a
// ptr::read to take ownership of the E.
+ let _ = target;
let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);
drop(unerased);
}
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -426,14 +428,14 @@ unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'st
where
E: StdError + Send + Sync + 'static,
{
- &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._error
+ &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object
}
unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)
where
E: StdError + Send + Sync + 'static,
{
- &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._error
+ &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._object
}
unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>
diff --git a/src/error.rs b/src/error.rs
--- a/src/error.rs
+++ b/src/error.rs
@@ -443,22 +445,111 @@ where
mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)
}
-unsafe fn object_is<T>(target: TypeId) -> bool
+unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
+where
+ E: 'static,
+{
+ if TypeId::of::<E>() == target {
+ let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;
+ let addr = &(*unerased)._object as *const E as *mut ();
+ Some(NonNull::new_unchecked(addr))
+ } else {
+ None
+ }
+}
+
+unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
where
- T: 'static,
+ C: 'static,
+ E: 'static,
{
- TypeId::of::<T>() == target
+ if TypeId::of::<C>() == target {
+ let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;
+ let addr = &(*unerased)._object.context as *const C as *mut ();
+ Some(NonNull::new_unchecked(addr))
+ } else if TypeId::of::<E>() == target {
+ let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;
+ let addr = &(*unerased)._object.error as *const E as *mut ();
+ Some(NonNull::new_unchecked(addr))
+ } else {
+ None
+ }
}
-// repr C to ensure that `E` remains in the final position
+unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)
+where
+ C: 'static,
+ E: 'static,
+{
+ // Called after downcasting by value to either the C or the E and doing a
+ // ptr::read to take ownership of that value.
+ if TypeId::of::<C>() == target {
+ let unerased = mem::transmute::<
+ Box<ErrorImpl<()>>,
+ Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,
+ >(e);
+ drop(unerased);
+ } else {
+ let unerased = mem::transmute::<
+ Box<ErrorImpl<()>>,
+ Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,
+ >(e);
+ drop(unerased);
+ }
+}
+
+unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
+where
+ C: 'static,
+{
+ if TypeId::of::<C>() == target {
+ let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;
+ let addr = &(*unerased)._object.context as *const C as *mut ();
+ Some(NonNull::new_unchecked(addr))
+ } else {
+ let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;
+ let source = &(*unerased)._object.error;
+ (source.inner.vtable.object_downcast)(&source.inner, target)
+ }
+}
+
+unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)
+where
+ C: 'static,
+{
+ // Called after downcasting by value to either the C or one of the causes
+ // and doing a ptr::read to take ownership of that value.
+ if TypeId::of::<C>() == target {
+ let unerased = mem::transmute::<
+ Box<ErrorImpl<()>>,
+ Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,
+ >(e);
+ drop(unerased);
+ } else {
+ let unerased = mem::transmute::<
+ Box<ErrorImpl<()>>,
+ Box<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>,
+ >(e);
+ let inner = ptr::read(&unerased._object.error.inner);
+ drop(unerased);
+ let erased = ManuallyDrop::into_inner(inner);
+ (erased.vtable.object_drop_rest)(erased, target);
+ }
+}
+
+// repr C to ensure that E remains in the final position.
#[repr(C)]
pub(crate) struct ErrorImpl<E> {
vtable: &'static ErrorVTable,
backtrace: Option<Backtrace>,
- // NOTE: Don't use directly. Use only through vtable. Erased type may have different alignment.
- _error: E,
+ // NOTE: Don't use directly. Use only through vtable. Erased type may have
+ // different alignment.
+ _object: E,
}
+// repr C to ensure that ContextError<C, E> has the same layout as
+// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.
+#[repr(C)]
pub(crate) struct ContextError<C, E> {
pub context: C,
pub error: E,
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -286,6 +286,8 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
/// This trait is sealed and cannot be implemented for types outside of
/// `anyhow`.
///
+/// <br>
+///
/// # Example
///
/// ```
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -326,6 +328,100 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Caused by:
/// No such file or directory (os error 2)
/// ```
+///
+/// <br>
+///
+/// # Effect on downcasting
+///
+/// After attaching context of type `C` onto an error of type `E`, the resulting
+/// `anyhow::Error` may be downcast to `C` **or** to `E`.
+///
+/// That is, in codebases that rely on downcasting, Anyhow's context supports
+/// both of the following use cases:
+///
+/// - **Attaching context whose type is insignificant onto errors whose type
+/// is used in downcasts.**
+///
+/// In other error libraries whose context is not designed this way, it can
+/// be risky to introduce context to existing code because new context might
+/// break existing working downcasts. In Anyhow, any downcast that worked
+/// before adding context will continue to work after you add a context, so
+/// you should freely add human-readable context to errors wherever it would
+/// be helpful.
+///
+/// ```
+/// # use anyhow::bail;
+/// # use thiserror::Error;
+/// #
+/// # #[derive(Error, Debug)]
+/// # #[error("???")]
+/// # struct SuspiciousError;
+/// #
+/// # fn helper() -> Result<()> {
+/// # bail!(SuspiciousError);
+/// # }
+/// #
+/// use anyhow::{Context, Result};
+///
+/// fn do_it() -> Result<()> {
+/// helper().context("failed to complete the work")?;
+/// # const IGNORE: &str = stringify! {
+/// ...
+/// # };
+/// # unreachable!()
+/// }
+///
+/// fn main() {
+/// let err = do_it().unwrap_err();
+/// if let Some(e) = err.downcast_ref::<SuspiciousError>() {
+/// // If helper() returned SuspiciousError, this downcast will
+/// // correctly succeed even with the context in between.
+/// # return;
+/// }
+/// # panic!("expected downcast to succeed");
+/// }
+/// ```
+///
+/// - **Attaching context whose type is used in downcasts onto errors whose
+/// type is insignificant.**
+///
+/// Some codebases prefer to use machine-readable context to categorize
+/// lower level errors in a way that will be actionable to higher levels of
+/// the application.
+///
+/// ```
+/// # use anyhow::bail;
+/// # use thiserror::Error;
+/// #
+/// # #[derive(Error, Debug)]
+/// # #[error("???")]
+/// # struct HelperFailed;
+/// #
+/// # fn helper() -> Result<()> {
+/// # bail!("no such file or directory");
+/// # }
+/// #
+/// use anyhow::{Context, Result};
+///
+/// fn do_it() -> Result<()> {
+/// helper().context(HelperFailed)?;
+/// # const IGNORE: &str = stringify! {
+/// ...
+/// # };
+/// # unreachable!()
+/// }
+///
+/// fn main() {
+/// let err = do_it().unwrap_err();
+/// if let Some(e) = err.downcast_ref::<HelperFailed>() {
+/// // If helper failed, this downcast will succeed because
+/// // HelperFailed is the context that has been attached to
+/// // that error.
+/// # return;
+/// }
+/// # panic!("expected downcast to succeed");
+/// }
+/// ```
pub trait Context<T, E>: context::private::Sealed {
/// Wrap the error value with additional context.
fn context<C>(self, context: C) -> Result<T, Error>
|
diff --git a/tests/test_context.rs b/tests/test_context.rs
--- a/tests/test_context.rs
+++ b/tests/test_context.rs
@@ -1,4 +1,9 @@
-use anyhow::{Context, Result};
+mod drop;
+
+use crate::drop::{DetectDrop, Flag};
+use anyhow::{Context, Error, Result};
+use std::fmt::{self, Display};
+use thiserror::Error;
// https://github.com/dtolnay/anyhow/issues/18
#[test]
diff --git a/tests/test_context.rs b/tests/test_context.rs
--- a/tests/test_context.rs
+++ b/tests/test_context.rs
@@ -8,3 +13,147 @@ fn test_inference() -> Result<()> {
assert_eq!(y, 1);
Ok(())
}
+
+macro_rules! context_type {
+ ($name:ident) => {
+ #[derive(Debug)]
+ struct $name {
+ message: &'static str,
+ drop: DetectDrop,
+ }
+
+ impl Display for $name {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.write_str(self.message)
+ }
+ }
+ };
+}
+
+context_type!(HighLevel);
+context_type!(MidLevel);
+
+#[derive(Error, Debug)]
+#[error("{message}")]
+struct LowLevel {
+ message: &'static str,
+ drop: DetectDrop,
+}
+
+struct Dropped {
+ low: Flag,
+ mid: Flag,
+ high: Flag,
+}
+
+impl Dropped {
+ fn none(&self) -> bool {
+ !self.low.get() && !self.mid.get() && !self.high.get()
+ }
+
+ fn all(&self) -> bool {
+ self.low.get() && self.mid.get() && self.high.get()
+ }
+}
+
+fn make_chain() -> (Error, Dropped) {
+ let dropped = Dropped {
+ low: Flag::new(),
+ mid: Flag::new(),
+ high: Flag::new(),
+ };
+
+ let low = LowLevel {
+ message: "no such file or directory",
+ drop: DetectDrop::new(&dropped.low),
+ };
+
+ // impl Context for Result<T, E>
+ let mid = Err::<(), LowLevel>(low)
+ .context(MidLevel {
+ message: "failed to load config",
+ drop: DetectDrop::new(&dropped.mid),
+ })
+ .unwrap_err();
+
+ // impl Context for Result<T, Error>
+ let high = Err::<(), Error>(mid)
+ .context(HighLevel {
+ message: "failed to start server",
+ drop: DetectDrop::new(&dropped.high),
+ })
+ .unwrap_err();
+
+ (high, dropped)
+}
+
+#[test]
+fn test_downcast_ref() {
+ let (err, dropped) = make_chain();
+
+ assert!(!err.is::<String>());
+ assert!(err.downcast_ref::<String>().is_none());
+
+ assert!(err.is::<HighLevel>());
+ let high = err.downcast_ref::<HighLevel>().unwrap();
+ assert_eq!(high.to_string(), "failed to start server");
+
+ assert!(err.is::<MidLevel>());
+ let mid = err.downcast_ref::<MidLevel>().unwrap();
+ assert_eq!(mid.to_string(), "failed to load config");
+
+ assert!(err.is::<LowLevel>());
+ let low = err.downcast_ref::<LowLevel>().unwrap();
+ assert_eq!(low.to_string(), "no such file or directory");
+
+ assert!(dropped.none());
+ drop(err);
+ assert!(dropped.all());
+}
+
+#[test]
+fn test_downcast_high() {
+ let (err, dropped) = make_chain();
+
+ let err = err.downcast::<HighLevel>().unwrap();
+ assert!(!dropped.high.get());
+ assert!(dropped.low.get() && dropped.mid.get());
+
+ drop(err);
+ assert!(dropped.all());
+}
+
+#[test]
+fn test_downcast_mid() {
+ let (err, dropped) = make_chain();
+
+ let err = err.downcast::<MidLevel>().unwrap();
+ assert!(!dropped.mid.get());
+ assert!(dropped.low.get() && dropped.high.get());
+
+ drop(err);
+ assert!(dropped.all());
+}
+
+#[test]
+fn test_downcast_low() {
+ let (err, dropped) = make_chain();
+
+ let err = err.downcast::<LowLevel>().unwrap();
+ assert!(!dropped.low.get());
+ assert!(dropped.mid.get() && dropped.high.get());
+
+ drop(err);
+ assert!(dropped.all());
+}
+
+#[test]
+fn test_unsuccessful_downcast() {
+ let (err, dropped) = make_chain();
+
+ let err = err.downcast::<String>().unwrap_err();
+ assert!(dropped.none());
+
+ drop(err);
+ assert!(dropped.all());
+}
|
Figure out how context should interact with downcasting
For example if we have:
```rust
let e = fs::read("/...").context(ReadFailed).unwrap_err();
match e.downcast_ref::<ReadFailed>() {
```
should this downcast succeed or fail?
|
For that matter, should `e.downcast_ref::<io::Error>()` succeed?
|
2019-10-28T12:27:06Z
|
1.0
|
2019-10-28T04:41:06Z
|
2737bbeb59f50651ff54ca3d879a3f5d659a98ab
|
[
"test_downcast_high",
"test_downcast_low",
"test_downcast_mid"
] |
[
"test_downcast_ref",
"test_inference",
"test_unsuccessful_downcast",
"test_convert",
"test_question_mark",
"test_downcast_mut",
"test_drop",
"test_downcast",
"test_large_alignment",
"test_display",
"test_ensure",
"test_messages",
"test_error_size",
"test_null_pointer_optimization",
"test_autotraits",
"test_fmt_source",
"test_io_source",
"test_literal_source",
"test_variable_source",
"src/context.rs - context::Option<T> (line 62)",
"src/lib.rs - (line 15)",
"src/lib.rs - Chain (line 216)",
"src/error.rs - error::Error::chain (line 227)",
"src/lib.rs - (line 157)",
"src/lib.rs - (line 48)",
"src/error.rs - error::Error::context (line 134)",
"src/lib.rs - (line 138)",
"src/lib.rs - (line 93)",
"src/lib.rs - Result (line 241)",
"src/macros.rs - anyhow (line 158)",
"src/lib.rs - Result (line 255)",
"src/macros.rs - bail (line 7)",
"src/macros.rs - bail (line 25)",
"src/macros.rs - ensure (line 85)",
"src/macros.rs - ensure (line 96)"
] |
[] |
[] |
dtolnay/anyhow
| 47
|
dtolnay__anyhow-47
|
[
"46"
] |
6088b60791fc063f35183df8a4706a8723a8568a
|
diff --git a/src/kind.rs b/src/kind.rs
--- a/src/kind.rs
+++ b/src/kind.rs
@@ -45,7 +45,6 @@
// (&error).anyhow_kind().new(error)
use crate::Error;
-use std::error::Error as StdError;
use std::fmt::{Debug, Display};
#[cfg(backtrace)]
diff --git a/src/kind.rs b/src/kind.rs
--- a/src/kind.rs
+++ b/src/kind.rs
@@ -80,13 +79,13 @@ pub trait TraitKind: Sized {
}
}
-impl<T> TraitKind for T where T: StdError + Send + Sync + 'static {}
+impl<E> TraitKind for E where E: Into<Error> {}
impl Trait {
pub fn new<E>(self, error: E) -> Error
where
- E: StdError + Send + Sync + 'static,
+ E: Into<Error>,
{
- Error::from_std(error, backtrace!())
+ error.into()
}
}
|
diff --git a/tests/test_source.rs b/tests/test_source.rs
--- a/tests/test_source.rs
+++ b/tests/test_source.rs
@@ -53,3 +53,10 @@ fn test_io_source() {
let error = anyhow!(TestError::Io(io));
assert_eq!("oh no!", error.source().unwrap().to_string());
}
+
+#[test]
+fn test_anyhow_from_anyhow() {
+ let error = anyhow!("oh no!").context("context");
+ let error = anyhow!(error);
+ assert_eq!("oh no!", error.source().unwrap().to_string());
+}
|
Usage of `bail!(error)` loses the context of `error`
I was in a situation recently where I was doing:
```rust
match some_result {
Ok(()) => {}
Err(e) => {
if !err_is_ok(e) {
bail!(e);
}
}
}
```
in this case `e` was actually of type `anyhow::Error` so a `return Err(e)` would have worked just fine, but I was surprised when this `bail!()` lost the context of the error of `e`, presumably because it called `.to_string()` on the result and lost all the context information.
|
2019-11-19T03:43:20Z
|
1.0
|
2019-11-18T19:46:40Z
|
2737bbeb59f50651ff54ca3d879a3f5d659a98ab
|
[
"test_anyhow_from_anyhow"
] |
[
"test_sync",
"test_send",
"test_iter",
"test_rev",
"test_len",
"test_downcast_low",
"test_downcast_high",
"test_downcast_mid",
"test_downcast_ref",
"test_inference",
"test_unsuccessful_downcast",
"test_question_mark",
"test_convert",
"test_downcast",
"test_downcast_mut",
"test_drop",
"test_large_alignment",
"test_altdebug",
"test_altdisplay",
"test_display",
"test_ensure",
"test_messages",
"test_autotraits",
"test_error_size",
"test_null_pointer_optimization",
"test_fmt_source",
"test_io_source",
"test_variable_source",
"test_literal_source",
"src/lib.rs - Chain (line 291)",
"src/lib.rs - (line 15)",
"src/lib.rs - (line 138)",
"src/context.rs - context::Option<T> (line 62)",
"src/lib.rs - Context (line 369)",
"src/error.rs - error::Error::chain (line 278)",
"src/lib.rs - (line 157)",
"src/error.rs - error::Error::context (line 185)",
"src/lib.rs - (line 48)",
"src/error.rs - error::Error::downcast_ref (line 361)",
"src/error.rs - error::Error::msg (line 39)",
"src/lib.rs - (line 93)",
"src/lib.rs - Result (line 317)",
"src/macros.rs - anyhow (line 158)",
"src/lib.rs - Error (line 263)",
"src/macros.rs - bail (line 7)",
"src/lib.rs - Result (line 331)",
"src/macros.rs - ensure (line 85)",
"src/macros.rs - bail (line 25)",
"src/macros.rs - ensure (line 96)",
"src/lib.rs - Context (line 429)",
"src/lib.rs - Context (line 470)"
] |
[] |
[] |
|
dimforge/nalgebra
| 813
|
dimforge__nalgebra-813
|
[
"812"
] |
8bc277332625e6cf18fc17a4432000179ac7b5ae
|
diff --git a/src/base/array_storage.rs b/src/base/array_storage.rs
--- a/src/base/array_storage.rs
+++ b/src/base/array_storage.rs
@@ -377,7 +377,7 @@ where
where
V: SeqAccess<'a>,
{
- let mut out: Self::Value = unsafe { mem::uninitialized() };
+ let mut out: Self::Value = unsafe { mem::MaybeUninit::uninit().assume_init() };
let mut curr = 0;
while let Some(value) = visitor.next_element()? {
diff --git a/src/base/conversion.rs b/src/base/conversion.rs
--- a/src/base/conversion.rs
+++ b/src/base/conversion.rs
@@ -257,9 +257,8 @@ macro_rules! impl_from_into_mint_1D(
#[inline]
fn into(self) -> mint::$VT<N> {
unsafe {
- let mut res: mint::$VT<N> = mem::uninitialized();
+ let mut res: mint::$VT<N> = mem::MaybeUninit::uninit().assume_init();
ptr::copy_nonoverlapping(self.data.ptr(), &mut res.x, $SZ);
-
res
}
}
diff --git a/src/base/conversion.rs b/src/base/conversion.rs
--- a/src/base/conversion.rs
+++ b/src/base/conversion.rs
@@ -324,7 +323,7 @@ macro_rules! impl_from_into_mint_2D(
#[inline]
fn into(self) -> mint::$MV<N> {
unsafe {
- let mut res: mint::$MV<N> = mem::uninitialized();
+ let mut res: mint::$MV<N> = mem::MaybeUninit::uninit().assume_init();
let mut ptr = self.data.ptr();
$(
ptr::copy_nonoverlapping(ptr, &mut res.$component.x, $SZRows);
|
diff --git a/tests/core/serde.rs b/tests/core/serde.rs
--- a/tests/core/serde.rs
+++ b/tests/core/serde.rs
@@ -3,9 +3,10 @@
use na::{
DMatrix, Isometry2, Isometry3, IsometryMatrix2, IsometryMatrix3, Matrix3x4, Point2, Point3,
Quaternion, Rotation2, Rotation3, Similarity2, Similarity3, SimilarityMatrix2,
- SimilarityMatrix3, Translation2, Translation3, Unit,
+ SimilarityMatrix3, Translation2, Translation3, Unit, Vector2,
};
use rand;
+use serde::{Deserialize, Serialize};
use serde_json;
macro_rules! test_serde(
diff --git a/tests/core/serde.rs b/tests/core/serde.rs
--- a/tests/core/serde.rs
+++ b/tests/core/serde.rs
@@ -54,3 +55,16 @@ fn serde_flat() {
let serialized = serde_json::to_string(&v).unwrap();
assert_eq!(serialized, "[0.0,0.0,1.0,0.0]");
}
+
+#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
+enum Stuff {
+ A(f64),
+ B(f64),
+}
+
+#[test]
+fn deserialize_enum() {
+ let json = r#"[{"letter":"A", "value":123.4}, {"letter":"B", "value":567.8}]"#;
+ let parsed: Result<Vector2<Stuff>, _> = serde_json::from_str(json);
+ println!("parsed: {:?}", parsed);
+}
|
Deserialization in serde panics in rustc 1.48+ with some enum inner types
This error presents as: ```attempted to leave type `nalgebra::ArrayStorage<...>` uninitialized, which is invalid```
This line of code panics: https://github.com/dimforge/nalgebra/blob/c0f4ee6db96952ab42c3505d1647cfeda86616b1/src/base/array_storage.rs#L380
This panic is mentioned in the [1.48 detailed notes](https://github.com/rust-lang/rust/blob/master/RELEASES.md#compatibility-notes) as
> [mem::uninitialized will now panic if any inner types inside a struct or enum disallow zero-initialization.](https://github.com/rust-lang/rust/pull/71274/)
The tracking issue for this is here: https://github.com/rust-lang/rust/issues/66151
The way `visit_seq` is implemented looks like it should correctly initialize the whole matrix or drop the partially initialized matrix and return an `Err`. Can this function use a compiler version switch to use `MaybeUninit::uninit().assume_init()` mentioned in the [std::mem::uninitialized deprecation notes](https://doc.rust-lang.org/std/mem/fn.uninitialized.html)?
|
This minimal example triggers the failure:
`src/main.rs`
```
extern crate nalgebra;
extern crate serde;
extern crate serde_json;
use nalgebra::Vector2;
use serde_derive::{Serialize, Deserialize};
use serde_json::from_str;
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
#[serde(tag = "letter", content = "value")]
enum Stuff {
A(f64),
B(f64),
}
fn main() {
let json = r#"[{"letter":"A", "value":123.4}, {"letter":"B", "value":567.8}]"#;
// Boom:
// thread 'main' panicked at 'attempted to leave type `nalgebra::ArrayStorage<Stuff, nalgebra::U2, nalgebra::U1>` uninitialized, which is invalid', /home/nicodemus/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/mem/mod.rs:658:9
let parsed: Result<Vector2<Stuff>, _> = from_str(json);
println!("parsed: {:?}", parsed);
}
```
`Cargo.toml`
```
[package]
name = "nalgebra_issue_812"
version = "0.1.0"
authors = ["Nicodemus Paradiso <nicodemus26@gmail.com>"]
edition = "2018"
[dependencies]
serde = "1.0.118"
serde_json = "1.0.60"
serde_derive = "1.0.118"
[dependencies.nalgebra]
version = "0.23.1"
features = [
"std", "serde-serialize"
]
```
With 1.47:
```
$ rustup override set 1.47
info: using existing install for '1.47-x86_64-unknown-linux-gnu'
info: override toolchain set to '1.47-x86_64-unknown-linux-gnu'
1.47-x86_64-unknown-linux-gnu unchanged - rustc 1.47.0 (18bf6b4f0 2020-10-07)
$ cargo run
...
Compiling nalgebra_issue_812 v0.1.0
Finished dev [unoptimized + debuginfo] target(s) in 39.54s
Running `target/debug/nalgebra_issue_812`
parsed: Ok(Matrix { data: [A(123.4), B(567.8)] })
```
|
2020-12-18T18:56:35Z
|
0.23
|
2020-12-18T11:06:44Z
|
81d29040d7c894ab550d686ec6f52d1418e8c9df
|
[
"core::serde::deserialize_enum"
] |
[
"base::indexing::dimrange_rangefrom_dimname",
"base::indexing::dimrange_range_usize",
"base::indexing::dimrange_rangefrom_usize",
"base::indexing::dimrange_rangefull",
"base::indexing::dimrange_usize",
"base::indexing::dimrange_rangeinclusive_usize",
"base::indexing::dimrange_rangeto_usize",
"base::indexing::dimrange_rangetoinclusive_usize",
"linalg::exp::tests::one_norm",
"base::matrix::lower_exp",
"geometry::transform::tests::checks_homogeneous_invariants_of_square_identity_matrix",
"linalg::symmetric_eigen::test::wilkinson_shift_zero",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_det",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diag_diff_and_zero_off_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_off_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_trace",
"geometry::quaternion_construction::tests::random_unit_quats_are_unit",
"linalg::symmetric_eigen::test::wilkinson_shift_random",
"core::abomonation::abomonate_isometry3",
"core::abomonation::abomonate_quaternion",
"core::abomonation::abomonate_similarity3",
"core::abomonation::abomonate_matrix3x4",
"core::abomonation::abomonate_point3",
"core::abomonation::abomonate_rotation3",
"core::abomonation::abomonate_isometry_matrix3",
"core::abomonation::abomonate_dmatrix",
"core::abomonation::abomonate_translation3",
"core::abomonation::abomonate_similarity_matrix3",
"core::conversion::array_matrix_conversion_2_2",
"core::cg::test_scaling_wrt_point_1",
"core::cg::test_scaling_wrt_point_2",
"core::conversion::array_matrix_conversion_2_4",
"core::conversion::array_matrix_conversion_2_3",
"core::conversion::array_matrix_conversion_2_5",
"core::cg::test_scaling_wrt_point_3",
"core::conversion::array_matrix_conversion_3_5",
"core::conversion::array_matrix_conversion_2_6",
"core::conversion::array_matrix_conversion_3_2",
"core::conversion::array_matrix_conversion_3_3",
"core::conversion::array_matrix_conversion_3_4",
"core::blas::gemm_noncommutative",
"core::conversion::array_matrix_conversion_4_2",
"core::conversion::array_matrix_conversion_3_6",
"core::conversion::array_matrix_conversion_4_3",
"core::conversion::array_matrix_conversion_4_5",
"core::conversion::array_matrix_conversion_4_4",
"core::conversion::array_matrix_conversion_5_3",
"core::conversion::array_matrix_conversion_5_5",
"core::conversion::array_matrix_conversion_5_2",
"core::conversion::array_matrix_conversion_6_3",
"core::conversion::array_matrix_conversion_6_5",
"core::conversion::array_matrix_conversion_6_4",
"core::conversion::array_matrix_conversion_6_6",
"core::conversion::array_row_vector_conversion_1",
"core::conversion::array_row_vector_conversion_3",
"core::conversion::array_row_vector_conversion_4",
"core::conversion::array_row_vector_conversion_5",
"core::conversion::array_row_vector_conversion_2",
"core::conversion::array_row_vector_conversion_6",
"core::conversion::array_vector_conversion_2",
"core::conversion::array_vector_conversion_3",
"core::conversion::array_vector_conversion_1",
"core::conversion::array_vector_conversion_6",
"core::conversion::array_vector_conversion_4",
"core::conversion::array_vector_conversion_5",
"core::conversion::array_matrix_conversion_4_6",
"core::conversion::array_matrix_conversion_5_4",
"core::conversion::array_matrix_conversion_5_6",
"core::conversion::array_matrix_conversion_6_2",
"core::conversion::matrix_slice_from_matrix_ref",
"core::edition::insert_columns",
"core::edition::insert_columns_to_empty_matrix",
"core::edition::insert_rows_to_empty_matrix",
"core::edition::insert_rows",
"core::edition::remove_columns",
"core::edition::remove_columns_at",
"core::edition::remove_rows",
"core::edition::remove_rows_at",
"core::edition::resize_empty_matrix",
"core::edition::resize",
"core::edition::swap_columns",
"core::edition::swap_rows",
"core::edition::upper_lower_triangular",
"core::empty::empty_matrix_gemm",
"core::empty::empty_matrix_gemm_tr",
"core::empty::empty_matrix_mul_matrix",
"core::empty::empty_matrix_mul_vector",
"core::empty::empty_matrix_tr_mul_matrix",
"core::empty::empty_matrix_tr_mul_vector",
"core::matrix::apply",
"core::matrix::coordinates",
"core::matrix::components_mut",
"core::matrix::copy_from_slice",
"core::matrix::copy_from_slice_too_large",
"core::matrix::copy_from_slice_too_small",
"core::matrix::cross_product_vector_and_row_vector",
"core::matrix::debug_output_corresponds_to_data_container",
"core::conversion::translation_conversion",
"core::conversion::similarity_conversion",
"core::conversion::unit_quaternion_conversion",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis1",
"core::conversion::rotation_conversion",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis2",
"core::conversion::isometry_conversion",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis3",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis4",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis5",
"core::matrix::finite_dim_inner_space_tests::orthonormalize2",
"core::matrix::from_columns",
"core::matrix::from_columns_dynamic",
"core::matrix::from_diagonal",
"core::matrix::from_not_enough_columns",
"core::matrix::from_rows",
"core::matrix::from_rows_with_different_dimensions",
"core::matrix::from_too_many_rows",
"core::matrix::identity",
"core::matrix::finite_dim_inner_space_tests::orthonormalize1",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim1",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim2",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim4",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim3",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis6",
"core::matrix::iter",
"core::matrix::kronecker",
"core::matrix::linear_index",
"core::matrix::map",
"core::matrix::map_with_location",
"core::matrix::normalization_tests::normalized_vec_norm_is_one",
"core::matrix::normalization_tests::normalized_vec_norm_is_one_dyn",
"core::matrix::partial_clamp",
"core::matrix::partial_cmp",
"core::matrix::partial_eq_different_types",
"core::matrix::partial_eq_shape_mismatch",
"core::matrix::push",
"core::matrix::set_row_column",
"core::matrix::simple_add",
"core::matrix::simple_mul",
"core::matrix::simple_product",
"core::matrix::simple_scalar_conversion",
"core::matrix::simple_scalar_mul",
"core::matrix::simple_sum",
"core::matrix::simple_transpose",
"core::matrix::simple_transpose_mut",
"core::matrix::swizzle",
"core::matrix::to_homogeneous",
"core::matrix::trace",
"core::matrix::trace_panic",
"core::matrix::is_column_major",
"core::matrix::transposition_tests::check_transpose_components_dyn",
"core::matrix::transposition_tests::transpose_mut_transpose_mut_is_self",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim6",
"core::matrix::transposition_tests::transpose_transpose_is_id_dyn",
"core::matrix::transposition_tests::transpose_transpose_is_self",
"core::matrix::vector_index_mut",
"core::matrix::zip_map",
"core::matrix_slice::col_slice_mut",
"core::matrix_slice::column_out_of_bounds",
"core::matrix_slice::columns_out_of_bounds",
"core::matrix_slice::columns_range_pair",
"core::matrix_slice::columns_with_step_out_of_bounds",
"core::matrix_slice::nested_col_slices",
"core::matrix::transposition_tests::tr_mul_is_transpose_then_mul",
"core::matrix_slice::nested_slices",
"core::matrix_slice::nested_fixed_slices",
"core::matrix_slice::nested_row_slices",
"core::matrix_slice::new_slice",
"core::matrix_slice::new_slice_mut",
"core::matrix_slice::row_out_of_bounds",
"core::matrix_slice::row_slice_mut",
"core::matrix_slice::rows_out_of_bounds",
"core::matrix_slice::rows_range_pair",
"core::matrix_slice::rows_with_step_out_of_bounds",
"core::matrix_slice::slice_mut",
"core::matrix_slice::slice_out_of_bounds",
"core::matrix_slice::slice_with_steps_out_of_bounds",
"core::matrixcompare::assert_matrix_eq_dense_negative_comparison",
"core::matrixcompare::assert_matrix_eq_dense_positive_comparison",
"core::matrix::finite_dim_inner_space_tests::orthonormalize3",
"core::matrixcompare::matrixcompare_shape_agrees_with_matrix",
"core::mint::mint_matrix_conversion_2_2",
"core::mint::mint_matrix_conversion_3_3",
"core::mint::mint_matrix_conversion_2_3",
"core::mint::mint_matrix_conversion_4_4",
"core::mint::mint_matrix_conversion_3_4",
"core::mint::mint_vector_conversion_2",
"core::matrixcompare::fetch_single_is_equivalent_to_index_f64",
"core::mint::mint_vector_conversion_4",
"core::mint::mint_vector_conversion_3",
"core::serde::serde_flat",
"core::serde::serde_dmatrix",
"core::serde::serde_isometry2",
"core::serde::serde_isometry3",
"core::serde::serde_isometry_matrix2",
"core::serde::serde_isometry_matrix3",
"core::serde::serde_matrix3x4",
"core::serde::serde_point2",
"core::serde::serde_point3",
"core::serde::serde_quaternion",
"core::serde::serde_rotation2",
"core::mint::mint_quaternion_conversions",
"core::serde::serde_rotation3",
"core::serde::serde_similarity2",
"core::serde::serde_similarity3",
"core::serde::serde_similarity_matrix2",
"core::serde::serde_similarity_matrix3",
"core::serde::serde_translation2",
"core::serde::serde_translation3",
"core::matrix::finite_dim_inner_space_tests::orthonormalize4",
"geometry::isometry::append_rotation_wrt_point_to_id",
"geometry::isometry::composition2",
"geometry::isometry::inverse_is_parts_inversion",
"geometry::isometry::inverse_is_identity",
"geometry::isometry::observer_frame_3",
"geometry::isometry::composition3",
"geometry::point::point_clone",
"geometry::point::point_coordinates",
"geometry::point::point_ops",
"geometry::point::point_scale",
"geometry::isometry::look_at_rh_3",
"geometry::point::point_sub",
"geometry::point::to_homogeneous",
"geometry::point::point_vector_sum",
"geometry::projection::orthographic_inverse",
"geometry::projection::perspective_inverse",
"geometry::projection::perspective_matrix_point_transformation",
"geometry::isometry::rotation_wrt_point_invariance",
"geometry::projection::quickcheck_tests::orthographic_project_unproject",
"geometry::projection::quickcheck_tests::perspective_project_unproject",
"geometry::quaternion::from_euler_angles",
"geometry::quaternion::unit_quaternion_double_covering",
"geometry::quaternion::euler_angles",
"geometry::quaternion::unit_quaternion_inv",
"geometry::quaternion::unit_quaternion_rotation_conversion",
"geometry::isometry::multiply_equals_alga_transform",
"geometry::quaternion::unit_quaternion_mul_vector",
"geometry::isometry::all_op_exist",
"geometry::rotation::quaternion_euler_angles_issue_494",
"geometry::rotation::angle_2",
"geometry::rotation::quickcheck_tests::angle_is_commutative_3",
"geometry::rotation::quickcheck_tests::angle_is_commutative_2",
"geometry::rotation::angle_3",
"geometry::quaternion::unit_quaternion_transformation",
"geometry::rotation::quickcheck_tests::euler_angles_gimble_lock",
"geometry::rotation::quickcheck_tests::euler_angles",
"geometry::rotation::quickcheck_tests::new_rotation_2",
"geometry::rotation::quickcheck_tests::new_rotation_3",
"geometry::rotation::quickcheck_tests::powf_rotation_2",
"geometry::rotation::quickcheck_tests::powf_rotation_3",
"geometry::quaternion::all_op_exist",
"geometry::rotation::quickcheck_tests::rotation_between_3",
"geometry::rotation::quickcheck_tests::rotation_between_is_anticommutative_2",
"geometry::rotation::quickcheck_tests::rotation_between_2",
"geometry::rotation::quickcheck_tests::rotation_between_is_anticommutative_3",
"geometry::rotation::quickcheck_tests::rotation_between_is_identity",
"core::matrix::finite_dim_inner_space_tests::orthonormalize5",
"geometry::rotation::quickcheck_tests::from_euler_angles",
"geometry::rotation::quickcheck_tests::rotation_inv_3",
"geometry::rotation::quickcheck_tests::rotation_inv_2",
"geometry::similarity::inverse_is_parts_inversion",
"geometry::unit_complex::unit_complex_inv",
"geometry::unit_complex::unit_complex_mul_vector",
"geometry::unit_complex::unit_complex_rotation_conversion",
"core::blas::blas_quickcheck::gemv_tr",
"geometry::unit_complex::unit_complex_transformation",
"geometry::similarity::multiply_equals_alga_transform",
"linalg::bidiagonal::bidiagonal_identity",
"linalg::balancing::balancing_parlett_reinsch_static",
"geometry::similarity::inverse_is_identity",
"geometry::unit_complex::all_op_exist",
"linalg::balancing::balancing_parlett_reinsch",
"linalg::bidiagonal::complex::bidiagonal_static_3_5",
"linalg::bidiagonal::complex::bidiagonal_static_square_2x2",
"linalg::bidiagonal::complex::bidiagonal_static_5_3",
"linalg::bidiagonal::complex::bidiagonal",
"core::matrix::finite_dim_inner_space_tests::orthonormalize6",
"linalg::bidiagonal::complex::bidiagonal_static_square",
"linalg::bidiagonal::f64::bidiagonal_static_square",
"linalg::bidiagonal::f64::bidiagonal_static_square_2x2",
"linalg::bidiagonal::f64::bidiagonal",
"geometry::similarity::all_op_exist",
"linalg::bidiagonal::f64::bidiagonal_static_5_3",
"linalg::bidiagonal::f64::bidiagonal_static_3_5",
"geometry::similarity::composition",
"core::blas::blas_quickcheck::gemv_symm",
"linalg::cholesky::complex::cholesky_inverse_static",
"linalg::cholesky::complex::cholesky_static",
"linalg::cholesky::complex::cholesky_rank_one_update",
"linalg::cholesky::complex::cholesky_solve_static",
"linalg::cholesky::complex::cholesky_insert_column",
"core::blas::blas_quickcheck::quadform_tr",
"linalg::cholesky::f64::cholesky_insert_column",
"linalg::cholesky::f64::cholesky_rank_one_update",
"linalg::cholesky::complex::cholesky_remove_column",
"linalg::cholesky::f64::cholesky_remove_column",
"linalg::cholesky::f64::cholesky_inverse_static",
"core::blas::blas_quickcheck::ger_symm",
"linalg::convolution::convolve_full_check",
"linalg::convolution::convolve_same_check",
"linalg::cholesky::f64::cholesky_static",
"linalg::convolution::convolve_valid_check",
"linalg::cholesky::f64::cholesky_solve_static",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_static_square_2x2",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_static_square_3x3",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_static_square_4x4",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_static_square_2x2",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_static_square_3x3",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_singular",
"linalg::eigen::symmetric_eigen_singular_24x24",
"linalg::exp::tests::exp_complex",
"linalg::exp::tests::exp_dynamic",
"linalg::exp::tests::exp_static",
"linalg::full_piv_lu::full_piv_lu_simple",
"linalg::full_piv_lu::full_piv_lu_simple_with_pivot",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_static_square_4x4",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_inverse_static",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_static_3_5",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_solve_static",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_static_5_3",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_static_square",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_inverse_static",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_singular",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_inverse",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_static_3_5",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_solve_static",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_static_5_3",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_static_square",
"linalg::cholesky::f64::cholesky",
"linalg::hessenberg::complex::hessenberg_static",
"linalg::hessenberg::complex::hessenberg_static_mat2",
"linalg::hessenberg::f64::hessenberg_static",
"linalg::hessenberg::f64::hessenberg_static_mat2",
"linalg::hessenberg::hessenberg_simple",
"linalg::inverse::matrix1_try_inverse",
"linalg::inverse::matrix1_try_inverse_scaled_identity",
"linalg::inverse::matrix2_try_inverse",
"linalg::inverse::matrix2_try_inverse_scaled_identity",
"linalg::inverse::matrix3_try_inverse",
"linalg::inverse::matrix3_try_inverse_scaled_identity",
"linalg::inverse::matrix4_try_inverse_issue_214",
"linalg::inverse::matrix5_try_inverse",
"linalg::inverse::matrix5_try_inverse_scaled_identity",
"linalg::lu::lu_simple",
"linalg::lu::lu_simple_with_pivot",
"linalg::lu::quickcheck_tests::complex::lu",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_inverse",
"core::blas::blas_quickcheck::quadform",
"linalg::lu::quickcheck_tests::complex::lu_inverse_static",
"linalg::lu::quickcheck_tests::complex::lu_solve_static",
"linalg::lu::quickcheck_tests::complex::lu_static_3_5",
"linalg::lu::quickcheck_tests::complex::lu_static_5_3",
"linalg::lu::quickcheck_tests::complex::lu_static_square",
"linalg::lu::quickcheck_tests::f64::lu",
"linalg::lu::quickcheck_tests::complex::lu_inverse",
"linalg::lu::quickcheck_tests::f64::lu_inverse_static",
"linalg::lu::quickcheck_tests::f64::lu_inverse",
"linalg::lu::quickcheck_tests::f64::lu_solve_static",
"linalg::lu::quickcheck_tests::f64::lu_static_3_5",
"linalg::lu::quickcheck_tests::f64::lu_static_5_3",
"linalg::lu::quickcheck_tests::f64::lu_static_square",
"linalg::qr::complex::qr",
"linalg::cholesky::f64::cholesky_solve",
"linalg::qr::complex::qr_inverse_static",
"linalg::cholesky::f64::cholesky_inverse",
"linalg::qr::complex::qr_solve_static",
"linalg::qr::complex::qr_static_3_5",
"linalg::qr::complex::qr_static_5_3",
"linalg::qr::complex::qr_static_square",
"linalg::qr::f64::qr",
"linalg::qr::complex::qr_inverse",
"linalg::qr::f64::qr_inverse_static",
"linalg::qr::f64::qr_inverse",
"linalg::qr::f64::qr_solve_static",
"linalg::qr::f64::qr_static_3_5",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_solve",
"linalg::qr::f64::qr_static_5_3",
"linalg::qr::f64::qr_static_square",
"linalg::schur::quickcheck_tests::complex::schur_static_mat2",
"linalg::schur::quickcheck_tests::complex::schur_static_mat3",
"linalg::schur::quickcheck_tests::complex::schur_static_mat4",
"linalg::schur::quickcheck_tests::complex::schur",
"linalg::schur::quickcheck_tests::f64::schur_static_mat2",
"linalg::lu::quickcheck_tests::f64::lu_solve",
"linalg::schur::quickcheck_tests::f64::schur_static_mat3",
"linalg::schur::schur_simpl_mat3",
"linalg::schur::schur_singular",
"linalg::schur::quickcheck_tests::f64::schur_static_mat4",
"linalg::schur::schur_static_mat3_fail",
"linalg::schur::schur_static_mat4_fail",
"linalg::schur::schur_static_mat4_fail2",
"linalg::solve::complex::solve_upper_triangular",
"linalg::solve::complex::solve_lower_triangular",
"linalg::solve::complex::tr_solve_lower_triangular",
"linalg::solve::complex::tr_solve_upper_triangular",
"linalg::solve::f64::solve_lower_triangular",
"linalg::schur::quickcheck_tests::f64::schur",
"linalg::solve::f64::solve_upper_triangular",
"linalg::solve::f64::tr_solve_upper_triangular",
"linalg::solve::f64::tr_solve_lower_triangular",
"linalg::svd::quickcheck_tests::complex::svd",
"linalg::svd::quickcheck_tests::complex::svd_pseudo_inverse",
"linalg::svd::quickcheck_tests::complex::svd_static_2_5",
"linalg::svd::quickcheck_tests::complex::svd_static_5_2",
"linalg::hessenberg::f64::hessenberg",
"linalg::svd::quickcheck_tests::complex::svd_static_3_5",
"linalg::svd::quickcheck_tests::complex::svd_static_square_2x2",
"linalg::svd::quickcheck_tests::complex::svd_static_5_3",
"linalg::svd::quickcheck_tests::complex::svd_static_square",
"linalg::svd::quickcheck_tests::f64::svd",
"linalg::svd::quickcheck_tests::f64::svd_static_2_5",
"linalg::svd::quickcheck_tests::f64::svd_pseudo_inverse",
"linalg::svd::quickcheck_tests::f64::svd_static_5_2",
"linalg::svd::quickcheck_tests::f64::svd_static_5_3",
"linalg::svd::quickcheck_tests::f64::svd_static_3_5",
"linalg::svd::quickcheck_tests::f64::svd_static_square_2x2",
"linalg::svd::svd_err",
"linalg::svd::svd_fail",
"linalg::svd::quickcheck_tests::f64::svd_static_square",
"linalg::svd::svd_identity",
"linalg::svd::svd_singular",
"linalg::svd::svd_singular_vertical",
"linalg::svd::svd_singular_horizontal",
"linalg::svd::svd_with_delimited_subproblem",
"linalg::svd::svd_zeros",
"linalg::svd::quickcheck_tests::complex::svd_solve",
"linalg::tridiagonal::complex::symm_tridiagonal_static_square",
"linalg::tridiagonal::complex::symm_tridiagonal_singular",
"linalg::tridiagonal::complex::symm_tridiagonal_static_square_2x2",
"linalg::tridiagonal::f64::symm_tridiagonal_singular",
"linalg::svd::quickcheck_tests::f64::svd_solve",
"linalg::tridiagonal::f64::symm_tridiagonal_static_square",
"linalg::tridiagonal::f64::symm_tridiagonal_static_square_2x2",
"linalg::cholesky::complex::cholesky",
"linalg::qr::f64::qr_solve",
"linalg::lu::quickcheck_tests::complex::lu_solve",
"linalg::cholesky::complex::cholesky_solve",
"linalg::tridiagonal::f64::symm_tridiagonal",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_solve",
"linalg::qr::complex::qr_solve",
"linalg::cholesky::complex::cholesky_inverse",
"linalg::hessenberg::complex::hessenberg",
"linalg::tridiagonal::complex::symm_tridiagonal",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::tr_dot (line 237)",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::dotc (line 213)",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::dot (line 182)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::gerc (line 790)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::ger (line 758)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::gemm (line 824)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::syger (line 1176)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::hegerc (line 1211)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::gemm_ad (line 1040)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::ger_symm (line 1139)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::gemm_tr (line 978)",
"src/base/blas.rs - base::blas::SquareMatrix<N, D1, S>::quadform (line 1395)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::axpy (line 360)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::axcpy (line 326)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::gemv (line 385)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R, C, S>::abs (line 24)",
"src/base/blas.rs - base::blas::SquareMatrix<N, D1, S>::quadform_tr (line 1303)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::hegemv (line 569)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::cdpy (line 151)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::gemv_tr (line 654)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::sygemv (line 526)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::gemv_ad (line 689)",
"src/base/blas.rs - base::blas::SquareMatrix<N, D1, S>::quadform_tr_with_workspace (line 1249)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_div (line 152)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::cmpy (line 151)",
"src/base/blas.rs - base::blas::SquareMatrix<N, D1, S>::quadform_with_workspace (line 1339)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_div_assign (line 151)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_div_mut (line 151)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_mul (line 152)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_mul_assign (line 151)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_mul_mut (line 151)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_diagonal_element (line 624)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_element (line 623)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_partial_diagonal (line 626)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_column_slice (line 748)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::identity (line 625)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::zeros (line 623)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_fn (line 624)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_diagonal_element (line 635)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::repeat (line 625)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_element (line 634)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_vec (line 749)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_iterator (line 625)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_row_slice (line 751)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_column_slice (line 753)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_partial_diagonal (line 637)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::identity (line 636)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_fn (line 635)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::repeat (line 636)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::zeros (line 634)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_iterator (line 636)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_diagonal_element (line 602)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_vec (line 754)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_row_slice (line 756)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_element (line 601)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_columns (line 228)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_column_slice (line 738)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_partial_diagonal (line 604)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_fn (line 602)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::identity (line 603)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::repeat (line 603)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::zeros (line 601)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_iterator (line 603)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_rows (line 186)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_vec_generic (line 290)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_diagonal_element (line 613)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_vec (line 739)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_row_slice (line 741)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_element (line 612)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_column_slice (line 743)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_fn (line 613)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_partial_diagonal (line 615)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::identity (line 614)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::repeat (line 614)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::zeros (line 612)",
"src/base/construction.rs - base::construction::MatrixN<N, D>::from_diagonal (line 317)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_iterator (line 614)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_vec (line 744)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_row_slice (line 746)",
"src/base/edition.rs - base::edition::Matrix<N, Dynamic, U1, S>::extend (line 1086)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 1039)",
"src/base/edition.rs - base::edition::Matrix<N, R, C, S>::reshape_generic (line 831)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 1059)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 1111)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 1133)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 396)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 1145)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 408)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 421)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 431)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 443)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 454)",
"src/base/interpolation.rs - base::interpolation::Unit<Vector<N, D, S>>::slerp (line 65)",
"src/base/matrix.rs - base::matrix::Matrix::data (line 160)",
"src/base/interpolation.rs - base::interpolation::Vector<N, D, S>::lerp (line 17)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 470)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 481)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::ncols (line 332)",
"src/base/interpolation.rs - base::interpolation::Vector<N, D, S>::slerp (line 38)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::nrows (line 319)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::as_ptr (line 390)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::shape (line 305)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::column_iter_mut (line 951)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::strides (line 345)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::iter (line 868)",
"src/base/min_max.rs - base::min_max::Matrix<N, R, C, S>::amax (line 10)",
"src/base/min_max.rs - base::min_max::Matrix<N, R, C, S>::amin (line 67)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::column_iter (line 903)",
"src/base/min_max.rs - base::min_max::Matrix<N, R, C, S>::camax (line 28)",
"src/base/min_max.rs - base::min_max::Matrix<N, R, C, S>::camin (line 85)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::row_iter_mut (line 928)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::row_iter (line 888)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::vector_to_matrix_index (line 361)",
"src/base/min_max.rs - base::min_max::Matrix<N, R, C, S>::icamax_full (line 129)",
"src/base/min_max.rs - base::min_max::Vector<N, D, S>::icamax (line 203)",
"src/base/min_max.rs - base::min_max::Matrix<N, R, C, S>::iamax_full (line 168)",
"src/base/min_max.rs - base::min_max::Matrix<N, R, C, S>::max (line 48)",
"src/base/min_max.rs - base::min_max::Vector<N, D, S>::argmin (line 316)",
"src/base/min_max.rs - base::min_max::Matrix<N, R, C, S>::min (line 108)",
"src/base/min_max.rs - base::min_max::Vector<N, D, S>::imax (line 268)",
"src/base/min_max.rs - base::min_max::Vector<N, D, S>::iamax (line 285)",
"src/base/min_max.rs - base::min_max::Vector<N, D, S>::iamin (line 364)",
"src/base/norm.rs - base::norm::Matrix<N, R, C, S>::apply_metric_distance (line 225)",
"src/base/min_max.rs - base::min_max::Vector<N, D, S>::argmax (line 237)",
"src/base/norm.rs - base::norm::Matrix<N, R, C, S>::apply_norm (line 205)",
"src/base/min_max.rs - base::min_max::Vector<N, D, S>::imin (line 347)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 403)",
"src/base/properties.rs - base::properties::Matrix<N, R, C, S>::is_empty (line 32)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 443)",
"src/base/properties.rs - base::properties::Matrix<N, R, C, S>::len (line 17)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::mean (line 299)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 393)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_mean (line 324)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::column_mean (line 364)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_mean_tr (line 344)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::column_variance (line 259)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::sum (line 88)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 433)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_variance (line 219)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_variance_tr (line 239)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::column_sum (line 157)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::variance (line 189)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_rotation_mut (line 236)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_rotation_wrt_point_mut (line 258)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_rotation_wrt_center_mut (line 281)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_sum (line 109)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_translation_mut (line 217)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse_mut (line 196)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_sum_tr (line 133)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse (line 175)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::to_homogeneous (line 434)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::from_parts (line 146)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::to_matrix (line 465)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse_transform_vector (line 379)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse_transform_point (line 355)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse_transform_unit_vector (line 402)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::transform_point (line 310)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::transform_vector (line 333)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry2<N>::new (line 165)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix2<N>::new (line 127)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<N>::face_towards (line 414)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, D, R>::identity (line 32)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<N>::look_at_lh (line 415)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, D, R>::rotation_wrt_point (line 53)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<N>::look_at_rh (line 415)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<N>::face_towards (line 421)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<N>::new (line 390)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<N>::look_at_lh (line 422)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<N>::look_at_rh (line 422)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::as_matrix (line 229)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::bottom (line 333)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::Isometry3<N>::lerp_slerp (line 13)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::Isometry3<N>::try_lerp_slerp (line 46)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<N>::new (line 397)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::IsometryMatrix3<N>::try_lerp_slerp (line 114)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::from_matrix_unchecked (line 129)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::as_projective (line 248)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::into_inner (line 274)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::IsometryMatrix3<N>::lerp_slerp (line 81)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::inverse (line 174)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::left (line 301)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_bottom (line 537)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::right (line 317)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::project_vector (line 472)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_left (line 499)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_bottom_and_top (line 638)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::project_point (line 399)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_left_and_right (line 613)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_top (line 556)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_right (line 518)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::new (line 74)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_zfar (line 594)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::to_homogeneous (line 210)",
"src/geometry/point.rs - geometry::point::Point<N, D>::is_empty (line 218)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_znear_and_zfar (line 663)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::to_projective (line 261)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_znear (line 575)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::zfar (line 381)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::top (line 349)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::znear (line 365)",
"src/geometry/point.rs - geometry::point::Point<N, D>::apply (line 146)",
"src/geometry/point.rs - geometry::point::Point<N, D>::iter (line 239)",
"src/geometry/point_construction.rs - geometry::point_construction::Point2<N>::new (line 201)",
"src/geometry/point.rs - geometry::point::Point<N, D>::len (line 201)",
"src/geometry/point_construction.rs - geometry::point_construction::Point1<N>::new (line 174)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::unproject_point (line 434)",
"src/geometry/point_construction.rs - geometry::point_construction::Point3<N>::new (line 201)",
"src/geometry/point.rs - geometry::point::Point<N, D>::to_homogeneous (line 168)",
"src/geometry/point_construction.rs - geometry::point_construction::Point4<N>::new (line 201)",
"src/geometry/point.rs - geometry::point::Point<N, D>::iter_mut (line 262)",
"src/geometry/point_construction.rs - geometry::point_construction::Point5<N>::new (line 201)",
"src/geometry/point_construction.rs - geometry::point_construction::Point6<N>::new (line 201)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::as_vector (line 221)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, D>::from_slice (line 57)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, D>::origin (line 34)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, D>::from_homogeneous (line 79)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::as_vector_mut (line 549)",
"src/geometry/point.rs - geometry::point::Point<N, D>::map (line 126)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::acos (line 721)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::conjugate (line 161)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::acosh (line 870)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::conjugate_mut (line 584)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::asinh (line 837)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::asin (line 759)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::atan (line 798)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::atanh (line 906)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::dot (line 296)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::cosh (line 854)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::exp (line 493)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::cos (line 703)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::lerp (line 178)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::magnitude_squared (line 283)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::inner (line 363)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::ln (line 475)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::exp_eps (line 508)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::magnitude (line 253)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::norm_squared (line 267)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::normalize_mut (line 623)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::norm (line 236)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::outer (line 381)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::normalize (line 139)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::scalar (line 208)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::polar_decomposition (line 446)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::powf (line 535)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::right_div (line 683)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::reject (line 423)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::project (line 401)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::tan (line 779)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::sin (line 741)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::sinh (line 821)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::vector_mut (line 563)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::vector (line 193)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::tanh (line 887)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::try_inverse_mut (line 600)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::try_inverse (line 317)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::angle (line 1014)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::angle_to (line 1077)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::conjugate (line 1044)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::axis_angle (line 1279)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::axis (line 1227)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse (line 1060)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::euler_angles (line 1424)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse_mut (line 1210)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::lerp (line 1113)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse_transform_point (line 1508)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse_transform_vector (line 1530)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::nlerp (line 1129)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::quaternion (line 1031)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse_transform_unit_vector (line 1550)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::ln (line 1313)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::powf (line 1338)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::slerp (line 1150)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::rotation_to (line 1095)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::to_homogeneous (line 1445)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::scaled_axis (line 1255)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<N>::from_parts (line 63)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<N>::identity (line 89)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::to_rotation_matrix (line 1364)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::transform_vector (line 1488)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<N>::new (line 38)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::transform_point (line 1468)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::face_towards (line 525)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_euler_angles (line 244)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_axis_angle (line 201)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_rotation_matrix (line 272)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_scaled_axis (line 684)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::look_at_lh (line 597)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_scaled_axis_eps (line 714)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::look_at_rh (line 566)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::new (line 621)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::identity (line 180)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::rotation_between (line 381)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::new_eps (line 652)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::rotation_between_axis (line 440)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::from_matrix_unchecked (line 153)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::scaled_rotation_between_axis (line 466)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::into_inner (line 229)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::scaled_rotation_between (line 404)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse_transform_unit_vector (line 493)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse (line 332)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse_transform_point (line 455)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse_transform_vector (line 474)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse_mut (line 383)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::mean_of (line 748)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::matrix (line 189)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::to_homogeneous (line 264)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transpose (line 308)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transform_point (line 417)",
"src/geometry/rotation_construction.rs - geometry::rotation_construction::Rotation<N, D>::identity (line 20)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transform_vector (line 436)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transpose_mut (line 356)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::angle (line 212)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::powf (line 194)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::angle_to (line 226)",
"src/geometry/rotation_interpolation.rs - geometry::rotation_interpolation::Rotation3<N>::slerp (line 39)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::new (line 30)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::rotation_to (line 162)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::rotation_between (line 110)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::angle (line 731)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::euler_angles (line 861)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::scaled_rotation_between (line 133)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::axis_angle (line 801)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::from_euler_angles (line 394)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::axis (line 748)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::face_towards (line 438)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::angle_to (line 830)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::look_at_rh (line 485)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::look_at_lh (line 516)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::rotation_to (line 616)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::powf (line 633)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::from_scaled_axis (line 316)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::scaled_axis (line 777)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::new (line 289)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::rotation_between (line 546)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::scaled_rotation_between (line 569)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::inverse_transform_vector (line 314)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::inverse_transform_point (line 294)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, D, R>::rotation_wrt_point (line 90)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U2, UnitComplex<N>>::new (line 168)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::transform_vector (line 274)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, D, R>::identity (line 32)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::transform_point (line 253)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U2, Rotation2<N>>::new (line 142)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::look_at_rh (line 365)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::face_towards (line 366)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::look_at_lh (line 365)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::into_inner (line 256)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::face_towards (line 367)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::look_at_lh (line 366)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::matrix (line 281)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::look_at_rh (line 366)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::new (line 357)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::new (line 358)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::matrix_mut_unchecked (line 301)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::inverse (line 396)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::to_homogeneous (line 345)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::inverse_transform_point (line 234)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::inverse_mut (line 451)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::to_homogeneous (line 151)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::inverse (line 128)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::inverse_mut (line 183)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::try_inverse (line 363)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U3>::new (line 99)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::transform_point (line 216)",
"src/geometry/transform_construction.rs - geometry::transform_construction::Transform<N, D, C>::identity (line 19)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, D>::identity (line 25)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U1>::new (line 99)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U2>::new (line 99)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::try_inverse_mut (line 422)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::angle (line 70)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U4>::new (line 99)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U5>::new (line 99)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U6>::new (line 99)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::angle_to (line 141)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::conjugate (line 163)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::conjugate_mut (line 196)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse (line 179)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::sin_angle (line 83)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse_mut (line 215)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse_transform_point (line 315)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse_transform_vector (line 333)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse_transform_unit_vector (line 349)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::to_rotation_matrix (line 238)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::to_homogeneous (line 256)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::transform_point (line 281)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::transform_vector (line 299)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::from_cos_sin_unchecked (line 88)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::from_angle (line 67)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::from_rotation_matrix (line 155)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::identity (line 24)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::powf (line 225)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::new (line 47)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::rotation_to (line 204)",
"src/lib.rs - (line 26)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::rotation_between_axis (line 306)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::scaled_rotation_between (line 270)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::rotation_between (line 247)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::scaled_rotation_between_axis (line 331)"
] |
[
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::Isometry2<N>::lerp_slerp (line 149)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::IsometryMatrix2<N>::lerp_slerp (line 185)",
"src/geometry/rotation_interpolation.rs - geometry::rotation_interpolation::Rotation2<N>::slerp (line 9)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::from_axis_angle (line 339)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::cos_angle (line 97)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::slerp (line 372)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::complex (line 122)"
] |
[] |
dimforge/nalgebra
| 404
|
dimforge__nalgebra-404
|
[
"401"
] |
962e89417ca2eab9254fa4fda5a27fc925cf0965
|
diff --git a/src/base/matrix.rs b/src/base/matrix.rs
--- a/src/base/matrix.rs
+++ b/src/base/matrix.rs
@@ -909,7 +909,7 @@ where
}
}
- None
+ first_ord
}
#[inline]
|
diff --git a/tests/core/matrix.rs b/tests/core/matrix.rs
--- a/tests/core/matrix.rs
+++ b/tests/core/matrix.rs
@@ -706,6 +706,16 @@ fn set_row_column() {
assert_eq!(expected2, computed);
}
+#[test]
+fn partial_clamp() {
+ // NOTE: from #401.
+ let n = Vector2::new(1.5, 0.0);
+ let min = Vector2::new(-75.0, -0.0);
+ let max = Vector2::new(75.0, 0.0);
+ let inter = na::partial_clamp(&n, &min, &max);
+ assert_eq!(*inter.unwrap(), n);
+}
+
#[cfg(feature = "arbitrary")]
mod transposition_tests {
use super::*;
|
partial_clamp unintuitive/broken
This is using nalgebra version `0.16.3`.
The following code:
```rust
println!("acc: {:?}", acc);
println!("movement.vel: {:?}", movement.vel);
println!("&(movement.vel + acc): {:?}", &(movement.vel + acc));
println!("&movement.max_vel: {:?}", &movement.max_vel);
println!("&-movement.max_vel: {:?}", &-movement.max_vel);
let n = &(movement.vel + acc);
let min = &-movement.max_vel;
let max = &movement.max_vel;
let inter = na::partial_clamp(n, min, max);
println!("inter: {:?}", inter);
```
Produces the following output:
```
acc: Matrix { data: [1.5, 0.0] }
movement.vel: Matrix { data: [0.0, 0.0] }
&(movement.vel + acc): Matrix { data: [1.5, 0.0] }
&movement.max_vel: Matrix { data: [75.0, 0.0] }
&-movement.max_vel: Matrix { data: [-75.0, -0.0] }
inter: None
```
So somehow `[1.5, 0.0]` can not be clamped between `[-75.0, -0.0]` and `[75.0, 0.0]`.
This used to work in a previous version of nalgebra (`0.8.2`) (I am updating some old code), so I suppose this is either intended (and just unintuitive), or broke somewhere along the way.
Thanks!
**Edit:**
Tackling this a bit further, the following worked just fine:
```rust
let inter_x = na::partial_clamp(&n.x, &min.x, &max.x);
let inter_y = na::partial_clamp(&n.y, &min.y, &max.y);
println!("inter_x: {:?}", inter_x);
println!("inter_y: {:?}", inter_y);
```
prints:
```
inter_x: Some(1.5)
inter_y: Some(0.0)
```
Maybe that helps (or maybe I'm just missing something obvious here).
|
2018-09-24T11:59:56Z
|
0.16
|
2018-09-24T18:58:13Z
|
d702bf0382896ac571190bcfc6e7ae13c657809b
|
[
"core::matrix::partial_clamp"
] |
[
"linalg::symmetric_eigen::test::wilkinson_shift_zero",
"geometry::transform::tests::checks_homogeneous_invariants_of_square_identity_matrix",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_det",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diag_diff_and_zero_off_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_off_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_trace",
"linalg::symmetric_eigen::test::wilkinson_shift_random",
"geometry::quaternion_construction::tests::random_unit_quats_are_unit",
"core::abomonation::abomonate_dmatrix",
"core::abomonation::abomonate_isometry3",
"core::abomonation::abomonate_point3",
"core::abomonation::abomonate_similarity3",
"core::abomonation::abomonate_quaternion",
"core::abomonation::abomonate_matrix3x4",
"core::abomonation::abomonate_translation3",
"core::conversion::array_matrix_conversion_2_2",
"core::abomonation::abomonate_rotation3",
"core::abomonation::abomonate_isometry_matrix3",
"core::conversion::array_matrix_conversion_2_3",
"core::conversion::array_matrix_conversion_2_5",
"core::abomonation::abomonate_similarity_matrix3",
"core::conversion::array_matrix_conversion_2_4",
"core::conversion::array_matrix_conversion_2_6",
"core::conversion::array_matrix_conversion_3_2",
"core::conversion::array_matrix_conversion_3_5",
"core::conversion::array_matrix_conversion_3_6",
"core::conversion::array_matrix_conversion_4_2",
"core::conversion::array_matrix_conversion_4_3",
"core::conversion::array_matrix_conversion_4_6",
"core::conversion::array_matrix_conversion_5_2",
"core::conversion::array_matrix_conversion_5_3",
"core::conversion::array_matrix_conversion_5_4",
"core::conversion::array_matrix_conversion_5_5",
"core::conversion::array_matrix_conversion_4_4",
"core::conversion::array_matrix_conversion_5_6",
"core::conversion::array_matrix_conversion_3_4",
"core::conversion::array_matrix_conversion_3_3",
"core::conversion::array_matrix_conversion_6_2",
"core::conversion::array_matrix_conversion_6_3",
"core::conversion::array_matrix_conversion_6_4",
"core::conversion::array_matrix_conversion_6_5",
"core::conversion::array_matrix_conversion_4_5",
"core::conversion::array_row_vector_conversion_1",
"core::conversion::array_matrix_conversion_6_6",
"core::conversion::array_row_vector_conversion_2",
"core::conversion::array_row_vector_conversion_3",
"core::conversion::array_row_vector_conversion_4",
"core::conversion::array_row_vector_conversion_5",
"core::conversion::array_row_vector_conversion_6",
"core::conversion::array_vector_conversion_1",
"core::conversion::array_vector_conversion_2",
"core::conversion::array_vector_conversion_3",
"core::conversion::array_vector_conversion_4",
"core::conversion::array_vector_conversion_5",
"core::conversion::array_vector_conversion_6",
"core::edition::insert_columns_to_empty_matrix",
"core::edition::insert_columns",
"core::edition::insert_rows_to_empty_matrix",
"core::edition::insert_rows",
"core::edition::remove_columns",
"core::edition::remove_rows",
"core::edition::resize",
"core::edition::swap_columns",
"core::edition::resize_empty_matrix",
"core::edition::swap_rows",
"core::edition::upper_lower_triangular",
"core::matrix::apply",
"core::matrix::coordinates",
"core::matrix::components_mut",
"core::matrix::copy_from_slice",
"core::matrix::copy_from_slice_too_small",
"core::matrix::copy_from_slice_too_large",
"core::matrix::debug_output_corresponds_to_data_container",
"core::matrix::cross_product_vector_and_row_vector",
"core::conversion::translation_conversion",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis2",
"core::conversion::similarity_conversion",
"core::conversion::rotation_conversion",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis1",
"core::conversion::isometry_conversion",
"core::conversion::unit_quaternion_conversion",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis3",
"core::matrix::finite_dim_inner_space_tests::orthonormalize1",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis4",
"core::matrix::finite_dim_inner_space_tests::orthonormalize2",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis6",
"core::matrix::from_columns_dynamic",
"core::matrix::from_diagonal",
"core::matrix::from_not_enough_columns",
"core::matrix::from_rows",
"core::matrix::from_rows_with_different_dimensions",
"core::matrix::from_too_many_rows",
"core::matrix::from_columns",
"core::matrix::identity",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim1",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim2",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim3",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis5",
"core::matrix::is_column_major",
"core::matrix::iter",
"core::matrix::kronecker",
"core::matrix::finite_dim_inner_space_tests::orthonormalize3",
"core::matrix::linear_index",
"core::matrix::map",
"core::matrix::normalization_tests::normalized_vec_norm_is_one",
"core::matrix::set_row_column",
"core::matrix::simple_add",
"core::matrix::simple_mul",
"core::matrix::simple_product",
"core::matrix::simple_scalar_conversion",
"core::matrix::simple_scalar_mul",
"core::matrix::simple_sum",
"core::matrix::simple_transpose",
"core::matrix::simple_transpose_mut",
"core::matrix::to_homogeneous",
"core::matrix::trace",
"core::matrix::trace_panic",
"core::matrix::transposition_tests::check_transpose_components_dyn",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim4",
"core::matrix::normalization_tests::normalized_vec_norm_is_one_dyn",
"core::matrix::transposition_tests::transpose_mut_transpose_mut_is_self",
"core::matrix::transposition_tests::transpose_transpose_is_self",
"core::matrix::vector_index_mut",
"core::matrix::zip_map",
"core::matrix_slice::col_slice_mut",
"core::matrix_slice::column_out_of_bounds",
"core::matrix_slice::columns_out_of_bounds",
"core::matrix_slice::columns_range_pair",
"core::matrix_slice::columns_with_step_out_of_bounds",
"core::matrix_slice::nested_col_slices",
"core::matrix::transposition_tests::tr_mul_is_transpose_then_mul",
"core::matrix_slice::nested_fixed_slices",
"core::matrix_slice::nested_row_slices",
"core::matrix_slice::nested_slices",
"core::matrix_slice::new_slice",
"core::matrix_slice::new_slice_mut",
"core::matrix_slice::row_out_of_bounds",
"core::matrix_slice::row_slice_mut",
"core::matrix::transposition_tests::transpose_transpose_is_id_dyn",
"core::matrix_slice::rows_with_step_out_of_bounds",
"core::matrix_slice::rows_range_pair",
"core::matrix_slice::slice_mut",
"core::matrix_slice::slice_out_of_bounds",
"core::matrix_slice::slice_with_steps_out_of_bounds",
"core::mint::mint_matrix_conversion_2_2",
"core::mint::mint_matrix_conversion_3_3",
"core::mint::mint_matrix_conversion_4_4",
"core::mint::mint_quaternion_conversions",
"core::mint::mint_vector_conversion_2",
"core::mint::mint_vector_conversion_3",
"core::mint::mint_vector_conversion_4",
"core::serde::serde_flat",
"core::serde::serde_dmatrix",
"core::serde::serde_isometry_matrix3",
"core::serde::serde_matrix3x4",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim6",
"core::serde::serde_point3",
"core::matrix_slice::rows_out_of_bounds",
"core::serde::serde_quaternion",
"core::serde::serde_rotation3",
"core::serde::serde_similarity3",
"core::serde::serde_translation3",
"core::serde::serde_similarity_matrix3",
"core::serde::serde_isometry3",
"geometry::isometry::append_rotation_wrt_point_to_id",
"core::matrix::finite_dim_inner_space_tests::orthonormalize4",
"geometry::isometry::composition2",
"geometry::isometry::inverse_is_parts_inversion",
"geometry::isometry::look_at_rh_3",
"geometry::isometry::inverse_is_identity",
"geometry::isometry::multiply_equals_alga_transform",
"geometry::isometry::rotation_wrt_point_invariance",
"geometry::point::point_coordinates",
"geometry::point::point_scale",
"geometry::point::point_ops",
"geometry::point::point_vector_sum",
"geometry::point::to_homogeneous",
"geometry::projection::orthographic_inverse",
"geometry::projection::perspective_inverse",
"geometry::point::point_sub",
"geometry::isometry::observer_frame_3",
"geometry::projection::quickcheck_tests::perspective_project_unproject",
"geometry::projection::quickcheck_tests::orthographic_project_unproject",
"geometry::isometry::composition3",
"geometry::quaternion::from_euler_angles",
"geometry::quaternion::unit_quaternion_inv",
"geometry::quaternion::to_euler_angles",
"geometry::quaternion::unit_quaternion_double_covering",
"geometry::quaternion::unit_quaternion_rotation_conversion",
"geometry::rotation::angle_2",
"geometry::rotation::angle_3",
"geometry::rotation::quickcheck_tests::angle_is_commutative_2",
"geometry::quaternion::unit_quaternion_mul_vector",
"geometry::rotation::quickcheck_tests::angle_is_commutative_3",
"geometry::rotation::quickcheck_tests::new_rotation_2",
"geometry::rotation::quickcheck_tests::from_euler_angles",
"geometry::rotation::quickcheck_tests::new_rotation_3",
"geometry::rotation::quickcheck_tests::powf_rotation_2",
"geometry::quaternion::unit_quaternion_transformation",
"geometry::rotation::quickcheck_tests::powf_rotation_3",
"geometry::rotation::quickcheck_tests::rotation_between_2",
"geometry::rotation::quickcheck_tests::rotation_between_3",
"geometry::rotation::quickcheck_tests::rotation_between_is_anticommutative_2",
"geometry::rotation::quickcheck_tests::rotation_between_is_anticommutative_3",
"geometry::rotation::quickcheck_tests::rotation_between_is_identity",
"geometry::rotation::quickcheck_tests::rotation_inv_2",
"geometry::rotation::quickcheck_tests::to_euler_angles_gimble_lock",
"geometry::rotation::quickcheck_tests::rotation_inv_3",
"geometry::rotation::quickcheck_tests::to_euler_angles",
"core::matrix::finite_dim_inner_space_tests::orthonormalize5",
"geometry::isometry::all_op_exist",
"geometry::similarity::inverse_is_parts_inversion",
"geometry::unit_complex::all_op_exist",
"geometry::unit_complex::unit_complex_inv",
"geometry::unit_complex::unit_complex_mul_vector",
"geometry::similarity::inverse_is_identity",
"geometry::unit_complex::unit_complex_rotation_conversion",
"geometry::similarity::multiply_equals_alga_transform",
"geometry::quaternion::all_op_exist",
"geometry::unit_complex::unit_complex_transformation",
"linalg::balancing::balancing_parlett_reinsch_static",
"linalg::balancing::balancing_parlett_reinsch",
"core::matrix::finite_dim_inner_space_tests::orthonormalize6",
"core::blas::gemv_tr",
"linalg::bidiagonal::bidiagonal_static_5_3",
"linalg::bidiagonal::bidiagonal_static_3_5",
"linalg::bidiagonal::bidiagonal_static_square_2x2",
"linalg::bidiagonal::bidiagonal",
"linalg::cholesky::cholesky_inverse_static",
"linalg::cholesky::cholesky_solve_static",
"linalg::bidiagonal::bidiagonal_static_square",
"linalg::cholesky::cholesky_static",
"linalg::eigen::quickcheck_tests::symmetric_eigen_static_square_2x2",
"geometry::similarity::all_op_exist",
"geometry::similarity::composition",
"linalg::eigen::quickcheck_tests::symmetric_eigen_static_square_3x3",
"linalg::full_piv_lu::full_piv_lu_simple",
"linalg::full_piv_lu::full_piv_lu_simple_with_pivot",
"linalg::eigen::symmetric_eigen_singular_24x24",
"linalg::full_piv_lu::quickcheck_tests::full_piv_lu",
"linalg::full_piv_lu::quickcheck_tests::full_piv_lu_inverse_static",
"core::blas::quadform_tr",
"linalg::eigen::quickcheck_tests::symmetric_eigen_static_square_4x4",
"linalg::full_piv_lu::quickcheck_tests::full_piv_lu_static_3_5",
"linalg::full_piv_lu::quickcheck_tests::full_piv_lu_solve_static",
"linalg::full_piv_lu::quickcheck_tests::full_piv_lu_static_5_3",
"linalg::full_piv_lu::quickcheck_tests::full_piv_lu_static_square",
"linalg::hessenberg::hessenberg_simple",
"linalg::hessenberg::hessenberg_static",
"linalg::hessenberg::hessenberg_static_mat2",
"linalg::inverse::matrix1_try_inverse",
"linalg::inverse::matrix1_try_inverse_scaled_identity",
"linalg::inverse::matrix2_try_inverse",
"linalg::inverse::matrix2_try_inverse_scaled_identity",
"linalg::inverse::matrix3_try_inverse",
"linalg::inverse::matrix3_try_inverse_scaled_identity",
"linalg::inverse::matrix4_try_inverse_issue_214",
"linalg::inverse::matrix5_try_inverse",
"linalg::inverse::matrix5_try_inverse_scaled_identity",
"linalg::lu::lu_simple",
"linalg::lu::lu_simple_with_pivot",
"linalg::lu::quickcheck_tests::lu",
"core::blas::ger_symm",
"linalg::lu::quickcheck_tests::lu_inverse_static",
"linalg::full_piv_lu::quickcheck_tests::full_piv_lu_inverse",
"linalg::eigen::quickcheck_tests::symmetric_eigen",
"linalg::lu::quickcheck_tests::lu_static_3_5",
"core::blas::gemv_symm",
"linalg::eigen::quickcheck_tests::symmetric_eigen_singular",
"linalg::lu::quickcheck_tests::lu_static_5_3",
"linalg::lu::quickcheck_tests::lu_static_square",
"linalg::lu::quickcheck_tests::lu_solve_static",
"linalg::qr::qr",
"linalg::qr::qr_inverse_static",
"linalg::qr::qr_solve_static",
"linalg::lu::quickcheck_tests::lu_inverse",
"linalg::qr::qr_static_3_5",
"linalg::qr::qr_static_5_3",
"linalg::real_schur::quickcheck_tests::schur_static_mat2",
"linalg::real_schur::quickcheck_tests::schur_static_mat3",
"linalg::qr::qr_static_square",
"linalg::real_schur::schur_simpl_mat3",
"linalg::real_schur::schur_singular",
"linalg::real_schur::schur_static_mat3_fail",
"linalg::real_schur::schur_static_mat4_fail",
"linalg::real_schur::schur_static_mat4_fail2",
"linalg::cholesky::cholesky",
"linalg::real_schur::quickcheck_tests::schur_static_mat4",
"linalg::solve::solve_lower_triangular",
"linalg::qr::qr_inverse",
"linalg::solve::solve_upper_triangular",
"linalg::solve::tr_solve_lower_triangular",
"linalg::solve::tr_solve_upper_triangular",
"linalg::svd::quickcheck_tests::svd_pseudo_inverse",
"linalg::svd::quickcheck_tests::svd",
"linalg::svd::quickcheck_tests::svd_static_2_5",
"linalg::svd::quickcheck_tests::svd_static_5_2",
"linalg::svd::quickcheck_tests::svd_static_3_5",
"linalg::svd::quickcheck_tests::svd_static_square_2x2",
"linalg::svd::svd_fail",
"linalg::svd::svd_identity",
"linalg::svd::quickcheck_tests::svd_static_5_3",
"linalg::svd::svd_singular_horizontal",
"linalg::svd::svd_singular",
"linalg::svd::svd_with_delimited_subproblem",
"linalg::svd::svd_zeros",
"linalg::svd::quickcheck_tests::svd_static_square",
"linalg::svd::svd_singular_vertical",
"linalg::tridiagonal::symm_tridiagonal_static_square_2x2",
"linalg::tridiagonal::symm_tridiagonal_static_square",
"linalg::real_schur::quickcheck_tests::schur",
"linalg::svd::quickcheck_tests::svd_solve",
"linalg::cholesky::cholesky_solve",
"linalg::cholesky::cholesky_inverse",
"core::blas::quadform",
"linalg::lu::quickcheck_tests::lu_solve",
"linalg::full_piv_lu::quickcheck_tests::full_piv_lu_solve",
"linalg::qr::qr_solve",
"linalg::hessenberg::hessenberg",
"linalg::tridiagonal::symm_tridiagonal",
"src/lib.rs - (line 26)"
] |
[
"core::mint::mint_matrix_conversion_2_3",
"core::mint::mint_matrix_conversion_3_4"
] |
[] |
|
dimforge/nalgebra
| 645
|
dimforge__nalgebra-645
|
[
"644"
] |
d9a9c606029af0ad808c8e5385779a167d554114
|
diff --git a/src/base/blas.rs b/src/base/blas.rs
--- a/src/base/blas.rs
+++ b/src/base/blas.rs
@@ -565,6 +565,7 @@ where
);
if ncols2 == 0 {
+ self.fill(N::zero());
return;
}
diff --git a/src/base/blas.rs b/src/base/blas.rs
--- a/src/base/blas.rs
+++ b/src/base/blas.rs
@@ -1006,6 +1007,12 @@ where N: Scalar + Zero + ClosedAdd + ClosedMul
"gemm: dimensions mismatch for addition."
);
+
+ if a.ncols() == 0 {
+ self.fill(N::zero());
+ return;
+ }
+
// We assume large matrices will be Dynamic but small matrices static.
// We could use matrixmultiply for large statically-sized matrices but the performance
// threshold to activate it would be different from SMALL_DIM because our code optimizes
|
diff --git /dev/null b/tests/core/empty.rs
new file mode 100644
--- /dev/null
+++ b/tests/core/empty.rs
@@ -0,0 +1,30 @@
+use na::{DMatrix, DVector};
+
+#[test]
+fn empty_matrix_mul_vector() {
+ // Issue #644
+ let m = DMatrix::<f32>::zeros(8, 0);
+ let v = DVector::<f32>::zeros(0);
+ assert_eq!(m * v, DVector::zeros(8));
+}
+
+#[test]
+fn empty_matrix_mul_matrix() {
+ let m1 = DMatrix::<f32>::zeros(3, 0);
+ let m2 = DMatrix::<f32>::zeros(0, 4);
+ assert_eq!(m1 * m2, DMatrix::zeros(3, 4));
+}
+
+#[test]
+fn empty_matrix_tr_mul_vector() {
+ let m = DMatrix::<f32>::zeros(0, 5);
+ let v = DVector::<f32>::zeros(0);
+ assert_eq!(m.tr_mul(&v), DVector::zeros(5));
+}
+
+#[test]
+fn empty_matrix_tr_mul_matrix() {
+ let m1 = DMatrix::<f32>::zeros(0, 3);
+ let m2 = DMatrix::<f32>::zeros(0, 4);
+ assert_eq!(m1.tr_mul(&m2), DMatrix::zeros(3, 4));
+}
\ No newline at end of file
diff --git a/tests/core/mod.rs b/tests/core/mod.rs
--- a/tests/core/mod.rs
+++ b/tests/core/mod.rs
@@ -8,6 +8,7 @@ mod matrix_slice;
#[cfg(feature = "mint")]
mod mint;
mod serde;
+mod empty;
#[cfg(feature = "arbitrary")]
|
Multiplication of matrices with zero elements causes UB
The following test fails randomly:
```rust
#[test]
fn zero_mul() {
let m = DMatrix::<f32>::zeros(8, 0);
let v = DVector::<f32>::zeros(0);
assert_eq!(m * v, DVector::zeros(8));
}
```
This is because nalgebra does not properly handle the case of 0-shaped matrices. Here the output matrix (for the multiplication result) is allocated with uninitialized values before performing the multiplication. Because the matrices are 0-shaped, nothing happen during the multiplication, causing the output matrix to remain uninitialized.
|
2019-09-02T00:34:57Z
|
0.18
|
2019-09-01T18:38:05Z
|
f71d0c5b8cb087d5e9c629c93ce2aeec0620b5fe
|
[
"core::empty::empty_matrix_mul_matrix",
"core::empty::empty_matrix_mul_vector"
] |
[
"base::indexing::dimrange_range_usize",
"base::indexing::dimrange_rangefrom_dimname",
"base::indexing::dimrange_rangefull",
"base::indexing::dimrange_rangeinclusive_usize",
"base::indexing::dimrange_rangefrom_usize",
"base::indexing::dimrange_rangeto_usize",
"base::indexing::dimrange_usize",
"base::indexing::dimrange_rangetoinclusive_usize",
"geometry::transform::tests::checks_homogeneous_invariants_of_square_identity_matrix",
"linalg::symmetric_eigen::test::wilkinson_shift_zero",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_det",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diag_diff_and_zero_off_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_off_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_trace",
"geometry::quaternion_construction::tests::random_unit_quats_are_unit",
"linalg::symmetric_eigen::test::wilkinson_shift_random",
"core::abomonation::abomonate_isometry3",
"core::abomonation::abomonate_dmatrix",
"core::abomonation::abomonate_point3",
"core::abomonation::abomonate_quaternion",
"core::abomonation::abomonate_matrix3x4",
"core::abomonation::abomonate_isometry_matrix3",
"core::conversion::array_matrix_conversion_2_3",
"core::abomonation::abomonate_translation3",
"core::abomonation::abomonate_rotation3",
"core::conversion::array_matrix_conversion_2_2",
"core::abomonation::abomonate_similarity3",
"core::conversion::array_matrix_conversion_2_5",
"core::conversion::array_matrix_conversion_2_6",
"core::abomonation::abomonate_similarity_matrix3",
"core::conversion::array_matrix_conversion_3_3",
"core::conversion::array_matrix_conversion_2_4",
"core::conversion::array_matrix_conversion_3_4",
"core::conversion::array_matrix_conversion_3_5",
"core::conversion::array_matrix_conversion_3_2",
"core::conversion::array_matrix_conversion_3_6",
"core::conversion::array_matrix_conversion_4_2",
"core::conversion::array_matrix_conversion_4_4",
"core::conversion::array_matrix_conversion_4_5",
"core::conversion::array_matrix_conversion_4_6",
"core::conversion::array_matrix_conversion_5_2",
"core::conversion::array_matrix_conversion_5_5",
"core::conversion::array_matrix_conversion_5_6",
"core::conversion::array_matrix_conversion_5_3",
"core::conversion::array_matrix_conversion_5_4",
"core::conversion::array_matrix_conversion_6_2",
"core::conversion::array_matrix_conversion_6_4",
"core::conversion::array_matrix_conversion_6_3",
"core::conversion::array_matrix_conversion_6_5",
"core::conversion::array_matrix_conversion_4_3",
"core::conversion::array_row_vector_conversion_1",
"core::conversion::array_matrix_conversion_6_6",
"core::conversion::array_row_vector_conversion_2",
"core::conversion::array_row_vector_conversion_3",
"core::conversion::array_row_vector_conversion_4",
"core::conversion::array_row_vector_conversion_5",
"core::conversion::array_row_vector_conversion_6",
"core::conversion::array_vector_conversion_4",
"core::conversion::array_vector_conversion_3",
"core::conversion::array_vector_conversion_1",
"core::conversion::array_vector_conversion_2",
"core::conversion::array_vector_conversion_6",
"core::edition::insert_columns",
"core::edition::insert_columns_to_empty_matrix",
"core::edition::insert_rows",
"core::edition::insert_rows_to_empty_matrix",
"core::edition::remove_columns",
"core::edition::remove_columns_at",
"core::edition::remove_rows",
"core::edition::remove_rows_at",
"core::edition::resize",
"core::edition::resize_empty_matrix",
"core::edition::swap_columns",
"core::edition::swap_rows",
"core::edition::upper_lower_triangular",
"core::empty::empty_matrix_tr_mul_matrix",
"core::empty::empty_matrix_tr_mul_vector",
"core::matrix::apply",
"core::matrix::components_mut",
"core::matrix::coordinates",
"core::matrix::copy_from_slice",
"core::matrix::copy_from_slice_too_large",
"core::matrix::copy_from_slice_too_small",
"core::matrix::cross_product_vector_and_row_vector",
"core::matrix::debug_output_corresponds_to_data_container",
"core::conversion::array_vector_conversion_5",
"core::conversion::translation_conversion",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis1",
"core::conversion::similarity_conversion",
"core::conversion::isometry_conversion",
"core::conversion::rotation_conversion",
"core::conversion::unit_quaternion_conversion",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis2",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis3",
"core::matrix::finite_dim_inner_space_tests::orthonormalize1",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis4",
"core::matrix::finite_dim_inner_space_tests::orthonormalize2",
"core::matrix::from_columns",
"core::matrix::from_columns_dynamic",
"core::matrix::from_diagonal",
"core::matrix::from_not_enough_columns",
"core::matrix::from_rows",
"core::matrix::from_rows_with_different_dimensions",
"core::matrix::from_too_many_rows",
"core::matrix::identity",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim1",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim2",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis5",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim3",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis6",
"core::matrix::is_column_major",
"core::matrix::iter",
"core::matrix::kronecker",
"core::matrix::linear_index",
"core::matrix::map",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim4",
"core::matrix::map_with_location",
"core::matrix::normalization_tests::normalized_vec_norm_is_one",
"core::matrix::partial_clamp",
"core::matrix::normalization_tests::normalized_vec_norm_is_one_dyn",
"core::matrix::push",
"core::matrix::partial_cmp",
"core::matrix::set_row_column",
"core::matrix::simple_add",
"core::matrix::simple_mul",
"core::matrix::simple_scalar_conversion",
"core::matrix::simple_product",
"core::matrix::simple_scalar_mul",
"core::matrix::simple_transpose",
"core::matrix::simple_transpose_mut",
"core::matrix::simple_sum",
"core::matrix::swizzle",
"core::matrix::to_homogeneous",
"core::matrix::trace",
"core::matrix::trace_panic",
"core::matrix::transposition_tests::check_transpose_components_dyn",
"core::matrix::transposition_tests::transpose_mut_transpose_mut_is_self",
"core::matrix::transposition_tests::tr_mul_is_transpose_then_mul",
"core::matrix::transposition_tests::transpose_transpose_is_id_dyn",
"core::matrix::vector_index_mut",
"core::matrix::zip_map",
"core::matrix_slice::col_slice_mut",
"core::matrix::transposition_tests::transpose_transpose_is_self",
"core::matrix_slice::columns_out_of_bounds",
"core::matrix_slice::column_out_of_bounds",
"core::matrix::finite_dim_inner_space_tests::orthonormalize3",
"core::matrix_slice::nested_col_slices",
"core::matrix_slice::nested_fixed_slices",
"core::matrix_slice::nested_row_slices",
"core::matrix_slice::nested_slices",
"core::matrix_slice::new_slice",
"core::matrix_slice::columns_range_pair",
"core::matrix_slice::row_out_of_bounds",
"core::matrix_slice::row_slice_mut",
"core::matrix_slice::rows_out_of_bounds",
"core::matrix_slice::rows_range_pair",
"core::matrix_slice::rows_with_step_out_of_bounds",
"core::matrix_slice::slice_mut",
"core::matrix_slice::slice_out_of_bounds",
"core::matrix_slice::slice_with_steps_out_of_bounds",
"core::mint::mint_matrix_conversion_2_2",
"core::mint::mint_matrix_conversion_2_3",
"core::mint::mint_matrix_conversion_3_3",
"core::mint::mint_matrix_conversion_3_4",
"core::mint::mint_matrix_conversion_4_4",
"core::mint::mint_quaternion_conversions",
"core::mint::mint_vector_conversion_2",
"core::mint::mint_vector_conversion_3",
"core::mint::mint_vector_conversion_4",
"core::serde::serde_dmatrix",
"core::serde::serde_flat",
"core::serde::serde_isometry2",
"core::serde::serde_isometry3",
"core::serde::serde_isometry_matrix2",
"core::serde::serde_isometry_matrix3",
"core::serde::serde_matrix3x4",
"core::serde::serde_point2",
"core::serde::serde_point3",
"core::serde::serde_quaternion",
"core::serde::serde_rotation2",
"core::matrix_slice::new_slice_mut",
"core::matrix_slice::columns_with_step_out_of_bounds",
"core::serde::serde_rotation3",
"core::serde::serde_similarity3",
"core::serde::serde_similarity2",
"core::serde::serde_similarity_matrix2",
"core::serde::serde_similarity_matrix3",
"core::serde::serde_translation3",
"core::serde::serde_translation2",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim6",
"geometry::isometry::append_rotation_wrt_point_to_id",
"geometry::isometry::composition2",
"core::matrix::finite_dim_inner_space_tests::orthonormalize4",
"geometry::isometry::inverse_is_identity",
"geometry::isometry::inverse_is_parts_inversion",
"geometry::isometry::look_at_rh_3",
"geometry::isometry::observer_frame_3",
"geometry::point::point_clone",
"geometry::point::point_coordinates",
"geometry::point::point_ops",
"geometry::isometry::multiply_equals_alga_transform",
"geometry::point::point_scale",
"geometry::point::point_vector_sum",
"geometry::point::to_homogeneous",
"geometry::projection::orthographic_inverse",
"geometry::projection::perspective_inverse",
"geometry::projection::perspective_matrix_point_transformation",
"geometry::isometry::composition3",
"geometry::point::point_sub",
"geometry::projection::quickcheck_tests::orthographic_project_unproject",
"geometry::isometry::rotation_wrt_point_invariance",
"geometry::projection::quickcheck_tests::perspective_project_unproject",
"geometry::quaternion::euler_angles",
"geometry::quaternion::from_euler_angles",
"geometry::quaternion::unit_quaternion_double_covering",
"geometry::quaternion::unit_quaternion_rotation_conversion",
"geometry::quaternion::unit_quaternion_inv",
"geometry::rotation::angle_2",
"geometry::rotation::angle_3",
"geometry::rotation::quaternion_euler_angles_issue_494",
"geometry::quaternion::unit_quaternion_mul_vector",
"geometry::rotation::quickcheck_tests::angle_is_commutative_2",
"geometry::rotation::quickcheck_tests::angle_is_commutative_3",
"geometry::rotation::quickcheck_tests::euler_angles",
"geometry::quaternion::unit_quaternion_transformation",
"geometry::rotation::quickcheck_tests::euler_angles_gimble_lock",
"geometry::rotation::quickcheck_tests::new_rotation_2",
"geometry::rotation::quickcheck_tests::powf_rotation_2",
"geometry::rotation::quickcheck_tests::new_rotation_3",
"geometry::rotation::quickcheck_tests::from_euler_angles",
"geometry::rotation::quickcheck_tests::powf_rotation_3",
"geometry::rotation::quickcheck_tests::rotation_between_2",
"geometry::rotation::quickcheck_tests::rotation_between_3",
"geometry::rotation::quickcheck_tests::rotation_between_is_anticommutative_2",
"geometry::rotation::quickcheck_tests::rotation_between_is_identity",
"geometry::rotation::quickcheck_tests::rotation_between_is_anticommutative_3",
"geometry::rotation::quickcheck_tests::rotation_inv_2",
"geometry::isometry::all_op_exist",
"geometry::rotation::quickcheck_tests::rotation_inv_3",
"core::matrix::finite_dim_inner_space_tests::orthonormalize5",
"geometry::similarity::inverse_is_parts_inversion",
"geometry::unit_complex::all_op_exist",
"geometry::unit_complex::unit_complex_inv",
"geometry::quaternion::all_op_exist",
"geometry::unit_complex::unit_complex_rotation_conversion",
"geometry::unit_complex::unit_complex_mul_vector",
"core::blas::gemv_tr",
"geometry::unit_complex::unit_complex_transformation",
"linalg::balancing::balancing_parlett_reinsch_static",
"linalg::bidiagonal::bidiagonal_identity",
"geometry::similarity::inverse_is_identity",
"geometry::similarity::multiply_equals_alga_transform",
"linalg::balancing::balancing_parlett_reinsch",
"linalg::bidiagonal::complex::bidiagonal_static_square_2x2",
"core::matrix::finite_dim_inner_space_tests::orthonormalize6",
"linalg::bidiagonal::complex::bidiagonal_static_5_3",
"linalg::bidiagonal::complex::bidiagonal_static_3_5",
"linalg::bidiagonal::complex::bidiagonal",
"linalg::bidiagonal::complex::bidiagonal_static_square",
"linalg::bidiagonal::f64::bidiagonal",
"linalg::bidiagonal::f64::bidiagonal_static_5_3",
"linalg::bidiagonal::f64::bidiagonal_static_square",
"linalg::bidiagonal::f64::bidiagonal_static_square_2x2",
"linalg::bidiagonal::f64::bidiagonal_static_3_5",
"geometry::similarity::all_op_exist",
"geometry::similarity::composition",
"linalg::cholesky::complex::cholesky_inverse_static",
"linalg::cholesky::complex::cholesky_static",
"core::blas::gemv_symm",
"linalg::cholesky::complex::cholesky_solve_static",
"linalg::cholesky::f64::cholesky_inverse_static",
"linalg::convolution::convolve_full_check",
"linalg::convolution::convolve_same_check",
"linalg::convolution::convolve_valid_check",
"linalg::cholesky::f64::cholesky_static",
"core::blas::ger_symm",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_static_square_2x2",
"linalg::cholesky::f64::cholesky_solve_static",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_static_square_3x3",
"core::blas::quadform_tr",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_static_square_4x4",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_static_square_2x2",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_static_square_3x3",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_static_square_4x4",
"linalg::eigen::symmetric_eigen_singular_24x24",
"linalg::full_piv_lu::full_piv_lu_simple",
"linalg::full_piv_lu::full_piv_lu_simple_with_pivot",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_inverse_static",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_singular",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_singular",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_solve_static",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_static_3_5",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_static_square",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_static_5_3",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_inverse_static",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_solve_static",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_static_3_5",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_static_5_3",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_static_square",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_inverse",
"linalg::hessenberg::complex::hessenberg_static",
"linalg::hessenberg::complex::hessenberg_static_mat2",
"linalg::cholesky::f64::cholesky",
"linalg::hessenberg::f64::hessenberg_static",
"linalg::hessenberg::f64::hessenberg_static_mat2",
"linalg::hessenberg::hessenberg_simple",
"linalg::inverse::matrix1_try_inverse",
"linalg::inverse::matrix1_try_inverse_scaled_identity",
"linalg::inverse::matrix2_try_inverse",
"linalg::inverse::matrix2_try_inverse_scaled_identity",
"linalg::inverse::matrix3_try_inverse",
"linalg::inverse::matrix3_try_inverse_scaled_identity",
"linalg::inverse::matrix4_try_inverse_issue_214",
"linalg::inverse::matrix5_try_inverse",
"linalg::inverse::matrix5_try_inverse_scaled_identity",
"linalg::lu::lu_simple",
"linalg::lu::lu_simple_with_pivot",
"linalg::lu::quickcheck_tests::complex::lu",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_inverse",
"linalg::lu::quickcheck_tests::complex::lu_inverse_static",
"linalg::lu::quickcheck_tests::complex::lu_inverse",
"linalg::lu::quickcheck_tests::complex::lu_solve_static",
"linalg::lu::quickcheck_tests::complex::lu_static_3_5",
"linalg::lu::quickcheck_tests::complex::lu_static_5_3",
"linalg::lu::quickcheck_tests::complex::lu_static_square",
"linalg::lu::quickcheck_tests::f64::lu",
"core::blas::quadform",
"linalg::lu::quickcheck_tests::f64::lu_inverse_static",
"linalg::lu::quickcheck_tests::f64::lu_inverse",
"linalg::lu::quickcheck_tests::f64::lu_solve_static",
"linalg::lu::quickcheck_tests::f64::lu_static_3_5",
"linalg::lu::quickcheck_tests::f64::lu_static_5_3",
"linalg::lu::quickcheck_tests::f64::lu_static_square",
"linalg::qr::complex::qr",
"linalg::cholesky::f64::cholesky_solve",
"linalg::qr::complex::qr_inverse_static",
"linalg::cholesky::f64::cholesky_inverse",
"linalg::qr::complex::qr_solve_static",
"linalg::qr::complex::qr_inverse",
"linalg::qr::complex::qr_static_5_3",
"linalg::qr::complex::qr_static_3_5",
"linalg::qr::f64::qr",
"linalg::qr::complex::qr_static_square",
"linalg::qr::f64::qr_inverse_static",
"linalg::qr::f64::qr_inverse",
"linalg::qr::f64::qr_solve_static",
"linalg::qr::f64::qr_static_3_5",
"linalg::qr::f64::qr_static_5_3",
"linalg::qr::f64::qr_static_square",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_solve",
"linalg::schur::quickcheck_tests::complex::schur_static_mat2",
"linalg::schur::quickcheck_tests::complex::schur_static_mat3",
"linalg::schur::quickcheck_tests::complex::schur_static_mat4",
"linalg::lu::quickcheck_tests::f64::lu_solve",
"linalg::schur::quickcheck_tests::f64::schur_static_mat2",
"linalg::schur::quickcheck_tests::f64::schur_static_mat3",
"linalg::schur::quickcheck_tests::f64::schur_static_mat4",
"linalg::schur::schur_simpl_mat3",
"linalg::schur::schur_singular",
"linalg::schur::schur_static_mat3_fail",
"linalg::schur::schur_static_mat4_fail",
"linalg::schur::schur_static_mat4_fail2",
"linalg::solve::complex::solve_lower_triangular",
"linalg::schur::quickcheck_tests::f64::schur",
"linalg::solve::complex::solve_upper_triangular",
"linalg::solve::complex::tr_solve_lower_triangular",
"linalg::solve::f64::solve_lower_triangular",
"linalg::solve::f64::solve_upper_triangular",
"linalg::schur::quickcheck_tests::complex::schur",
"linalg::solve::complex::tr_solve_upper_triangular",
"linalg::solve::f64::tr_solve_lower_triangular",
"linalg::solve::f64::tr_solve_upper_triangular",
"linalg::svd::quickcheck_tests::complex::svd",
"linalg::svd::quickcheck_tests::complex::svd_pseudo_inverse",
"linalg::svd::quickcheck_tests::complex::svd_static_2_5",
"linalg::svd::quickcheck_tests::complex::svd_static_5_2",
"linalg::svd::quickcheck_tests::complex::svd_static_3_5",
"linalg::svd::quickcheck_tests::complex::svd_static_5_3",
"linalg::svd::quickcheck_tests::complex::svd_static_square_2x2",
"linalg::svd::quickcheck_tests::f64::svd",
"linalg::svd::quickcheck_tests::complex::svd_static_square",
"linalg::hessenberg::f64::hessenberg",
"linalg::svd::quickcheck_tests::f64::svd_static_2_5",
"linalg::svd::quickcheck_tests::f64::svd_pseudo_inverse",
"linalg::svd::quickcheck_tests::f64::svd_static_3_5",
"linalg::svd::quickcheck_tests::complex::svd_solve",
"linalg::svd::quickcheck_tests::f64::svd_static_5_2",
"linalg::svd::quickcheck_tests::f64::svd_static_square_2x2",
"linalg::svd::svd_err",
"linalg::svd::svd_fail",
"linalg::svd::quickcheck_tests::f64::svd_static_5_3",
"linalg::svd::svd_identity",
"linalg::svd::svd_singular_horizontal",
"linalg::svd::svd_singular",
"linalg::svd::svd_with_delimited_subproblem",
"linalg::svd::svd_zeros",
"linalg::svd::svd_singular_vertical",
"linalg::cholesky::complex::cholesky",
"linalg::tridiagonal::complex::symm_tridiagonal_singular",
"linalg::svd::quickcheck_tests::f64::svd_static_square",
"linalg::tridiagonal::complex::symm_tridiagonal_static_square_2x2",
"linalg::tridiagonal::complex::symm_tridiagonal_static_square",
"linalg::tridiagonal::f64::symm_tridiagonal_singular",
"linalg::tridiagonal::f64::symm_tridiagonal_static_square",
"linalg::tridiagonal::f64::symm_tridiagonal_static_square_2x2",
"linalg::svd::quickcheck_tests::f64::svd_solve",
"linalg::lu::quickcheck_tests::complex::lu_solve",
"linalg::qr::f64::qr_solve",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_solve",
"linalg::tridiagonal::f64::symm_tridiagonal",
"linalg::cholesky::complex::cholesky_solve",
"linalg::qr::complex::qr_solve",
"linalg::hessenberg::complex::hessenberg",
"linalg::cholesky::complex::cholesky_inverse",
"linalg::tridiagonal::complex::symm_tridiagonal",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::tr_dot (line 434)",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::icamax_full (line 201)",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::dotc (line 410)",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::dot (line 379)",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::iamax_full (line 238)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::axpy (line 501)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::gemv (line 536)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::argmin (line 127)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::argmax (line 56)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::icamax (line 23)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::iamin (line 169)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::iamax (line 98)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::imax (line 84)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::cdpy (line 79)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R, C, S>::abs (line 22)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::cmpy (line 79)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::imin (line 155)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_div_mut (line 134)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_div (line 54)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_div_assign (line 114)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_mul (line 54)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_mul_assign (line 114)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_mul_mut (line 134)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_element (line 343)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_diagonal_element (line 503)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_fn (line 451)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_column_slice (line 640)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::identity (line 480)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_partial_diagonal (line 528)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_vec (line 668)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::zeros (line 395)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_row_slice (line 613)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::repeat (line 370)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_iterator (line 423)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_diagonal_element (line 503)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_column_slice (line 640)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_element (line 343)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_partial_diagonal (line 528)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_fn (line 451)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::zeros (line 395)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_iterator (line 423)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::identity (line 480)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::repeat (line 370)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_row_slice (line 613)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_vec (line 668)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_column_slice (line 640)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_diagonal_element (line 503)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_element (line 343)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_columns (line 207)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_fn (line 451)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_partial_diagonal (line 528)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::identity (line 480)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_iterator (line 423)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::zeros (line 395)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_rows (line 167)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::repeat (line 370)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_vec_generic (line 266)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_row_slice (line 613)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_vec (line 668)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_diagonal_element (line 503)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_element (line 343)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_partial_diagonal (line 528)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_column_slice (line 640)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_fn (line 451)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::identity (line 480)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::zeros (line 395)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_iterator (line 423)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_vec (line 668)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::repeat (line 370)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_row_slice (line 613)",
"src/base/construction.rs - base::construction::MatrixN<N, D>::from_diagonal (line 293)",
"src/base/edition.rs - base::edition::Matrix<N, Dynamic, U1, S>::extend (line 996)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 1021)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 949)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 1043)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 969)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 1055)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 339)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 374)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 364)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 351)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 386)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 413)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 397)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 424)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::ncols (line 203)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::len (line 162)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::nrows (line 190)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::column_iter (line 267)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::iter (line 232)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::column_iter_mut (line 665)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::shape (line 176)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::strides (line 216)",
"src/base/matrix.rs - base::matrix::Unit<Vector<N, D, S>>::slerp (line 1600)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::row_iter (line 252)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::row_iter_mut (line 645)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::amax (line 889)",
"src/base/matrix.rs - base::matrix::Vector<N, D, S>::lerp (line 1581)",
"src/base/norm.rs - base::norm::Matrix<N, R, C, S>::apply_norm (line 134)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::amin (line 931)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::camax (line 902)",
"src/base/norm.rs - base::norm::Matrix<N, R, C, S>::apply_metric_distance (line 151)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::camin (line 944)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 403)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::max (line 917)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 443)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::min (line 959)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 393)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::column_mean (line 294)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::mean (line 238)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::column_sum (line 119)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_mean_tr (line 277)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_mean (line 260)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 433)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::column_variance (line 202)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_sum_tr (line 102)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_sum (line 85)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_variance (line 168)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::sum (line 67)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_variance_tr (line 185)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_rotation_mut (line 197)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::variance (line 144)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_translation_mut (line 178)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_rotation_wrt_center_mut (line 242)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_rotation_wrt_point_mut (line 219)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse (line 137)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse_mut (line 157)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::from_parts (line 114)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse_transform_vector (line 333)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse_transform_point (line 309)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::to_homogeneous (line 361)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, D, R>::rotation_wrt_point (line 50)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::transform_point (line 264)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U2, Rotation2<N>>::new (line 118)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::transform_vector (line 287)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, D, R>::identity (line 29)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U2, UnitComplex<N>>::new (line 153)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, Rotation3<N>>::face_towards (line 241)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, Rotation3<N>>::look_at_lh (line 335)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, Rotation3<N>>::look_at_rh (line 292)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::as_projective (line 244)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::as_matrix (line 225)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, Rotation3<N>>::new (line 189)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, UnitQuaternion<N>>::face_towards (line 241)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::bottom (line 329)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, UnitQuaternion<N>>::look_at_lh (line 335)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::from_matrix_unchecked (line 125)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, UnitQuaternion<N>>::new (line 189)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, UnitQuaternion<N>>::look_at_rh (line 292)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::into_inner (line 270)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::left (line 297)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::right (line 313)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_bottom (line 531)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::inverse (line 170)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_bottom_and_top (line 632)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_left (line 493)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::project_vector (line 468)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::project_point (line 395)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::new (line 70)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_left_and_right (line 607)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_right (line 512)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_top (line 550)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_zfar (line 588)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_znear_and_zfar (line 657)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_znear (line 569)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::to_projective (line 257)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::top (line 345)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::to_homogeneous (line 206)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::zfar (line 377)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::znear (line 361)",
"src/geometry/point.rs - geometry::point::Point<N, D>::len (line 136)",
"src/geometry/point.rs - geometry::point::Point<N, D>::iter (line 161)",
"src/geometry/point.rs - geometry::point::Point<N, D>::iter_mut (line 184)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::unproject_point (line 430)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, D>::origin (line 28)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U1>::new (line 163)",
"src/geometry/point.rs - geometry::point::Point<N, D>::to_homogeneous (line 103)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U2>::new (line 163)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, D>::from_slice (line 49)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U3>::new (line 163)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U4>::new (line 163)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U6>::new (line 163)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, D>::from_homogeneous (line 71)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U5>::new (line 163)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::as_vector (line 224)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::as_vector_mut (line 493)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::acosh (line 806)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::acos (line 663)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::asin (line 701)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::asinh (line 773)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::conjugate (line 136)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::atan (line 737)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::conjugate_mut (line 528)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::cos (line 645)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::atanh (line 839)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::cosh (line 790)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::dot (line 299)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::exp (line 435)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::inner (line 315)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::exp_eps (line 450)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::lerp (line 181)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::ln (line 417)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::magnitude (line 256)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::magnitude_squared (line 286)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::norm (line 239)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::normalize (line 115)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::normalize_mut (line 573)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::norm_squared (line 270)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::outer (line 333)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::polar_decomposition (line 391)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::project (line 352)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::powf (line 479)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::right_div (line 628)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::scalar (line 211)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::reject (line 371)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::sin (line 683)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::sinh (line 757)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::tan (line 721)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::tanh (line 823)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::try_inverse_mut (line 544)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::try_inverse (line 150)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::vector_mut (line 507)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::vector (line 196)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::angle (line 939)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::angle_to (line 1000)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::axis_angle (line 1174)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::euler_angles (line 1307)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::axis (line 1128)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::conjugate (line 969)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse (line 984)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse_mut (line 1111)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse_transform_point (line 1388)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::lerp (line 1036)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse_transform_vector (line 1410)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::nlerp (line 1052)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::ln (line 1205)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::quaternion (line 956)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::powf (line 1227)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::rotation_to (line 1018)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::to_rotation_matrix (line 1250)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::scaled_axis (line 1153)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::to_homogeneous (line 1325)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::transform_point (line 1348)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<N>::from_parts (line 59)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::transform_vector (line 1368)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<N>::new (line 36)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<N>::identity (line 94)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_euler_angles (line 217)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_axis_angle (line 176)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::face_towards (line 475)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_scaled_axis (line 630)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_rotation_matrix (line 245)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_scaled_axis_eps (line 658)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::identity (line 155)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::look_at_lh (line 547)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::rotation_between (line 335)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::look_at_rh (line 516)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::new_eps (line 600)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::new (line 571)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::scaled_rotation_between (line 357)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::rotation_between_axis (line 392)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::scaled_rotation_between_axis (line 417)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::into_inner (line 154)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::from_matrix_unchecked (line 227)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse_transform_point (line 401)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::matrix (line 114)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse (line 282)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse_mut (line 332)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transform_point (line 363)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse_transform_vector (line 420)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::to_homogeneous (line 189)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::angle (line 149)",
"src/geometry/rotation_construction.rs - geometry::rotation_construction::Rotation<N, D>::identity (line 19)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transform_vector (line 382)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::angle_to (line 163)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::new (line 28)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transpose (line 259)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transpose_mut (line 305)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::powf (line 211)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::rotation_to (line 180)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::angle (line 673)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::scaled_rotation_between (line 123)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::rotation_between (line 101)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::axis_angle (line 737)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::axis (line 690)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::angle_to (line 763)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::euler_angles (line 456)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::from_euler_angles (line 416)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::face_towards (line 505)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::from_axis_angle (line 364)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::from_scaled_axis (line 341)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::look_at_lh (line 583)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::look_at_rh (line 552)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::powf (line 797)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::new (line 266)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::scaled_axis (line 716)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::rotation_to (line 780)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::rotation_between (line 607)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::inverse_transform_point (line 288)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::scaled_rotation_between (line 629)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::transform_point (line 247)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::inverse_transform_vector (line 308)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::transform_vector (line 268)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, D, R>::identity (line 31)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U2, UnitComplex<N>>::new (line 158)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, D, R>::rotation_wrt_point (line 87)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U2, Rotation2<N>>::new (line 135)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::face_towards (line 224)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::look_at_rh (line 274)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::look_at_lh (line 312)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::face_towards (line 224)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::new (line 185)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::into_inner (line 246)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::look_at_lh (line 312)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::matrix (line 271)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::new (line 185)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::look_at_rh (line 274)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::inverse (line 385)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::matrix_mut_unchecked (line 291)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::inverse_mut (line 437)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::to_homogeneous (line 335)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::inverse_transform_point (line 220)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::to_homogeneous (line 141)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::inverse_mut (line 173)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::inverse (line 121)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::try_inverse_mut (line 408)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::try_inverse (line 353)",
"src/geometry/transform_construction.rs - geometry::transform_construction::Transform<N, D, C>::identity (line 18)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::transform_point (line 203)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U2>::new (line 85)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U1>::new (line 85)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U3>::new (line 85)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U4>::new (line 85)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::angle (line 16)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::complex (line 86)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, D>::identity (line 24)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U5>::new (line 85)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U6>::new (line 85)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::conjugate_mut (line 169)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::cos_angle (line 43)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::angle_to (line 133)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::conjugate (line 102)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse_mut (line 188)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse (line 117)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::sin_angle (line 29)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::powf (line 208)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse_transform_point (line 294)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::rotation_to (line 151)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse_transform_vector (line 312)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::to_rotation_matrix (line 223)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::to_homogeneous (line 241)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::from_angle (line 56)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::transform_point (line 260)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::identity (line 19)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::transform_vector (line 278)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::from_cos_sin_unchecked (line 77)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::from_rotation_matrix (line 120)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::new (line 36)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::rotation_between_axis (line 219)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::rotation_between (line 162)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::scaled_rotation_between (line 184)",
"src/lib.rs - (line 26)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::scaled_rotation_between_axis (line 244)"
] |
[] |
[] |
|
dimforge/nalgebra
| 641
|
dimforge__nalgebra-641
|
[
"640"
] |
a74702bb5af6d5fad292b06540bb66908f0708f1
|
diff --git a/src/base/cg.rs b/src/base/cg.rs
--- a/src/base/cg.rs
+++ b/src/base/cg.rs
@@ -358,10 +358,10 @@ where DefaultAllocator: Allocator<N, D, D>
+ unsafe { *self.get_unchecked((D::dim() - 1, D::dim() - 1)) };
if !n.is_zero() {
- return transform * (pt / n) + translation;
+ (transform * pt + translation) / n
+ } else {
+ transform * pt + translation
}
-
- transform * pt + translation
}
}
|
diff --git a/tests/geometry/projection.rs b/tests/geometry/projection.rs
--- a/tests/geometry/projection.rs
+++ b/tests/geometry/projection.rs
@@ -1,4 +1,4 @@
-use na::{Orthographic3, Perspective3};
+use na::{Orthographic3, Perspective3, Point3};
#[test]
fn perspective_inverse() {
diff --git a/tests/geometry/projection.rs b/tests/geometry/projection.rs
--- a/tests/geometry/projection.rs
+++ b/tests/geometry/projection.rs
@@ -20,6 +20,19 @@ fn orthographic_inverse() {
assert!(id.is_identity(1.0e-7));
}
+#[test]
+fn perspective_matrix_point_transformation() {
+ // https://github.com/rustsim/nalgebra/issues/640
+ let proj = Perspective3::new(4.0 / 3.0, 90.0, 0.1, 100.0);
+ let perspective_inv = proj.as_matrix().try_inverse().unwrap();
+ let some_point = Point3::new(1.0, 2.0, 0.0);
+
+ assert_eq!(
+ perspective_inv.transform_point(&some_point),
+ Point3::from_homogeneous(perspective_inv * some_point.coords.push(1.0)).unwrap()
+ );
+}
+
#[cfg(feature = "arbitrary")]
mod quickcheck_tests {
use na::{Orthographic3, Perspective3, Point3};
|
SquareMatrix::transform_point is wrong
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=17498e4b5eca2e898e4a4684247fc0cd
The `transform_point` method yields a wrong z value.
|
2019-08-27T20:30:49Z
|
0.18
|
2019-08-27T13:15:33Z
|
f71d0c5b8cb087d5e9c629c93ce2aeec0620b5fe
|
[
"geometry::projection::perspective_matrix_point_transformation"
] |
[
"base::indexing::dimrange_rangefrom_dimname",
"base::indexing::dimrange_range_usize",
"base::indexing::dimrange_rangefrom_usize",
"base::indexing::dimrange_rangefull",
"base::indexing::dimrange_rangeto_usize",
"base::indexing::dimrange_rangetoinclusive_usize",
"base::indexing::dimrange_rangeinclusive_usize",
"base::indexing::dimrange_usize",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_det",
"linalg::symmetric_eigen::test::wilkinson_shift_zero",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diag_diff_and_zero_off_diagonal",
"geometry::transform::tests::checks_homogeneous_invariants_of_square_identity_matrix",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_off_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_trace",
"geometry::quaternion_construction::tests::random_unit_quats_are_unit",
"linalg::symmetric_eigen::test::wilkinson_shift_random",
"core::abomonation::abomonate_dmatrix",
"core::abomonation::abomonate_isometry3",
"core::abomonation::abomonate_matrix3x4",
"core::abomonation::abomonate_point3",
"core::abomonation::abomonate_quaternion",
"core::conversion::array_matrix_conversion_2_2",
"core::conversion::array_matrix_conversion_2_3",
"core::abomonation::abomonate_translation3",
"core::abomonation::abomonate_similarity3",
"core::conversion::array_matrix_conversion_2_4",
"core::conversion::array_matrix_conversion_2_5",
"core::conversion::array_matrix_conversion_2_6",
"core::conversion::array_matrix_conversion_3_2",
"core::conversion::array_matrix_conversion_3_3",
"core::abomonation::abomonate_similarity_matrix3",
"core::conversion::array_matrix_conversion_3_4",
"core::conversion::array_matrix_conversion_3_5",
"core::conversion::array_matrix_conversion_3_6",
"core::conversion::array_matrix_conversion_4_3",
"core::conversion::array_matrix_conversion_4_2",
"core::conversion::array_matrix_conversion_4_5",
"core::conversion::array_matrix_conversion_4_4",
"core::conversion::array_matrix_conversion_5_2",
"core::conversion::array_matrix_conversion_4_6",
"core::conversion::array_matrix_conversion_5_3",
"core::conversion::array_matrix_conversion_5_4",
"core::conversion::array_matrix_conversion_5_5",
"core::conversion::array_matrix_conversion_5_6",
"core::conversion::array_matrix_conversion_6_3",
"core::conversion::array_matrix_conversion_6_4",
"core::conversion::array_matrix_conversion_6_5",
"core::conversion::array_row_vector_conversion_1",
"core::conversion::array_matrix_conversion_6_6",
"core::conversion::array_row_vector_conversion_2",
"core::conversion::array_row_vector_conversion_4",
"core::conversion::array_row_vector_conversion_5",
"core::conversion::array_row_vector_conversion_6",
"core::conversion::array_vector_conversion_1",
"core::conversion::array_vector_conversion_2",
"core::conversion::array_vector_conversion_3",
"core::conversion::array_vector_conversion_4",
"core::conversion::array_vector_conversion_5",
"core::conversion::array_vector_conversion_6",
"core::conversion::array_row_vector_conversion_3",
"core::conversion::array_matrix_conversion_6_2",
"core::conversion::translation_conversion",
"core::edition::insert_columns",
"core::edition::insert_columns_to_empty_matrix",
"core::edition::insert_rows",
"core::edition::insert_rows_to_empty_matrix",
"core::edition::remove_columns",
"core::edition::remove_columns_at",
"core::edition::remove_rows",
"core::edition::remove_rows_at",
"core::edition::resize",
"core::edition::resize_empty_matrix",
"core::edition::swap_columns",
"core::edition::swap_rows",
"core::edition::upper_lower_triangular",
"core::matrix::apply",
"core::matrix::components_mut",
"core::matrix::coordinates",
"core::matrix::copy_from_slice",
"core::matrix::copy_from_slice_too_large",
"core::matrix::copy_from_slice_too_small",
"core::matrix::cross_product_vector_and_row_vector",
"core::matrix::debug_output_corresponds_to_data_container",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis1",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis2",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis3",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis4",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis5",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis6",
"core::abomonation::abomonate_rotation3",
"core::abomonation::abomonate_isometry_matrix3",
"core::blas::gemv_tr",
"core::matrix::finite_dim_inner_space_tests::orthonormalize1",
"core::conversion::similarity_conversion",
"core::conversion::isometry_conversion",
"core::matrix::from_columns",
"core::conversion::unit_quaternion_conversion",
"core::matrix::from_columns_dynamic",
"core::matrix::from_diagonal",
"core::matrix::from_rows",
"core::matrix::from_rows_with_different_dimensions",
"core::conversion::rotation_conversion",
"core::matrix::from_too_many_rows",
"core::matrix::identity",
"core::matrix::from_not_enough_columns",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim1",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim2",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim3",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim4",
"core::matrix::iter",
"core::matrix::kronecker",
"core::matrix::linear_index",
"core::matrix::map",
"core::matrix::map_with_location",
"core::matrix::normalization_tests::normalized_vec_norm_is_one",
"core::matrix::finite_dim_inner_space_tests::orthonormalize2",
"core::matrix::partial_clamp",
"core::matrix::partial_cmp",
"core::matrix::push",
"core::matrix::set_row_column",
"core::matrix::simple_add",
"core::matrix::simple_mul",
"core::matrix::simple_product",
"core::matrix::normalization_tests::normalized_vec_norm_is_one_dyn",
"core::matrix::simple_scalar_conversion",
"core::matrix::simple_scalar_mul",
"core::matrix::simple_transpose",
"core::matrix::simple_transpose_mut",
"core::matrix::simple_sum",
"core::matrix::swizzle",
"core::matrix::to_homogeneous",
"core::matrix::trace",
"core::matrix::trace_panic",
"core::matrix::is_column_major",
"core::matrix::transposition_tests::check_transpose_components_dyn",
"core::matrix::transposition_tests::transpose_mut_transpose_mut_is_self",
"core::matrix::transposition_tests::tr_mul_is_transpose_then_mul",
"core::matrix::vector_index_mut",
"core::matrix::zip_map",
"core::matrix::transposition_tests::transpose_transpose_is_self",
"core::matrix_slice::col_slice_mut",
"core::matrix_slice::columns_out_of_bounds",
"core::matrix_slice::column_out_of_bounds",
"core::matrix::transposition_tests::transpose_transpose_is_id_dyn",
"core::matrix_slice::columns_range_pair",
"core::matrix_slice::columns_with_step_out_of_bounds",
"core::matrix_slice::nested_row_slices",
"core::matrix_slice::nested_fixed_slices",
"core::matrix_slice::new_slice",
"core::matrix_slice::nested_slices",
"core::matrix_slice::row_out_of_bounds",
"core::matrix_slice::new_slice_mut",
"core::matrix_slice::row_slice_mut",
"core::matrix_slice::rows_out_of_bounds",
"core::matrix_slice::rows_range_pair",
"core::matrix_slice::rows_with_step_out_of_bounds",
"core::matrix_slice::slice_mut",
"core::matrix_slice::slice_out_of_bounds",
"core::matrix_slice::slice_with_steps_out_of_bounds",
"core::mint::mint_matrix_conversion_2_2",
"core::mint::mint_matrix_conversion_2_3",
"core::mint::mint_matrix_conversion_3_3",
"core::mint::mint_matrix_conversion_3_4",
"core::mint::mint_matrix_conversion_4_4",
"core::mint::mint_quaternion_conversions",
"core::mint::mint_vector_conversion_2",
"core::mint::mint_vector_conversion_3",
"core::mint::mint_vector_conversion_4",
"core::serde::serde_flat",
"core::serde::serde_dmatrix",
"core::serde::serde_isometry2",
"core::serde::serde_isometry3",
"core::serde::serde_isometry_matrix2",
"core::serde::serde_isometry_matrix3",
"core::serde::serde_matrix3x4",
"core::serde::serde_point2",
"core::serde::serde_point3",
"core::matrix::finite_dim_inner_space_tests::orthonormalize3",
"core::matrix_slice::nested_col_slices",
"core::serde::serde_quaternion",
"core::serde::serde_rotation2",
"core::serde::serde_rotation3",
"core::serde::serde_similarity2",
"core::serde::serde_similarity3",
"core::serde::serde_similarity_matrix2",
"core::serde::serde_similarity_matrix3",
"core::serde::serde_translation2",
"core::serde::serde_translation3",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim6",
"geometry::isometry::append_rotation_wrt_point_to_id",
"geometry::isometry::inverse_is_parts_inversion",
"geometry::isometry::composition2",
"geometry::isometry::inverse_is_identity",
"geometry::isometry::look_at_rh_3",
"geometry::isometry::rotation_wrt_point_invariance",
"geometry::point::point_clone",
"geometry::point::point_coordinates",
"geometry::point::point_ops",
"geometry::point::point_scale",
"geometry::isometry::multiply_equals_alga_transform",
"geometry::point::point_vector_sum",
"geometry::point::to_homogeneous",
"geometry::projection::orthographic_inverse",
"geometry::isometry::observer_frame_3",
"geometry::projection::perspective_inverse",
"geometry::point::point_sub",
"geometry::projection::quickcheck_tests::orthographic_project_unproject",
"geometry::projection::quickcheck_tests::perspective_project_unproject",
"geometry::quaternion::euler_angles",
"geometry::quaternion::from_euler_angles",
"geometry::isometry::composition3",
"geometry::quaternion::unit_quaternion_double_covering",
"core::matrix::finite_dim_inner_space_tests::orthonormalize4",
"geometry::quaternion::unit_quaternion_inv",
"geometry::quaternion::unit_quaternion_mul_vector",
"geometry::rotation::angle_2",
"geometry::rotation::angle_3",
"geometry::rotation::quaternion_euler_angles_issue_494",
"geometry::rotation::quickcheck_tests::angle_is_commutative_3",
"geometry::quaternion::unit_quaternion_rotation_conversion",
"geometry::rotation::quickcheck_tests::angle_is_commutative_2",
"geometry::rotation::quickcheck_tests::euler_angles_gimble_lock",
"geometry::rotation::quickcheck_tests::euler_angles",
"geometry::rotation::quickcheck_tests::new_rotation_2",
"geometry::quaternion::unit_quaternion_transformation",
"core::blas::ger_symm",
"geometry::rotation::quickcheck_tests::powf_rotation_2",
"geometry::rotation::quickcheck_tests::new_rotation_3",
"geometry::rotation::quickcheck_tests::from_euler_angles",
"geometry::rotation::quickcheck_tests::powf_rotation_3",
"geometry::rotation::quickcheck_tests::rotation_between_2",
"core::blas::gemv_symm",
"geometry::rotation::quickcheck_tests::rotation_between_3",
"geometry::rotation::quickcheck_tests::rotation_between_is_anticommutative_2",
"geometry::rotation::quickcheck_tests::rotation_between_is_anticommutative_3",
"geometry::rotation::quickcheck_tests::rotation_between_is_identity",
"geometry::rotation::quickcheck_tests::rotation_inv_2",
"geometry::similarity::inverse_is_parts_inversion",
"geometry::rotation::quickcheck_tests::rotation_inv_3",
"geometry::unit_complex::unit_complex_inv",
"geometry::isometry::all_op_exist",
"geometry::unit_complex::unit_complex_rotation_conversion",
"geometry::unit_complex::all_op_exist",
"geometry::unit_complex::unit_complex_mul_vector",
"geometry::similarity::multiply_equals_alga_transform",
"geometry::unit_complex::unit_complex_transformation",
"linalg::bidiagonal::bidiagonal_identity",
"geometry::quaternion::all_op_exist",
"geometry::similarity::inverse_is_identity",
"linalg::balancing::balancing_parlett_reinsch_static",
"linalg::bidiagonal::complex::bidiagonal_static_square_2x2",
"linalg::balancing::balancing_parlett_reinsch",
"core::matrix::finite_dim_inner_space_tests::orthonormalize5",
"linalg::bidiagonal::complex::bidiagonal_static_5_3",
"linalg::bidiagonal::complex::bidiagonal_static_3_5",
"linalg::bidiagonal::complex::bidiagonal_static_square",
"linalg::bidiagonal::complex::bidiagonal",
"linalg::bidiagonal::f64::bidiagonal_static_square_2x2",
"linalg::bidiagonal::f64::bidiagonal_static_5_3",
"linalg::bidiagonal::f64::bidiagonal_static_3_5",
"linalg::bidiagonal::f64::bidiagonal",
"linalg::bidiagonal::f64::bidiagonal_static_square",
"linalg::cholesky::complex::cholesky_inverse_static",
"linalg::cholesky::complex::cholesky_static",
"linalg::cholesky::complex::cholesky_solve_static",
"core::blas::quadform_tr",
"linalg::cholesky::f64::cholesky_inverse_static",
"geometry::similarity::all_op_exist",
"linalg::convolution::convolve_full_check",
"linalg::convolution::convolve_same_check",
"linalg::convolution::convolve_valid_check",
"core::matrix::finite_dim_inner_space_tests::orthonormalize6",
"linalg::cholesky::f64::cholesky_static",
"linalg::cholesky::f64::cholesky_solve_static",
"geometry::similarity::composition",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_static_square_2x2",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_static_square_3x3",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_static_square_4x4",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_static_square_2x2",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_static_square_3x3",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_static_square_4x4",
"linalg::eigen::symmetric_eigen_singular_24x24",
"linalg::full_piv_lu::full_piv_lu_simple",
"linalg::full_piv_lu::full_piv_lu_simple_with_pivot",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen_singular",
"linalg::eigen::quickcheck_tests::f64::symmetric_eigen_singular",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_inverse_static",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_static_3_5",
"linalg::eigen::quickcheck_tests::complex::symmetric_eigen",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_solve_static",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_static_5_3",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_static_square",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_inverse_static",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_solve_static",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_static_3_5",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_static_5_3",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_static_square",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_inverse",
"linalg::hessenberg::complex::hessenberg_static",
"linalg::hessenberg::complex::hessenberg_static_mat2",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_inverse",
"linalg::cholesky::f64::cholesky",
"linalg::hessenberg::f64::hessenberg_static",
"linalg::hessenberg::hessenberg_simple",
"linalg::inverse::matrix1_try_inverse",
"linalg::inverse::matrix1_try_inverse_scaled_identity",
"linalg::inverse::matrix2_try_inverse",
"linalg::inverse::matrix2_try_inverse_scaled_identity",
"linalg::inverse::matrix3_try_inverse",
"linalg::inverse::matrix3_try_inverse_scaled_identity",
"linalg::inverse::matrix4_try_inverse_issue_214",
"linalg::inverse::matrix5_try_inverse",
"linalg::inverse::matrix5_try_inverse_scaled_identity",
"linalg::hessenberg::f64::hessenberg_static_mat2",
"linalg::lu::lu_simple",
"linalg::lu::lu_simple_with_pivot",
"linalg::lu::quickcheck_tests::complex::lu",
"linalg::lu::quickcheck_tests::complex::lu_inverse_static",
"core::blas::quadform",
"linalg::lu::quickcheck_tests::complex::lu_solve_static",
"linalg::lu::quickcheck_tests::complex::lu_static_3_5",
"linalg::lu::quickcheck_tests::complex::lu_static_5_3",
"linalg::lu::quickcheck_tests::complex::lu_static_square",
"linalg::lu::quickcheck_tests::f64::lu",
"linalg::lu::quickcheck_tests::complex::lu_inverse",
"linalg::lu::quickcheck_tests::f64::lu_inverse_static",
"linalg::lu::quickcheck_tests::f64::lu_inverse",
"linalg::lu::quickcheck_tests::f64::lu_solve_static",
"linalg::lu::quickcheck_tests::f64::lu_static_3_5",
"linalg::lu::quickcheck_tests::f64::lu_static_5_3",
"linalg::lu::quickcheck_tests::f64::lu_static_square",
"linalg::qr::complex::qr",
"linalg::cholesky::f64::cholesky_inverse",
"linalg::qr::complex::qr_inverse",
"linalg::qr::complex::qr_inverse_static",
"linalg::qr::complex::qr_solve_static",
"linalg::qr::complex::qr_static_3_5",
"linalg::qr::complex::qr_static_5_3",
"linalg::cholesky::f64::cholesky_solve",
"linalg::qr::f64::qr",
"linalg::qr::complex::qr_static_square",
"linalg::qr::f64::qr_inverse_static",
"linalg::qr::f64::qr_inverse",
"linalg::qr::f64::qr_solve_static",
"linalg::qr::f64::qr_static_3_5",
"linalg::qr::f64::qr_static_5_3",
"linalg::qr::f64::qr_static_square",
"linalg::full_piv_lu::quickcheck_tests::f64::full_piv_lu_solve",
"linalg::schur::quickcheck_tests::complex::schur_static_mat2",
"linalg::schur::quickcheck_tests::complex::schur",
"linalg::schur::quickcheck_tests::complex::schur_static_mat3",
"linalg::schur::quickcheck_tests::complex::schur_static_mat4",
"linalg::schur::quickcheck_tests::f64::schur_static_mat2",
"linalg::schur::quickcheck_tests::f64::schur_static_mat3",
"linalg::lu::quickcheck_tests::f64::lu_solve",
"linalg::schur::schur_simpl_mat3",
"linalg::schur::schur_singular",
"linalg::schur::schur_static_mat3_fail",
"linalg::schur::schur_static_mat4_fail",
"linalg::schur::schur_static_mat4_fail2",
"linalg::schur::quickcheck_tests::f64::schur_static_mat4",
"linalg::solve::complex::solve_lower_triangular",
"linalg::solve::complex::solve_upper_triangular",
"linalg::solve::complex::tr_solve_lower_triangular",
"linalg::solve::complex::tr_solve_upper_triangular",
"linalg::solve::f64::solve_lower_triangular",
"linalg::solve::f64::solve_upper_triangular",
"linalg::solve::f64::tr_solve_lower_triangular",
"linalg::solve::f64::tr_solve_upper_triangular",
"linalg::svd::quickcheck_tests::complex::svd",
"linalg::svd::quickcheck_tests::complex::svd_pseudo_inverse",
"linalg::svd::quickcheck_tests::complex::svd_static_2_5",
"linalg::svd::quickcheck_tests::complex::svd_static_3_5",
"linalg::svd::quickcheck_tests::complex::svd_static_5_2",
"linalg::svd::quickcheck_tests::complex::svd_static_5_3",
"linalg::schur::quickcheck_tests::f64::schur",
"linalg::svd::quickcheck_tests::complex::svd_static_square_2x2",
"linalg::svd::quickcheck_tests::complex::svd_static_square",
"linalg::svd::quickcheck_tests::f64::svd",
"linalg::svd::quickcheck_tests::f64::svd_pseudo_inverse",
"linalg::svd::quickcheck_tests::f64::svd_static_2_5",
"linalg::svd::quickcheck_tests::f64::svd_static_3_5",
"linalg::svd::quickcheck_tests::f64::svd_static_5_2",
"linalg::svd::quickcheck_tests::f64::svd_static_5_3",
"linalg::svd::quickcheck_tests::f64::svd_static_square",
"linalg::svd::quickcheck_tests::complex::svd_solve",
"linalg::svd::quickcheck_tests::f64::svd_static_square_2x2",
"linalg::svd::svd_err",
"linalg::svd::svd_fail",
"linalg::svd::svd_identity",
"linalg::svd::svd_singular",
"linalg::svd::svd_singular_horizontal",
"linalg::svd::svd_singular_vertical",
"linalg::svd::svd_zeros",
"linalg::svd::svd_with_delimited_subproblem",
"linalg::tridiagonal::complex::symm_tridiagonal_singular",
"linalg::tridiagonal::complex::symm_tridiagonal_static_square",
"linalg::tridiagonal::complex::symm_tridiagonal_static_square_2x2",
"linalg::svd::quickcheck_tests::f64::svd_solve",
"linalg::tridiagonal::f64::symm_tridiagonal_singular",
"linalg::tridiagonal::f64::symm_tridiagonal_static_square",
"linalg::tridiagonal::f64::symm_tridiagonal_static_square_2x2",
"linalg::hessenberg::f64::hessenberg",
"linalg::qr::f64::qr_solve",
"linalg::cholesky::complex::cholesky",
"linalg::full_piv_lu::quickcheck_tests::complex::full_piv_lu_solve",
"linalg::lu::quickcheck_tests::complex::lu_solve",
"linalg::cholesky::complex::cholesky_solve",
"linalg::tridiagonal::f64::symm_tridiagonal",
"linalg::cholesky::complex::cholesky_inverse",
"linalg::qr::complex::qr_solve",
"linalg::hessenberg::complex::hessenberg",
"linalg::tridiagonal::complex::symm_tridiagonal",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::icamax_full (line 201)",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::dotc (line 410)",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::tr_dot (line 434)",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::dot (line 379)",
"src/base/blas.rs - base::blas::Matrix<N, R, C, S>::iamax_full (line 238)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::gemm_ad (line 1151)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::gemm (line 961)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::ger_symm (line 1249)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::hegerc (line 1321)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::gerc (line 927)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::ger (line 895)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::gemm_tr (line 1093)",
"src/base/blas.rs - base::blas::Matrix<N, R1, C1, S>::syger (line 1286)",
"src/base/blas.rs - base::blas::SquareMatrix<N, D1, S>::quadform_tr (line 1412)",
"src/base/blas.rs - base::blas::SquareMatrix<N, D1, S>::quadform (line 1502)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::axpy (line 501)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::gemv (line 536)",
"src/base/blas.rs - base::blas::SquareMatrix<N, D1, S>::quadform_tr_with_workspace (line 1358)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::argmin (line 127)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::hegemv (line 707)",
"src/base/blas.rs - base::blas::SquareMatrix<N, D1, S>::quadform_with_workspace (line 1448)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::argmax (line 56)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::gemv_ad (line 828)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::gemv_tr (line 793)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::icamax (line 23)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::iamax (line 98)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::iamin (line 169)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::sygemv (line 664)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R, C, S>::abs (line 22)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::imax (line 84)",
"src/base/blas.rs - base::blas::Vector<N, D, S>::imin (line 155)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_div (line 54)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_div_assign (line 114)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::cmpy (line 79)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::cdpy (line 79)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_div_mut (line 134)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_mul (line 54)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_mul_assign (line 114)",
"src/base/componentwise.rs - base::componentwise::Matrix<N, R1, C1, SA>::component_mul_mut (line 134)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_diagonal_element (line 503)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_fn (line 451)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_partial_diagonal (line 528)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::identity (line 480)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_column_slice (line 640)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_element (line 343)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_iterator (line 423)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::zeros (line 395)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_row_slice (line 613)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::repeat (line 370)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, C>::from_vec (line 668)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_diagonal_element (line 503)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_column_slice (line 640)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_element (line 343)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_fn (line 451)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_partial_diagonal (line 528)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_iterator (line 423)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::identity (line 480)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::zeros (line 395)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_row_slice (line 613)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::repeat (line 370)",
"src/base/construction.rs - base::construction::MatrixMN<N, Dynamic, Dynamic>::from_vec (line 668)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_diagonal_element (line 503)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_columns (line 207)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_column_slice (line 640)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_element (line 343)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_fn (line 451)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_partial_diagonal (line 528)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::identity (line 480)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_iterator (line 423)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_rows (line 167)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_vec (line 668)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::zeros (line 395)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_vec_generic (line 266)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::from_row_slice (line 613)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, C>::repeat (line 370)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_diagonal_element (line 503)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_element (line 343)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_column_slice (line 640)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_fn (line 451)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_partial_diagonal (line 528)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::zeros (line 395)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::identity (line 480)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_iterator (line 423)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::repeat (line 370)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_vec (line 668)",
"src/base/construction.rs - base::construction::MatrixMN<N, R, Dynamic>::from_row_slice (line 613)",
"src/base/construction.rs - base::construction::MatrixN<N, D>::from_diagonal (line 293)",
"src/base/edition.rs - base::edition::Matrix<N, Dynamic, U1, S>::extend (line 996)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 1021)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 1043)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 1055)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 969)",
"src/base/edition.rs - base::edition::Matrix<N, R, Dynamic, S>::extend (line 949)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 339)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 364)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 374)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 351)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 386)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 397)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::len (line 162)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 413)",
"src/base/indexing.rs - base::indexing::Matrix<N, R, C, S> (line 424)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::ncols (line 203)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::column_iter_mut (line 665)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::nrows (line 190)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::column_iter (line 267)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::shape (line 176)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::iter (line 232)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::strides (line 216)",
"src/base/matrix.rs - base::matrix::Unit<Vector<N, D, S>>::slerp (line 1600)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::row_iter_mut (line 645)",
"src/base/matrix.rs - base::matrix::Matrix<N, R, C, S>::row_iter (line 252)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::amax (line 889)",
"src/base/norm.rs - base::norm::Matrix<N, R, C, S>::apply_metric_distance (line 151)",
"src/base/matrix.rs - base::matrix::Vector<N, D, S>::lerp (line 1581)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::amin (line 930)",
"src/base/norm.rs - base::norm::Matrix<N, R, C, S>::apply_norm (line 134)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::camax (line 902)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::camin (line 943)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::max (line 917)",
"src/base/ops.rs - base::ops::Matrix<N, R, C, S>::min (line 958)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 443)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 403)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::column_sum (line 119)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 393)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::column_mean (line 294)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::mean (line 238)",
"src/base/ops.rs - base::ops::MatrixMN<N, Dynamic, C>::sum (line 433)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::column_variance (line 202)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_mean (line 260)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_mean_tr (line 277)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_sum (line 85)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_sum_tr (line 102)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_variance (line 168)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::row_variance_tr (line 185)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::sum (line 67)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_rotation_mut (line 197)",
"src/base/statistics.rs - base::statistics::Matrix<N, R, C, S>::variance (line 144)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_rotation_wrt_center_mut (line 242)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_rotation_wrt_point_mut (line 219)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::append_translation_mut (line 178)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::from_parts (line 114)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse_mut (line 157)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse (line 137)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse_transform_point (line 309)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::to_homogeneous (line 361)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::inverse_transform_vector (line 333)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::transform_point (line 264)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<N, D, R>::transform_vector (line 287)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, D, R>::identity (line 29)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, D, R>::rotation_wrt_point (line 50)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U2, Rotation2<N>>::new (line 118)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U2, UnitComplex<N>>::new (line 153)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, Rotation3<N>>::face_towards (line 241)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, Rotation3<N>>::look_at_rh (line 292)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, Rotation3<N>>::look_at_lh (line 335)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, UnitQuaternion<N>>::look_at_lh (line 335)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, UnitQuaternion<N>>::face_towards (line 241)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, Rotation3<N>>::new (line 189)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::as_matrix (line 225)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::bottom (line 329)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::as_projective (line 244)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::from_matrix_unchecked (line 125)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, UnitQuaternion<N>>::new (line 189)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::into_inner (line 270)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::left (line 297)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<N, U3, UnitQuaternion<N>>::look_at_rh (line 292)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::inverse (line 170)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_bottom (line 531)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_bottom_and_top (line 632)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::right (line 313)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_left (line 493)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::project_point (line 395)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::new (line 70)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::project_vector (line 468)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_zfar (line 588)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_top (line 550)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_right (line 512)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_left_and_right (line 607)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_znear (line 569)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::set_znear_and_zfar (line 657)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::to_projective (line 257)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::top (line 345)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::zfar (line 377)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::to_homogeneous (line 206)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::znear (line 361)",
"src/geometry/point.rs - geometry::point::Point<N, D>::len (line 136)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<N>::unproject_point (line 430)",
"src/geometry/point.rs - geometry::point::Point<N, D>::iter_mut (line 184)",
"src/geometry/point.rs - geometry::point::Point<N, D>::iter (line 161)",
"src/geometry/point.rs - geometry::point::Point<N, D>::to_homogeneous (line 103)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, D>::origin (line 28)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, D>::from_homogeneous (line 71)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U1>::new (line 163)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U2>::new (line 163)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, D>::from_slice (line 49)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U3>::new (line 163)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U6>::new (line 163)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U4>::new (line 163)",
"src/geometry/point_construction.rs - geometry::point_construction::Point<N, U5>::new (line 163)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::as_vector (line 224)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::as_vector_mut (line 493)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::acosh (line 806)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::acos (line 663)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::conjugate (line 136)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::atanh (line 839)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::asinh (line 773)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::conjugate_mut (line 528)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::atan (line 737)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::asin (line 701)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::cos (line 645)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::cosh (line 790)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::dot (line 299)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::exp (line 435)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::inner (line 315)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::exp_eps (line 450)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::lerp (line 181)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::magnitude (line 256)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::norm (line 239)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::ln (line 417)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::magnitude_squared (line 286)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::norm_squared (line 270)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::normalize (line 115)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::normalize_mut (line 573)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::outer (line 333)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::powf (line 479)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::polar_decomposition (line 391)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::reject (line 371)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::scalar (line 211)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::project (line 352)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::right_div (line 628)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::sin (line 683)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::tan (line 721)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::sinh (line 757)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::tanh (line 823)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::vector (line 196)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::try_inverse_mut (line 544)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::vector_mut (line 507)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<N>::try_inverse (line 150)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::angle (line 939)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::angle_to (line 1000)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::axis (line 1128)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::axis_angle (line 1174)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::conjugate (line 969)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::euler_angles (line 1307)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse (line 984)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse_transform_vector (line 1410)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse_transform_point (line 1388)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::inverse_mut (line 1111)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::lerp (line 1036)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::ln (line 1205)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::quaternion (line 956)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::nlerp (line 1052)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::powf (line 1227)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::rotation_to (line 1018)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::to_homogeneous (line 1325)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::to_rotation_matrix (line 1250)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::scaled_axis (line 1153)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<N>::from_parts (line 59)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::transform_vector (line 1368)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<N>::transform_point (line 1348)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<N>::identity (line 94)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<N>::new (line 36)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_euler_angles (line 217)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::face_towards (line 475)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_axis_angle (line 176)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_scaled_axis (line 630)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_rotation_matrix (line 245)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::from_scaled_axis_eps (line 658)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::look_at_lh (line 547)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::identity (line 155)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::look_at_rh (line 516)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::new (line 571)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::new_eps (line 600)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::from_matrix_unchecked (line 227)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::scaled_rotation_between (line 357)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::rotation_between_axis (line 392)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::into_inner (line 154)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::rotation_between (line 335)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<N>::scaled_rotation_between_axis (line 417)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::matrix (line 114)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse_transform_vector (line 420)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse_transform_point (line 401)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse (line 282)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::inverse_mut (line 332)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::to_homogeneous (line 189)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transform_point (line 363)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::angle (line 149)",
"src/geometry/rotation_construction.rs - geometry::rotation_construction::Rotation<N, D>::identity (line 19)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transform_vector (line 382)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::angle_to (line 163)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transpose_mut (line 305)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::powf (line 211)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<N, D>::transpose (line 259)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::new (line 28)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::rotation_to (line 180)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::angle (line 673)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::rotation_between (line 101)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::angle_to (line 763)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::axis_angle (line 737)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::axis (line 690)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<N>::scaled_rotation_between (line 123)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::from_euler_angles (line 416)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::euler_angles (line 456)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::face_towards (line 505)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::from_axis_angle (line 364)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::from_scaled_axis (line 341)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::look_at_rh (line 552)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::powf (line 797)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::look_at_lh (line 583)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::new (line 266)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::scaled_axis (line 716)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::rotation_to (line 780)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::rotation_between (line 607)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::inverse_transform_point (line 288)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<N>::scaled_rotation_between (line 629)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::transform_vector (line 268)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::transform_point (line 247)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<N, D, R>::inverse_transform_vector (line 308)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, D, R>::rotation_wrt_point (line 87)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U2, Rotation2<N>>::new (line 135)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U2, UnitComplex<N>>::new (line 158)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, D, R>::identity (line 31)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::look_at_lh (line 312)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::face_towards (line 224)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::look_at_rh (line 274)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::look_at_lh (line 312)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::face_towards (line 224)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::into_inner (line 246)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, Rotation3<N>>::new (line 185)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::look_at_rh (line 274)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::matrix (line 271)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<N, U3, UnitQuaternion<N>>::new (line 185)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::inverse (line 385)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::inverse_mut (line 437)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::to_homogeneous (line 335)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::matrix_mut_unchecked (line 291)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::inverse_transform_point (line 220)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::inverse (line 121)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::transform_point (line 203)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::try_inverse (line 353)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::inverse_mut (line 173)",
"src/geometry/translation.rs - geometry::translation::Translation<N, D>::to_homogeneous (line 141)",
"src/geometry/transform.rs - geometry::transform::Transform<N, D, C>::try_inverse_mut (line 408)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U2>::new (line 85)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U1>::new (line 85)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U3>::new (line 85)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::complex (line 86)",
"src/geometry/transform_construction.rs - geometry::transform_construction::Transform<N, D, C>::identity (line 18)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, D>::identity (line 24)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::angle (line 16)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U4>::new (line 85)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::angle_to (line 133)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U5>::new (line 85)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<N, U6>::new (line 85)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::conjugate (line 102)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::cos_angle (line 43)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::conjugate_mut (line 169)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse (line 117)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse_mut (line 188)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::sin_angle (line 29)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::powf (line 208)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse_transform_point (line 294)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::inverse_transform_vector (line 312)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::rotation_to (line 151)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::to_rotation_matrix (line 223)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::to_homogeneous (line 241)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::transform_point (line 260)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::from_angle (line 56)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<N>::transform_vector (line 278)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::from_cos_sin_unchecked (line 77)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::identity (line 19)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::from_rotation_matrix (line 120)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::new (line 36)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::rotation_between (line 162)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::rotation_between_axis (line 219)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::scaled_rotation_between (line 184)",
"src/lib.rs - (line 26)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<N>::scaled_rotation_between_axis (line 244)"
] |
[] |
[] |
|
dimforge/nalgebra
| 1,384
|
dimforge__nalgebra-1384
|
[
"1380"
] |
a803815bd1d22a052690cfde3ff7fae26cd91152
|
diff --git a/src/linalg/inverse.rs b/src/linalg/inverse.rs
--- a/src/linalg/inverse.rs
+++ b/src/linalg/inverse.rs
@@ -145,13 +145,44 @@ where
{
let m = m.as_slice();
- out[(0, 0)] = m[5].clone() * m[10].clone() * m[15].clone()
+ let cofactor00 = m[5].clone() * m[10].clone() * m[15].clone()
- m[5].clone() * m[11].clone() * m[14].clone()
- m[9].clone() * m[6].clone() * m[15].clone()
+ m[9].clone() * m[7].clone() * m[14].clone()
+ m[13].clone() * m[6].clone() * m[11].clone()
- m[13].clone() * m[7].clone() * m[10].clone();
+ let cofactor01 = -m[4].clone() * m[10].clone() * m[15].clone()
+ + m[4].clone() * m[11].clone() * m[14].clone()
+ + m[8].clone() * m[6].clone() * m[15].clone()
+ - m[8].clone() * m[7].clone() * m[14].clone()
+ - m[12].clone() * m[6].clone() * m[11].clone()
+ + m[12].clone() * m[7].clone() * m[10].clone();
+
+ let cofactor02 = m[4].clone() * m[9].clone() * m[15].clone()
+ - m[4].clone() * m[11].clone() * m[13].clone()
+ - m[8].clone() * m[5].clone() * m[15].clone()
+ + m[8].clone() * m[7].clone() * m[13].clone()
+ + m[12].clone() * m[5].clone() * m[11].clone()
+ - m[12].clone() * m[7].clone() * m[9].clone();
+
+ let cofactor03 = -m[4].clone() * m[9].clone() * m[14].clone()
+ + m[4].clone() * m[10].clone() * m[13].clone()
+ + m[8].clone() * m[5].clone() * m[14].clone()
+ - m[8].clone() * m[6].clone() * m[13].clone()
+ - m[12].clone() * m[5].clone() * m[10].clone()
+ + m[12].clone() * m[6].clone() * m[9].clone();
+
+ let det = m[0].clone() * cofactor00.clone()
+ + m[1].clone() * cofactor01.clone()
+ + m[2].clone() * cofactor02.clone()
+ + m[3].clone() * cofactor03.clone();
+
+ if det.is_zero() {
+ return false;
+ }
+ out[(0, 0)] = cofactor00;
+
out[(1, 0)] = -m[1].clone() * m[10].clone() * m[15].clone()
+ m[1].clone() * m[11].clone() * m[14].clone()
+ m[9].clone() * m[2].clone() * m[15].clone()
diff --git a/src/linalg/inverse.rs b/src/linalg/inverse.rs
--- a/src/linalg/inverse.rs
+++ b/src/linalg/inverse.rs
@@ -173,12 +204,7 @@ where
- m[9].clone() * m[2].clone() * m[7].clone()
+ m[9].clone() * m[3].clone() * m[6].clone();
- out[(0, 1)] = -m[4].clone() * m[10].clone() * m[15].clone()
- + m[4].clone() * m[11].clone() * m[14].clone()
- + m[8].clone() * m[6].clone() * m[15].clone()
- - m[8].clone() * m[7].clone() * m[14].clone()
- - m[12].clone() * m[6].clone() * m[11].clone()
- + m[12].clone() * m[7].clone() * m[10].clone();
+ out[(0, 1)] = cofactor01;
out[(1, 1)] = m[0].clone() * m[10].clone() * m[15].clone()
- m[0].clone() * m[11].clone() * m[14].clone()
diff --git a/src/linalg/inverse.rs b/src/linalg/inverse.rs
--- a/src/linalg/inverse.rs
+++ b/src/linalg/inverse.rs
@@ -201,12 +227,7 @@ where
+ m[8].clone() * m[2].clone() * m[7].clone()
- m[8].clone() * m[3].clone() * m[6].clone();
- out[(0, 2)] = m[4].clone() * m[9].clone() * m[15].clone()
- - m[4].clone() * m[11].clone() * m[13].clone()
- - m[8].clone() * m[5].clone() * m[15].clone()
- + m[8].clone() * m[7].clone() * m[13].clone()
- + m[12].clone() * m[5].clone() * m[11].clone()
- - m[12].clone() * m[7].clone() * m[9].clone();
+ out[(0, 2)] = cofactor02;
out[(1, 2)] = -m[0].clone() * m[9].clone() * m[15].clone()
+ m[0].clone() * m[11].clone() * m[13].clone()
diff --git a/src/linalg/inverse.rs b/src/linalg/inverse.rs
--- a/src/linalg/inverse.rs
+++ b/src/linalg/inverse.rs
@@ -222,12 +243,7 @@ where
+ m[12].clone() * m[1].clone() * m[7].clone()
- m[12].clone() * m[3].clone() * m[5].clone();
- out[(0, 3)] = -m[4].clone() * m[9].clone() * m[14].clone()
- + m[4].clone() * m[10].clone() * m[13].clone()
- + m[8].clone() * m[5].clone() * m[14].clone()
- - m[8].clone() * m[6].clone() * m[13].clone()
- - m[12].clone() * m[5].clone() * m[10].clone()
- + m[12].clone() * m[6].clone() * m[9].clone();
+ out[(0, 3)] = cofactor03;
out[(3, 2)] = -m[0].clone() * m[5].clone() * m[11].clone()
+ m[0].clone() * m[7].clone() * m[9].clone()
diff --git a/src/linalg/inverse.rs b/src/linalg/inverse.rs
--- a/src/linalg/inverse.rs
+++ b/src/linalg/inverse.rs
@@ -257,21 +273,12 @@ where
+ m[8].clone() * m[1].clone() * m[6].clone()
- m[8].clone() * m[2].clone() * m[5].clone();
- let det = m[0].clone() * out[(0, 0)].clone()
- + m[1].clone() * out[(0, 1)].clone()
- + m[2].clone() * out[(0, 2)].clone()
- + m[3].clone() * out[(0, 3)].clone();
+ let inv_det = T::one() / det;
- if !det.is_zero() {
- let inv_det = T::one() / det;
-
- for j in 0..4 {
- for i in 0..4 {
- out[(i, j)] *= inv_det.clone();
- }
+ for j in 0..4 {
+ for i in 0..4 {
+ out[(i, j)] *= inv_det.clone();
}
- true
- } else {
- false
}
+ true
}
|
diff --git a/tests/core/matrix.rs b/tests/core/matrix.rs
--- a/tests/core/matrix.rs
+++ b/tests/core/matrix.rs
@@ -1263,6 +1263,16 @@ fn column_iterator_double_ended_mut() {
assert_eq!(col_iter_mut.next(), None);
}
+#[test]
+fn test_inversion_failure_leaves_matrix4_unchanged() {
+ let mut mat = na::Matrix4::new(
+ 1.0, 2.0, 3.0, 4.0, 2.0, 4.0, 6.0, 8.0, 3.0, 6.0, 9.0, 12.0, 4.0, 8.0, 12.0, 16.0,
+ );
+ let expected = mat.clone();
+ assert!(!mat.try_inverse_mut());
+ assert_eq!(mat, expected);
+}
+
#[test]
#[cfg(feature = "rayon")]
fn parallel_column_iteration() {
|
Inverting a 4x4 matrix with `try_inverse_mut` doesn't leave `self` unchanged if the inversion fails.
Calling `try_inverse_mut` on a 4x4 matrix uses [`do_inverse4`](https://github.com/dimforge/nalgebra/blob/a803815bd1d22a052690cfde3ff7fae26cd91152/src/linalg/inverse.rs#L139) which modifies `out` before checking the determinant.
|
2024-04-19T23:01:31Z
|
0.32
|
2024-05-05T10:05:36Z
|
a803815bd1d22a052690cfde3ff7fae26cd91152
|
[
"core::matrix::test_inversion_failure_leaves_matrix4_unchanged"
] |
[
"base::indexing::dimrange_range_usize",
"base::indexing::dimrange_rangefrom_dimname",
"base::indexing::dimrange_rangefrom_usize",
"base::indexing::dimrange_rangefull",
"base::indexing::dimrange_rangeinclusive_usize",
"base::indexing::dimrange_rangeto_usize",
"base::indexing::dimrange_usize",
"base::indexing::dimrange_rangetoinclusive_usize",
"base::matrix::tests::empty_display",
"base::matrix::tests::lower_exp",
"linalg::exp::tests::one_norm",
"geometry::transform::tests::checks_homogeneous_invariants_of_square_identity_matrix",
"linalg::symmetric_eigen::test::wilkinson_shift_zero",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_det",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diag_diff_and_zero_off_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_off_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_trace",
"geometry::quaternion_construction::tests::random_unit_quats_are_unit",
"linalg::symmetric_eigen::test::wilkinson_shift_random",
"core::conversion::array_matrix_conversion_2_2",
"core::conversion::array_matrix_conversion_2_4",
"core::conversion::array_matrix_conversion_2_3",
"core::cg::test_scaling_wrt_point_3",
"core::cg::test_scaling_wrt_point_2",
"core::cg::test_scaling_wrt_point_1",
"core::conversion::array_matrix_conversion_2_5",
"core::conversion::array_matrix_conversion_2_6",
"core::conversion::array_matrix_conversion_3_4",
"core::blas::gemm_noncommutative",
"core::conversion::array_matrix_conversion_3_5",
"core::conversion::array_matrix_conversion_3_2",
"core::conversion::array_matrix_conversion_3_6",
"core::conversion::array_matrix_conversion_4_2",
"core::conversion::array_matrix_conversion_4_3",
"core::conversion::array_matrix_conversion_4_4",
"core::conversion::array_matrix_conversion_3_3",
"core::conversion::array_matrix_conversion_4_6",
"core::conversion::array_matrix_conversion_5_3",
"core::conversion::array_matrix_conversion_5_4",
"core::conversion::array_matrix_conversion_5_5",
"core::conversion::array_matrix_conversion_5_6",
"core::conversion::array_matrix_conversion_4_5",
"core::conversion::array_matrix_conversion_6_2",
"core::conversion::array_matrix_conversion_6_3",
"core::conversion::array_matrix_conversion_6_4",
"core::conversion::array_matrix_conversion_6_5",
"core::conversion::array_matrix_conversion_6_6",
"core::conversion::array_row_vector_conversion_2",
"core::conversion::array_row_vector_conversion_3",
"core::conversion::array_row_vector_conversion_4",
"core::conversion::array_row_vector_conversion_6",
"core::conversion::array_vector_conversion_1",
"core::conversion::array_vector_conversion_2",
"core::conversion::array_vector_conversion_3",
"core::conversion::array_vector_conversion_4",
"core::conversion::array_vector_conversion_5",
"core::conversion::array_vector_conversion_6",
"core::conversion::array_row_vector_conversion_5",
"core::conversion::matrix_slice_from_matrix_ref",
"core::conversion::array_matrix_conversion_5_2",
"core::conversion::array_row_vector_conversion_1",
"core::edition::insert_columns_to_empty_matrix",
"core::edition::insert_columns",
"core::edition::insert_rows_to_empty_matrix",
"core::edition::insert_rows",
"core::edition::remove_columns",
"core::edition::remove_columns_at",
"core::edition::remove_rows_at",
"core::edition::remove_rows",
"core::edition::resize",
"core::edition::resize_empty_matrix",
"core::edition::swap_rows",
"core::edition::upper_lower_triangular",
"core::empty::empty_matrix_gemm",
"core::empty::empty_matrix_gemm_tr",
"core::empty::empty_matrix_mul_matrix",
"core::empty::empty_matrix_mul_vector",
"core::empty::empty_matrix_tr_mul_matrix",
"core::empty::empty_matrix_tr_mul_vector",
"core::macros::sanity_test",
"core::matrix::apply",
"core::matrix::column_iteration",
"core::matrix::column_iteration_double_ended",
"core::matrix::column_iteration_mut",
"core::matrix::column_iteration_mut_double_ended",
"core::matrix::column_iterator_double_ended_mut",
"core::matrix::components_mut",
"core::matrix::coordinates",
"core::matrix::copy_from_slice",
"core::matrix::copy_from_slice_too_large - should panic",
"core::matrix::copy_from_slice_too_small - should panic",
"core::matrix::cross_product_vector_and_row_vector",
"core::matrix::debug_output_corresponds_to_data_container",
"core::edition::swap_columns",
"core::conversion::translation_conversion",
"core::blas::blas_proptest::gemv_tr",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis1",
"core::blas::blas_proptest::ger_symm",
"core::blas::blas_proptest::gemv_symm",
"core::conversion::rotation_conversion",
"core::conversion::unit_quaternion_conversion",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis2",
"core::conversion::isometry_conversion",
"core::conversion::similarity_conversion",
"core::blas::blas_proptest::quadform_tr",
"core::matrix::from_columns",
"core::matrix::from_columns_dynamic",
"core::matrix::from_diagonal",
"core::matrix::from_not_enough_columns - should panic",
"core::matrix::from_rows",
"core::matrix::from_rows_with_different_dimensions - should panic",
"core::matrix::from_too_many_rows - should panic",
"core::matrix::identity",
"core::blas::blas_proptest::quadform",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim1",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis3",
"core::matrix::finite_dim_inner_space_tests::orthonormalize1",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis4",
"core::matrix::is_column_major",
"core::matrix::iter",
"core::matrix::iter_mut",
"core::matrix::kronecker",
"core::matrix::linear_index",
"core::matrix::map",
"core::matrix::map_with_location",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim2",
"core::matrix::finite_dim_inner_space_tests::orthonormalize3",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis5",
"core::matrix::finite_dim_inner_space_tests::orthonormalize2",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim3",
"core::matrix::parallel_column_iteration",
"core::matrix::partial_clamp",
"core::matrix::omatrix_to_string",
"core::matrix::partial_eq_shape_mismatch",
"core::matrix::partial_eq_different_types",
"core::matrix::push",
"core::matrix::partial_cmp",
"core::matrix::simple_add",
"core::matrix::set_row_column",
"core::matrix::simple_scalar_conversion",
"core::matrix::simple_scalar_mul",
"core::matrix::simple_product",
"core::matrix::simple_sum",
"core::matrix::simple_mul",
"core::matrix::swizzle",
"core::matrix::simple_transpose",
"core::matrix::simple_transpose_mut",
"core::matrix::trace",
"core::matrix::to_homogeneous",
"core::matrix::trace_panic - should panic",
"core::matrix::normalization_tests::normalized_vec_norm_is_one",
"core::matrix::finite_dim_inner_space_tests::orthonormalize4",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis6",
"core::matrix::vector_index_mut",
"core::matrix::zip_map",
"core::matrix_view::col_view_mut",
"core::matrix_view::column_out_of_bounds - should panic",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim4",
"core::matrix_view::columns_range_pair",
"core::matrix_view::columns_out_of_bounds - should panic",
"core::matrix_view::nested_col_views",
"core::matrix_view::nested_fixed_views",
"core::matrix_view::nested_row_views",
"core::matrix_view::nested_views",
"core::matrix_view::columns_with_step_out_of_bounds - should panic",
"core::matrix_view::new_from_slice",
"core::matrix_view::new_from_slice_mut",
"core::matrix_view::row_view_mut",
"core::matrix_view::row_out_of_bounds - should panic",
"core::matrix_view::rows_range_pair",
"core::matrix_view::rows_with_step_out_of_bounds - should panic",
"core::matrix_view::view_mut",
"core::matrix_view::view_out_of_bounds - should panic",
"core::matrix_view::view_with_steps_out_of_bounds - should panic",
"core::matrixcompare::assert_matrix_eq_dense_negative_comparison - should panic",
"core::matrixcompare::assert_matrix_eq_dense_positive_comparison",
"core::matrix_view::rows_out_of_bounds - should panic",
"core::matrix::parallel_column_iteration_mut",
"core::mint::mint_matrix_conversion_2_2",
"core::mint::mint_matrix_conversion_2_3",
"core::mint::mint_matrix_conversion_3_3",
"core::mint::mint_matrix_conversion_3_4",
"core::mint::mint_matrix_conversion_4_4",
"core::mint::mint_quaternion_conversions",
"core::mint::mint_vector_conversion_2",
"core::mint::mint_vector_conversion_3",
"core::mint::mint_vector_conversion_4",
"core::reshape::reshape_owned",
"core::reshape::reshape_slice",
"core::rkyv::rkyv_diff_type_matrix3x4",
"core::rkyv::rkyv_same_type_isometry3",
"core::rkyv::rkyv_same_type_isometry_matrix2",
"core::rkyv::rkyv_same_type_isometry_matrix3",
"core::rkyv::rkyv_same_type_matrix3x4",
"core::rkyv::rkyv_same_type_point2",
"core::rkyv::rkyv_same_type_point3",
"core::rkyv::rkyv_same_type_quaternion",
"core::rkyv::rkyv_same_type_rotation2",
"core::rkyv::rkyv_same_type_rotation3",
"core::rkyv::rkyv_same_type_similarity3",
"core::rkyv::rkyv_same_type_similarity_matrix2",
"core::rkyv::rkyv_same_type_similarity_matrix3",
"core::rkyv::rkyv_same_type_translation2",
"core::rkyv::rkyv_same_type_translation3",
"core::serde::deserialize_enum",
"core::serde::serde_dmatrix",
"core::matrix::normalization_tests::normalized_vec_norm_is_one_dyn",
"core::serde::serde_dmatrix_invalid_len - should panic",
"core::serde::serde_flat",
"core::serde::serde_isometry2",
"core::serde::serde_isometry3",
"core::serde::serde_isometry_matrix3",
"core::serde::serde_isometry_matrix2",
"core::serde::serde_matrix3x4",
"core::serde::serde_point2",
"core::serde::serde_point3",
"core::serde::serde_quaternion",
"core::serde::serde_rotation2",
"core::serde::serde_similarity2",
"core::serde::serde_rotation3",
"core::serde::serde_similarity3",
"core::serde::serde_similarity_matrix2",
"core::serde::serde_similarity_matrix3",
"core::serde::serde_smatrix_invalid_len - should panic",
"core::serde::serde_translation2",
"core::serde::serde_translation3",
"core::variance::test_variance_catastrophic_cancellation",
"core::matrix::transposition_tests::transpose_mut_transpose_mut_is_self",
"core::matrix::finite_dim_inner_space_tests::orthonormalize6",
"core::matrix::finite_dim_inner_space_tests::orthonormalize5",
"core::matrix::transposition_tests::transpose_transpose_is_self",
"core::matrix::transposition_tests::tr_mul_is_transpose_then_mul",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim6",
"geometry::dual_quaternion::isometry_equivalence",
"geometry::dual_quaternion::multiply_equals_alga_transform",
"geometry::dual_quaternion::inverse_is_identity",
"geometry::isometry::append_rotation_wrt_point_to_id",
"core::matrix::transposition_tests::check_transpose_components_dyn",
"geometry::dual_quaternion::composition",
"geometry::dual_quaternion::sclerp_is_not_defined_for_opposite_orientations",
"core::matrix::transposition_tests::transpose_transpose_is_id_dyn",
"core::matrixcompare::fetch_single_is_equivalent_to_index_f64",
"geometry::dual_quaternion::sclerp_is_defined_for_identical_orientations",
"geometry::point::display_fmt_respects_modifiers",
"geometry::point::point_clone",
"geometry::point::point_coordinates",
"core::matrixcompare::matrixcompare_shape_agrees_with_matrix",
"geometry::point::point_ops",
"geometry::point::point_scale",
"geometry::point::point_vector_sum",
"geometry::point::to_homogeneous",
"geometry::projection::orthographic_inverse",
"geometry::projection::perspective_inverse",
"geometry::projection::perspective_matrix_point_transformation",
"geometry::isometry::composition2",
"geometry::isometry::inverse_is_parts_inversion",
"geometry::projection::proptest_tests::orthographic_project_unproject",
"geometry::isometry::rotation_wrt_point_invariance",
"geometry::projection::proptest_tests::perspective_project_unproject",
"geometry::isometry::inverse_is_identity",
"geometry::isometry::look_at_rh_3",
"geometry::isometry::observer_frame_3",
"geometry::quaternion::euler_angles",
"geometry::quaternion::from_euler_angles",
"geometry::rotation::angle_3",
"geometry::rotation::angle_2",
"geometry::quaternion::unit_quaternion_double_covering",
"geometry::isometry::multiply_equals_alga_transform",
"geometry::quaternion::unit_quaternion_rotation_conversion",
"geometry::isometry::composition3",
"geometry::quaternion::unit_quaternion_inv",
"geometry::rotation::proptest_tests::euler_angles",
"geometry::rotation::proptest_tests::euler_angles_gimble_lock",
"geometry::rotation::proptest_tests::new_rotation_2",
"geometry::isometry::all_op_exist",
"geometry::rotation::proptest_tests::angle_is_commutative_2",
"geometry::rotation::proptest_tests::powf_rotation_2",
"geometry::rotation::proptest_tests::from_euler_angles",
"geometry::rotation::proptest_tests::new_rotation_3",
"geometry::quaternion::unit_quaternion_mul_vector",
"geometry::rotation::proptest_tests::angle_is_commutative_3",
"geometry::dual_quaternion::all_op_exist",
"geometry::quaternion::unit_quaternion_transformation",
"geometry::rotation::proptest_tests::powf_rotation_3",
"geometry::rotation::proptest_tests::rotation_inv_2",
"geometry::rotation::proptest_tests::slerp_powf_agree_2",
"geometry::rotation::proptest_tests::slerp_takes_shortest_path_2",
"geometry::rotation::proptest_tests::rotation_between_2",
"geometry::rotation::proptest_tests::rotation_between_3",
"geometry::rotation::proptest_tests::rotation_between_is_anticommutative_2",
"geometry::rotation::proptest_tests::rotation_inv_3",
"geometry::rotation::proptest_tests::rotation_between_is_anticommutative_3",
"geometry::rotation::quaternion_euler_angles_issue_494",
"geometry::rotation::proptest_tests::rotation_between_is_identity",
"geometry::quaternion::all_op_exist",
"geometry::rotation::proptest_tests::slerp_takes_shortest_path_3",
"geometry::unit_complex::unit_complex_inv",
"geometry::rotation::proptest_tests::slerp_powf_agree_3",
"geometry::unit_complex::unit_complex_rotation_conversion",
"linalg::bidiagonal::bidiagonal_identity",
"linalg::bidiagonal::bidiagonal_regression_issue_1313",
"linalg::bidiagonal::bidiagonal_regression_issue_1313_minimal",
"geometry::unit_complex::all_op_exist",
"geometry::similarity::inverse_is_parts_inversion",
"geometry::unit_complex::unit_complex_mul_vector",
"geometry::unit_complex::unit_complex_transformation",
"linalg::balancing::balancing_parlett_reinsch_static",
"geometry::similarity::inverse_is_identity",
"geometry::similarity::multiply_equals_alga_transform",
"geometry::rotation::from_rotation_matrix",
"linalg::balancing::balancing_parlett_reinsch",
"linalg::bidiagonal::proptest_tests::f64::bidiagonal_static_square_2x2",
"linalg::cholesky::cholesky_with_substitute",
"linalg::bidiagonal::proptest_tests::f64::bidiagonal_static_5_3",
"linalg::bidiagonal::proptest_tests::complex::bidiagonal_static_square_2x2",
"linalg::bidiagonal::proptest_tests::f64::bidiagonal_static_square",
"linalg::bidiagonal::proptest_tests::f64::bidiagonal_static_3_5",
"linalg::cholesky::complex::cholesky_determinant_static",
"geometry::similarity::all_op_exist",
"geometry::similarity::composition",
"linalg::cholesky::complex::cholesky_inverse_static",
"linalg::cholesky::complex::cholesky_rank_one_update",
"linalg::cholesky::complex::cholesky_solve_static",
"linalg::cholesky::complex::cholesky_insert_column",
"linalg::bidiagonal::proptest_tests::complex::bidiagonal_static_5_3",
"linalg::cholesky::complex::cholesky_static",
"linalg::bidiagonal::proptest_tests::complex::bidiagonal_static_3_5",
"linalg::cholesky::f64::cholesky_determinant_static",
"linalg::cholesky::complex::cholesky_remove_column",
"linalg::bidiagonal::proptest_tests::complex::bidiagonal_static_square",
"linalg::bidiagonal::proptest_tests::f64::bidiagonal",
"linalg::cholesky::f64::cholesky_rank_one_update",
"linalg::cholesky::f64::cholesky_inverse_static",
"linalg::cholesky::complex::cholesky_determinant",
"linalg::cholesky::f64::cholesky_determinant",
"linalg::col_piv_qr::col_piv_qr",
"linalg::cholesky::f64::cholesky_static",
"linalg::cholesky::f64::cholesky_insert_column",
"linalg::cholesky::f64::cholesky",
"linalg::cholesky::f64::cholesky_solve_static",
"linalg::cholesky::f64::cholesky_remove_column",
"linalg::cholesky::f64::cholesky_inverse",
"linalg::cholesky::complex::cholesky",
"linalg::cholesky::f64::cholesky_solve",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_static_3_5",
"linalg::cholesky::complex::cholesky_solve",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_inverse_static",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_solve_static",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_static_5_3",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_inverse_static",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_static_square",
"linalg::cholesky::complex::cholesky_inverse",
"linalg::convolution::convolve_full_check",
"linalg::convolution::convolve_same_check",
"linalg::convolution::convolve_valid_check",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_solve_static",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_static_5_3",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_static_3_5",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_static_square",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_inverse",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_solve",
"linalg::eigen::proptest_tests::complex::symmetric_eigen_static_square_2x2",
"linalg::eigen::proptest_tests::f64::symmetric_eigen_static_square_2x2",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_solve",
"linalg::eigen::symmetric_eigen_singular_24x24",
"linalg::eigen::very_small_deviation_from_identity_issue_1368",
"linalg::exp::tests::exp_complex",
"linalg::exp::tests::exp_dynamic",
"linalg::exp::tests::exp_static",
"linalg::full_piv_lu::full_piv_lu_simple",
"linalg::full_piv_lu::full_piv_lu_simple_with_pivot",
"linalg::eigen::proptest_tests::f64::symmetric_eigen_static_square_3x3",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_inverse",
"linalg::eigen::proptest_tests::complex::symmetric_eigen_static_square_3x3",
"linalg::eigen::proptest_tests::f64::symmetric_eigen_static_square_4x4",
"linalg::eigen::proptest_tests::f64::symmetric_eigen",
"linalg::eigen::proptest_tests::f64::symmetric_eigen_singular",
"linalg::eigen::proptest_tests::complex::symmetric_eigen",
"linalg::eigen::proptest_tests::complex::symmetric_eigen_static_square_4x4",
"linalg::eigen::proptest_tests::complex::symmetric_eigen_singular",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_inverse_static",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_solve_static",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_inverse",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_static_5_3",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_static_3_5",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_static_square",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_static_3_5",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_solve_static",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_inverse_static",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_static_square",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_static_5_3",
"linalg::hessenberg::f64::hessenberg_static_mat2",
"linalg::hessenberg::f64::hessenberg_static",
"linalg::inverse::matrix1_try_inverse",
"linalg::inverse::matrix1_try_inverse_scaled_identity",
"linalg::inverse::matrix2_try_inverse",
"linalg::inverse::matrix2_try_inverse_scaled_identity",
"linalg::inverse::matrix3_try_inverse",
"linalg::hessenberg::complex::hessenberg_static_mat2",
"linalg::inverse::matrix3_try_inverse_scaled_identity",
"linalg::inverse::matrix4_try_inverse_issue_214",
"linalg::inverse::matrix5_try_inverse",
"linalg::inverse::matrix5_try_inverse_scaled_identity",
"linalg::lu::lu_simple",
"linalg::lu::lu_simple_with_pivot",
"linalg::hessenberg::hessenberg_simple",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_solve",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_inverse",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_solve",
"linalg::hessenberg::f64::hessenberg",
"linalg::hessenberg::complex::hessenberg_static",
"linalg::lu::proptest_tests::complex::lu_inverse_static",
"linalg::lu::proptest_tests::complex::lu_static_3_5",
"linalg::lu::proptest_tests::complex::lu_solve_static",
"linalg::lu::proptest_tests::f64::lu_inverse_static",
"linalg::lu::proptest_tests::complex::lu_static_square",
"linalg::lu::proptest_tests::f64::lu",
"linalg::lu::proptest_tests::f64::lu_solve_static",
"linalg::lu::proptest_tests::f64::lu_static_3_5",
"linalg::lu::proptest_tests::f64::lu_inverse",
"linalg::lu::proptest_tests::f64::lu_static_square",
"linalg::lu::proptest_tests::complex::lu_solve",
"linalg::lu::proptest_tests::f64::lu_solve",
"linalg::pow::proptest_tests::f64::pow",
"linalg::hessenberg::complex::hessenberg",
"linalg::bidiagonal::proptest_tests::complex::bidiagonal",
"linalg::pow::proptest_tests::f64::pow_static_square_4x4",
"linalg::pow::proptest_tests::complex::pow",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr",
"linalg::lu::proptest_tests::complex::lu_inverse",
"linalg::pow::proptest_tests::complex::pow_static_square_4x4",
"linalg::qr::complex::qr_static_3_5",
"linalg::qr::complex::qr_inverse_static",
"linalg::qr::complex::qr_solve_static",
"linalg::qr::complex::qr_static_5_3",
"linalg::qr::f64::qr_inverse_static",
"linalg::qr::f64::qr_static_3_5",
"linalg::qr::f64::qr_solve_static",
"linalg::qr::f64::qr_inverse",
"linalg::qr::complex::qr_inverse",
"linalg::qr::f64::qr_static_5_3",
"linalg::qr::complex::qr_static_square",
"linalg::qr::f64::qr",
"linalg::qr::f64::qr_static_square",
"linalg::schur::proptest_tests::f64::schur_static_mat2",
"linalg::schur::proptest_tests::complex::schur_static_mat2",
"linalg::schur::schur_simpl_mat3",
"linalg::schur::schur_singular",
"linalg::schur::schur_static_mat3_fail",
"linalg::schur::schur_static_mat4_fail",
"linalg::schur::schur_static_mat4_fail2",
"linalg::qr::f64::qr_solve",
"linalg::schur::proptest_tests::f64::schur_static_mat3",
"linalg::qr::complex::qr_solve",
"linalg::schur::proptest_tests::f64::schur_static_mat4",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu",
"linalg::solve::f64::solve_lower_triangular",
"linalg::schur::proptest_tests::complex::schur_static_mat3",
"linalg::solve::f64::tr_solve_upper_triangular",
"linalg::solve::f64::solve_upper_triangular",
"linalg::solve::f64::tr_solve_lower_triangular",
"linalg::schur::proptest_tests::complex::schur_static_mat4",
"linalg::solve::complex::solve_lower_triangular",
"linalg::solve::complex::tr_solve_lower_triangular",
"linalg::solve::complex::tr_solve_upper_triangular",
"linalg::solve::complex::solve_upper_triangular",
"linalg::lu::proptest_tests::complex::lu",
"linalg::svd::proptest_tests::complex::svd_static_2_5",
"linalg::svd::proptest_tests::complex::svd_static_5_2",
"linalg::svd::proptest_tests::complex::svd_static_square_2x2",
"linalg::svd::proptest_tests::complex::svd_static_3_5",
"linalg::svd::proptest_tests::complex::svd_static_5_3",
"linalg::svd::proptest_tests::complex::svd_solve",
"linalg::svd::proptest_tests::complex::svd_static_square",
"linalg::svd::proptest_tests::complex::svd_static_square_3x3",
"linalg::svd::proptest_tests::f64::svd_static_2_5",
"linalg::svd::proptest_tests::f64::svd_static_5_2",
"linalg::svd::proptest_tests::f64::svd_static_3_5",
"linalg::svd::proptest_tests::f64::svd_static_5_3",
"linalg::svd::proptest_tests::f64::svd_static_square_2x2",
"linalg::svd::svd3_fail",
"linalg::svd::svd_err",
"linalg::svd::svd_fail",
"linalg::svd::svd_identity",
"linalg::svd::svd_regression_issue_1072",
"linalg::svd::svd_regression_issue_1313",
"linalg::svd::svd_regression_issue_983",
"linalg::svd::svd_singular",
"linalg::svd::svd_singular_horizontal",
"linalg::svd::svd_singular_vertical",
"linalg::svd::svd_sorted",
"linalg::svd::svd_with_delimited_subproblem",
"linalg::svd::svd_zeros",
"linalg::svd::proptest_tests::f64::svd_static_square",
"linalg::svd::proptest_tests::f64::svd_static_square_3x3",
"linalg::schur::proptest_tests::f64::schur",
"linalg::svd::proptest_tests::f64::svd_pseudo_inverse",
"linalg::svd::proptest_tests::f64::svd",
"linalg::tridiagonal::complex::symm_tridiagonal_static_square_2x2",
"linalg::qr::complex::qr",
"linalg::tridiagonal::f64::symm_tridiagonal_static_square_2x2",
"linalg::tridiagonal::f64::symm_tridiagonal_static_square",
"linalg::tridiagonal::complex::symm_tridiagonal_static_square",
"linalg::udu::udu_non_sym_panic - should panic",
"linalg::udu::udu_simple",
"proptest::ensure_arbitrary_test_compiles_dmatrix",
"linalg::udu::proptest_tests::f64::udu_static",
"proptest::ensure_arbitrary_test_compiles_dvector",
"proptest::ensure_arbitrary_test_compiles_matrix3",
"proptest::ensure_arbitrary_test_compiles_matrixmn_dynamic_u3",
"proptest::ensure_arbitrary_test_compiles_matrixmn_u3_dynamic",
"proptest::matrix_shrinking_satisfies_constraints",
"proptest::ensure_arbitrary_test_compiles_vector3",
"proptest::test_matrix_0_0",
"proptest::test_matrix_0_1",
"proptest::test_matrix_1_0",
"proptest::test_matrix_1_1",
"proptest::test_matrix_1_2",
"linalg::tridiagonal::f64::symm_tridiagonal",
"linalg::tridiagonal::f64::symm_tridiagonal_singular",
"proptest::test_matrix_2_3",
"proptest::test_matrix_2_1",
"proptest::test_matrix_2_2",
"proptest::test_matrix_3_2",
"proptest::test_matrix_3_3",
"proptest::test_matrix_input_1",
"linalg::svd::proptest_tests::f64::svd_polar_decomposition",
"proptest::test_matrix_output_types",
"linalg::udu::proptest_tests::f64::udu",
"proptest::test_matrix_input_2",
"proptest::test_matrix_input_3",
"proptest::test_matrix_u0_u0",
"proptest::test_matrix_u0_u1",
"proptest::test_matrix_u1_u0",
"proptest::test_matrix_input_4",
"proptest::test_matrix_u1_u1",
"proptest::test_matrix_u1_u2",
"proptest::test_matrix_u2_u2",
"proptest::test_matrix_u2_u3",
"proptest::test_matrix_u3_u2",
"proptest::test_matrix_u2_u1",
"proptest::test_matrix_u3_u3",
"linalg::svd::proptest_tests::complex::svd_pseudo_inverse",
"linalg::svd::proptest_tests::complex::svd",
"linalg::schur::proptest_tests::complex::schur",
"linalg::tridiagonal::complex::symm_tridiagonal",
"linalg::tridiagonal::complex::symm_tridiagonal_singular",
"linalg::svd::proptest_tests::complex::svd_polar_decomposition",
"proptest::slow::matrix_samples_all_possible_outputs",
"src/base/blas.rs - base::blas::Matrix<T,R,C,S>::dotc (line 210)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::gerc (line 681)",
"src/base/blas.rs - base::blas::Matrix<T,R,C,S>::tr_dot (line 234)",
"src/base/blas.rs - base::blas::Matrix<T,R,C,S>::dot (line 179)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::syger (line 947)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::ger (line 650)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::hegerc (line 982)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::gemm_tr (line 754)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::gemm_ad (line 811)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::gemm (line 714)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::ger_symm (line 910)",
"src/base/blas.rs - base::blas::SquareMatrix<T,D1,S>::quadform (line 1171)",
"src/base/blas.rs - base::blas::SquareMatrix<T,D1,S>::quadform_tr (line 1074)",
"src/base/blas.rs - base::blas::SquareMatrix<T,D1,S>::quadform_tr_with_workspace (line 1020)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::hegemv (line 465)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::gemv_ad (line 582)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::axcpy (line 286)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::axpy (line 308)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::gemv (line 332)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::add_scalar (line 312)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R,C,S>::abs (line 24)",
"src/base/blas.rs - base::blas::SquareMatrix<T,D1,S>::quadform_with_workspace (line 1113)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::sygemv (line 423)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::gemv_tr (line 548)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::add_scalar_mut (line 335)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::cdpy (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::cmpy (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_div (line 154)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_div_mut (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_div_assign (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_mul_mut (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_mul (line 154)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_mul_assign (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::inf (line 248)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::inf_sup (line 290)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::sup (line 269)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_column_slice (line 802)",
"src/base/construction.rs - base::construction::OMatrix<T,D,D>::from_diagonal (line 346)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_diagonal_element (line 678)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_fn (line 678)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_element (line 677)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_iterator (line 679)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_row_iterator (line 679)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_vec (line 803)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_row_slice (line 805)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_partial_diagonal (line 680)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::identity (line 679)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::repeat (line 679)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_fn (line 689)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_column_slice (line 807)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::zeros (line 677)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_diagonal_element (line 689)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_element (line 688)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_iterator (line 690)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_row_iterator (line 690)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_vec (line 808)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_row_slice (line 810)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_partial_diagonal (line 691)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::identity (line 690)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::repeat (line 690)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::zeros (line 688)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_column_slice (line 792)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_columns (line 255)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_fn (line 656)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_diagonal_element (line 656)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_element (line 655)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_iterator (line 657)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_row_iterator (line 657)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_row_slice (line 795)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_partial_diagonal (line 658)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_vec (line 793)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_rows (line 213)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_vec_generic (line 319)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::identity (line 657)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::repeat (line 657)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_column_slice (line 797)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::zeros (line 655)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_fn (line 667)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_diagonal_element (line 667)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_element (line 666)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_iterator (line 668)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_row_iterator (line 668)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_vec (line 798)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_partial_diagonal (line 669)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_row_slice (line 800)",
"src/base/edition.rs - base::edition::Matrix<T,R,C,S>::reshape_generic (line 964)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 378)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 390)",
"src/base/edition.rs - base::edition::Matrix<T,Dyn,U1,S>::extend (line 1227)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::identity (line 668)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::zeros (line 666)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::repeat (line 668)",
"src/base/edition.rs - base::edition::Matrix<T,R,Dyn,S>::extend (line 1180)",
"src/base/edition.rs - base::edition::Matrix<T,R,Dyn,S>::extend (line 1200)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 403)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 413)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 425)",
"src/base/edition.rs - base::edition::Matrix<T,R,Dyn,S>::extend (line 1252)",
"src/base/edition.rs - base::edition::Matrix<T,R,Dyn,S>::extend (line 1274)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 452)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 436)",
"src/base/edition.rs - base::edition::Matrix<T,R,Dyn,S>::extend (line 1286)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 463)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::iter (line 1083)",
"src/base/matrix.rs - base::matrix::Matrix::data (line 181)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::as_ptr (line 511)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::column_iter (line 1120)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::column_iter_mut (line 1168)",
"src/base/interpolation.rs - base::interpolation::Vector<T,D,S>::lerp (line 17)",
"src/base/interpolation.rs - base::interpolation::Unit<Vector<T,D,S>>::slerp (line 67)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::row_iter (line 1104)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::row_iter_mut (line 1145)",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::as_scalar (line 2277) - compile fail",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::nrows (line 435)",
"src/base/interpolation.rs - base::interpolation::Vector<T,D,S>::slerp (line 39)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::ncols (line 449)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::cast (line 744)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::vector_to_matrix_index (line 481)",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::as_scalar_mut (line 2298) - compile fail",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::shape (line 413)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::strides (line 463)",
"src/base/matrix.rs - base::matrix::super::alias::Matrix1<T>::into_scalar (line 2349) - compile fail",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::try_cast (line 762)",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::to_scalar (line 2322) - compile fail",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::as_scalar (line 2271)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::camax (line 29)",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::as_scalar_mut (line 2291)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::camin (line 89)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::amax (line 10)",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::to_scalar (line 2316)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::amin (line 70)",
"src/base/matrix.rs - base::matrix::Unit<Vector<T,D,S>>::cast (line 2245)",
"src/base/matrix.rs - base::matrix::super::alias::Matrix1<T>::into_scalar (line 2342)",
"src/base/matrix_view.rs - base::matrix_view::Matrix<T,R,C,S>::as_view (line 1123)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::iamax_full (line 175)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::icamax_full (line 135)",
"src/base/matrix_view.rs - base::matrix_view::Matrix<T,R,C,S>::as_view_mut (line 1170)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::argmax (line 246)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::argmin (line 328)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::iamax (line 296)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::iamin (line 378)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::icamax (line 211)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::max (line 50)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::imax (line 278)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::imin (line 360)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::min (line 113)",
"src/base/ops.rs - base::ops::OMatrix<T,Dyn,C>::sum (line 393)",
"src/base/norm.rs - base::norm::Matrix<T,R,C,S>::apply_metric_distance (line 232)",
"src/base/norm.rs - base::norm::Matrix<T,R,C,S>::apply_norm (line 211)",
"src/base/ops.rs - base::ops::OMatrix<T,Dyn,C>::sum (line 433)",
"src/base/ops.rs - base::ops::OMatrix<T,Dyn,C>::sum (line 383)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::product (line 207)",
"src/base/ops.rs - base::ops::OMatrix<T,Dyn,C>::sum (line 423)",
"src/base/properties.rs - base::properties::Matrix<T,R,C,S>::is_empty (line 34)",
"src/base/properties.rs - base::properties::Matrix<T,R,C,S>::len (line 18)",
"src/base/par_iter.rs - base::par_iter::Matrix<T,R,Cols,S>::par_column_iter (line 171)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::column_mean (line 502)",
"src/base/par_iter.rs - base::par_iter::Matrix<T,R,Cols,S>::par_column_iter_mut (line 201)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::column_product (line 283)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::sum (line 96)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::column_sum (line 172)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::column_variance (line 394)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::mean (line 434)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_mean (line 460)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_mean_tr (line 481)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_product (line 229)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_product_tr (line 256)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_sum_tr (line 145)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_variance_tr (line 373)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_sum (line 118)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_variance (line 352)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::variance (line 321)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion (line 26)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::conjugate_mut (line 159)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::conjugate (line 138)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::normalize (line 90)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::lerp (line 250)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::normalize_mut (line 115)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::conjugate (line 442)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::try_inverse (line 180)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::try_inverse_mut (line 215)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::dual_quaternion (line 425)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::conjugate_mut (line 462)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::inverse (line 482)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::inverse_mut (line 505)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::inverse_transform_unit_vector (line 905)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::inverse_transform_point (line 854)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::inverse_transform_vector (line 880)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::isometry_to (line 530)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::lerp (line 551)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::rotation (line 731)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::nlerp (line 584)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::to_homogeneous (line 935)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::sclerp (line 619)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::to_isometry (line 778)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::transform_point (line 804)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::DualQuaternion<T>::cast (line 56)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::transform_vector (line 829)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::translation (line 752)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::DualQuaternion<T>::from_real_and_dual (line 14)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::DualQuaternion<T>::from_real (line 78)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::DualQuaternion<T>::identity (line 30)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::UnitDualQuaternion<T>::cast (line 153)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::UnitDualQuaternion<T>::from_isometry (line 201)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::UnitDualQuaternion<T>::from_parts (line 175)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::UnitDualQuaternion<T>::from_rotation (line 223)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::UnitDualQuaternion<T>::identity (line 137)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::append_rotation_mut (line 220)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::append_rotation_wrt_center_mut (line 265)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::append_rotation_wrt_point_mut (line 242)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::append_translation_mut (line 201)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::from_parts (line 108)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inv_mul (line 178)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inverse (line 136)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inverse_mut (line 157)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inverse_transform_point (line 340)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inverse_transform_unit_vector (line 389)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::to_homogeneous (line 419)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inverse_transform_vector (line 365)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::to_matrix (line 451)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::transform_point (line 293)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::transform_vector (line 317)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry2<T>::cast (line 215)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry2<T>::new (line 185)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<T>::cast (line 427)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<T>::face_towards (line 482)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<T>::look_at_lh (line 483)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<T,R,D>::identity (line 41)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<T>::look_at_rh (line 483)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<T,R,D>::rotation_wrt_point (line 62)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<T>::new (line 426)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix2<T>::cast (line 161)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix2<T>::new (line 134)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<T>::cast (line 450)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<T>::face_towards (line 489)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<T>::look_at_lh (line 490)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<T>::look_at_rh (line 490)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<T>::new (line 449)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::Isometry2<T>::lerp_slerp (line 165)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::IsometryMatrix2<T>::lerp_slerp (line 205)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::Isometry3<T>::lerp_slerp (line 13)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::IsometryMatrix3<T>::lerp_slerp (line 89)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::Isometry3<T>::try_lerp_slerp (line 50)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::as_matrix (line 258)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::IsometryMatrix3<T>::try_lerp_slerp (line 126)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::as_projective (line 278)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::bottom (line 370)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::from_matrix_unchecked (line 100)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::into_inner (line 306)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::inverse (line 201)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::left (line 334)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::project_point (line 443)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::right (line 352)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::project_vector (line 518)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::new (line 123)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_bottom (line 587)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_bottom_and_top (line 693)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_left (line 547)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_left_and_right (line 667)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_right (line 567)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_top (line 607)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_zfar (line 647)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_znear (line 627)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_znear_and_zfar (line 719)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::to_homogeneous (line 238)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::to_projective (line 292)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::top (line 388)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::zfar (line 424)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::unproject_point (line 479)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::znear (line 406)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::apply (line 164)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::iter (line 294)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::is_empty (line 272)",
"src/geometry/point_construction.rs - geometry::point_construction::Point1<T>::new (line 199)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::iter_mut (line 325)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::len (line 254)",
"src/geometry/point_construction.rs - geometry::point_construction::Point5<T>::new (line 228)",
"src/geometry/point_construction.rs - geometry::point_construction::Point2<T>::new (line 228)",
"src/geometry/point_construction.rs - geometry::point_construction::Point3<T>::new (line 228)",
"src/geometry/point_construction.rs - geometry::point_construction::Point6<T>::new (line 228)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::lerp (line 228)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::map (line 143)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::to_homogeneous (line 186)",
"src/geometry/point_construction.rs - geometry::point_construction::OPoint<T,D>::cast (line 126)",
"src/geometry/point_construction.rs - geometry::point_construction::OPoint<T,D>::from_homogeneous (line 85)",
"src/geometry/point_construction.rs - geometry::point_construction::OPoint<T,D>::origin (line 40)",
"src/geometry/point_construction.rs - geometry::point_construction::OPoint<T,D>::from_slice (line 63)",
"src/geometry/point_construction.rs - geometry::point_construction::Point4<T>::new (line 228)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::as_vector (line 221)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::acos (line 745)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::acosh (line 902)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::as_vector_mut (line 565)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::asin (line 785)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::atanh (line 940)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::asinh (line 867)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::atan (line 826)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::conjugate (line 158)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::cos (line 726)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::conjugate_mut (line 600)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::cosh (line 885)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::dot (line 301)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::exp (line 506)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::inner (line 369)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::exp_eps (line 522)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::lerp (line 175)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::magnitude (line 255)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::norm (line 237)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::norm_squared (line 270)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::magnitude_squared (line 287)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::ln (line 487)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::normalize (line 135)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::normalize_mut (line 639)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::outer (line 389)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::polar_decomposition (line 457)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::powf (line 550)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::project (line 410)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::scalar (line 207)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::reject (line 433)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::sin (line 766)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::right_div (line 705)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::tan (line 806)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::tanh (line 920)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::sinh (line 850)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::try_inverse (line 323)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::try_inverse_mut (line 616)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::vector (line 191)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::vector_mut (line 579)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::angle (line 1060)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::angle_to (line 1125)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::axis (line 1280)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::axis_angle (line 1334)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::euler_angles (line 1483)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::conjugate (line 1092)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::inverse (line 1108)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::inverse_mut (line 1263)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::inverse_transform_point (line 1567)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::inverse_transform_unit_vector (line 1609)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::inverse_transform_vector (line 1589)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::lerp (line 1163)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::ln (line 1370)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::nlerp (line 1180)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::powf (line 1396)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::quaternion (line 1078)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::rotation_to (line 1144)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::scaled_axis (line 1309)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::to_rotation_matrix (line 1422)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::slerp (line 1201)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::to_homogeneous (line 1504)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::transform_point (line 1527)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::transform_vector (line 1547)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<T>::cast (line 56)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<T>::from_parts (line 84)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<T>::identity (line 115)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<T>::new (line 42)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::cast (line 227)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::from_euler_angles (line 288)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::face_towards (line 589)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::from_scaled_axis (line 748)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::from_axis_angle (line 245)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::from_rotation_matrix (line 327)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::look_at_lh (line 661)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::from_scaled_axis_eps (line 778)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::identity (line 207)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::look_at_rh (line 630)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::new (line 685)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::new_eps (line 716)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::rotation_between (line 445)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::rotation_between_axis (line 504)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::scaled_rotation_between_axis (line 530)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::from_matrix_unchecked (line 137)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::scaled_rotation_between (line 468)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::mean_of (line 812)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::into_inner (line 210)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::inverse (line 311)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::inverse_mut (line 362)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::inverse_transform_point (line 435)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::inverse_transform_unit_vector (line 475)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::matrix (line 165)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::to_homogeneous (line 245)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::inverse_transform_vector (line 455)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::transform_vector (line 415)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::transform_point (line 395)",
"src/geometry/rotation_construction.rs - geometry::rotation_construction::Rotation<T,D>::cast (line 51)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::transpose (line 287)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::transpose_mut (line 335)",
"src/geometry/rotation_interpolation.rs - geometry::rotation_interpolation::Rotation2<T>::slerp (line 9)",
"src/geometry/rotation_construction.rs - geometry::rotation_construction::Rotation<T,D>::identity (line 26)",
"src/geometry/rotation_interpolation.rs - geometry::rotation_interpolation::Rotation3<T>::slerp (line 40)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::angle (line 232)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::angle_to (line 249)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::powf (line 213)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::new (line 37)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::rotation_between (line 128)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::rotation_to (line 180)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::angle (line 809)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::angle_to (line 912)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::scaled_rotation_between (line 151)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::axis (line 830)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::axis_angle (line 886)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::euler_angles (line 944)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::euler_angles_ordered (line 1021)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::face_towards (line 465)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::euler_angles_ordered (line 995)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::from_euler_angles (line 421)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::from_scaled_axis (line 343)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::look_at_rh (line 521)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::look_at_lh (line 552)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::powf (line 670)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::new (line 316)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::rotation_to (line 652)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::rotation_between (line 582)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,1>::new (line 112)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::scaled_axis (line 861)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,5>::new (line 112)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,2>::new (line 112)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::pseudo_inverse (line 167)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::inverse_unchecked (line 137)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,3>::new (line 112)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::scaled_rotation_between (line 605)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::to_homogeneous (line 203)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,6>::new (line 112)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::transform_point (line 280)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::try_inverse (line 105)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::try_inverse_mut (line 241)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::try_inverse_transform_point (line 297)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,4>::new (line 112)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,D>::cast (line 44)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,D>::identity (line 22)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<T,R,D>::inverse_transform_point (line 260)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<T,R,D>::inverse_transform_vector (line 281)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<T,R,D>::transform_vector (line 239)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<T,R,D>::transform_point (line 217)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,R,D>::identity (line 41)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,R,D>::rotation_wrt_point (line 97)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation2<T>,2>::cast (line 167)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation3<T>,3>::cast (line 403)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation2<T>,2>::new (line 147)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation3<T>,3>::face_towards (line 413)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitQuaternion<T>,3>::cast (line 404)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitComplex<T>,2>::cast (line 208)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation3<T>,3>::look_at_rh (line 412)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitComplex<T>,2>::new (line 188)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitQuaternion<T>,3>::face_towards (line 414)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation3<T>,3>::look_at_lh (line 412)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation3<T>,3>::new (line 404)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitQuaternion<T>,3>::look_at_lh (line 413)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::into_inner (line 302)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitQuaternion<T>,3>::new (line 405)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitQuaternion<T>,3>::look_at_rh (line 413)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::inverse (line 444)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::matrix_mut_unchecked (line 348)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::matrix (line 327)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::to_homogeneous (line 394)",
"src/geometry/transform_construction.rs - geometry::transform_construction::Transform<T,C,D>::identity (line 30)",
"src/geometry/translation.rs - geometry::translation::Translation<T,D>::inverse (line 112)",
"src/geometry/translation.rs - geometry::translation::Translation<T,D>::inverse_mut (line 167)",
"src/geometry/translation.rs - geometry::translation::Translation<T,D>::inverse_transform_point (line 214)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::try_inverse_mut (line 470)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,1>::new (line 118)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::inverse_mut (line 499)",
"src/geometry/translation.rs - geometry::translation::Translation<T,D>::to_homogeneous (line 135)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::try_inverse (line 413)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,5>::new (line 118)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,6>::new (line 118)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,2>::new (line 118)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,3>::new (line 118)",
"src/geometry/translation.rs - geometry::translation::Translation<T,D>::transform_point (line 197)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,4>::new (line 118)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::angle (line 81)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,D>::cast (line 50)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,D>::identity (line 28)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::conjugate (line 180)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::angle_to (line 157)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::conjugate_mut (line 213)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::inverse (line 196)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::inverse_mut (line 232)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::inverse_transform_point (line 336)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::inverse_transform_unit_vector (line 372)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::inverse_transform_vector (line 355)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::sin_angle (line 95)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::slerp (line 396)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::to_rotation_matrix (line 255)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::to_homogeneous (line 274)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::transform_vector (line 319)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::transform_point (line 300)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::cast (line 133)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::from_angle (line 80)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::from_cos_sin_unchecked (line 101)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::from_rotation_matrix (line 186)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::identity (line 37)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::powf (line 269)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::new (line 60)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::rotation_to (line 247)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::scaled_rotation_between (line 315)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::rotation_between_axis (line 351)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::rotation_between (line 292)",
"src/lib.rs - (line 27)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::scaled_rotation_between_axis (line 376)",
"src/proptest/mod.rs - proptest (line 30)",
"src/proptest/mod.rs - proptest (line 55)",
"src/proptest/mod.rs - proptest (line 95)",
"src/proptest/mod.rs - proptest::matrix (line 226)"
] |
[
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::from_axis_angle (line 366)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::cos_angle (line 110)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::complex (line 152)"
] |
[
"linalg::svd::proptest_tests::f64::svd_solve"
] |
|
dimforge/nalgebra
| 1,369
|
dimforge__nalgebra-1369
|
[
"1368"
] |
749a9fee17028291fd47b8ea3c8d3baab53229a4
|
diff --git a/src/linalg/householder.rs b/src/linalg/householder.rs
--- a/src/linalg/householder.rs
+++ b/src/linalg/householder.rs
@@ -34,6 +34,17 @@ pub fn reflection_axis_mut<T: ComplexField, D: Dim, S: StorageMut<T, D>>(
if !factor.is_zero() {
column.unscale_mut(factor.sqrt());
+
+ // Normalize again, making sure the vector is unit-sized.
+ // If `factor` had a very small value, the first normalization
+ // (dividing by `factor.sqrt()`) might end up with a slightly
+ // non-unit vector (especially when using 32-bits float).
+ // Decompositions strongly rely on that unit-vector property,
+ // so we run a second normalization (that is much more numerically
+ // stable since the norm is close to 1) to ensure it has a unit
+ // size.
+ let _ = column.normalize_mut();
+
(-signed_norm, true)
} else {
// TODO: not sure why we don't have a - sign here.
|
diff --git a/tests/linalg/eigen.rs b/tests/linalg/eigen.rs
--- a/tests/linalg/eigen.rs
+++ b/tests/linalg/eigen.rs
@@ -1,4 +1,4 @@
-use na::DMatrix;
+use na::{DMatrix, Matrix3};
#[cfg(feature = "proptest-support")]
mod proptest_tests {
diff --git a/tests/linalg/eigen.rs b/tests/linalg/eigen.rs
--- a/tests/linalg/eigen.rs
+++ b/tests/linalg/eigen.rs
@@ -116,6 +116,31 @@ fn symmetric_eigen_singular_24x24() {
);
}
+// Regression test for #1368
+#[test]
+fn very_small_deviation_from_identity_issue_1368() {
+ let m = Matrix3::<f32>::new(
+ 1.0,
+ 3.1575704e-23,
+ 8.1146196e-23,
+ 3.1575704e-23,
+ 1.0,
+ 1.7471054e-22,
+ 8.1146196e-23,
+ 1.7471054e-22,
+ 1.0,
+ );
+
+ for v in m
+ .try_symmetric_eigen(f32::EPSILON, 0)
+ .unwrap()
+ .eigenvalues
+ .into_iter()
+ {
+ assert_relative_eq!(*v, 1.);
+ }
+}
+
// #[cfg(feature = "arbitrary")]
// quickcheck! {
// TODO: full eigendecomposition is not implemented yet because of its complexity when some
|
SVD Computes Wrong Singular Values for Very Small-Valued Matrices
This should be reproducible with `nalgebra = { version = "0.32.4", features = ["rand"] }`
```
use nalgebra::Matrix3;
fn main() {
let id = Matrix3::<f32>::identity();
loop {
let r = Matrix3::<f32>::new_random();
let m = id + r * 0.000000000000000000001;
if m == id {
panic!("too small")
}
let svd = m.svd_unordered(true, true);
if svd.singular_values.iter().any(|s| (s - 1.).abs() > 0.1) {
println!("Input Matrix: {m:#?}");
println!("Singular Values: {:#?}", svd.singular_values);
panic!();
}
}
}
```
Example output:
```
Input Matrix: [
[
1.0,
6.23101e-24,
2.2194742e-23,
],
[
7.9115625e-24,
1.0,
6.47089e-22,
],
[
1.922059e-23,
9.848782e-22,
1.0,
],
]
Singular Values: [
[
2.1223645,
1.0000001,
1.0,
],
]
```
|
There was a similar issue in https://github.com/dimforge/nalgebra/pull/1314, but I think the fix for that was included in 0.32.4. Maybe an interesting reference all the same.
|
2024-03-09T00:51:58Z
|
0.32
|
2024-03-28T14:26:12Z
|
a803815bd1d22a052690cfde3ff7fae26cd91152
|
[
"linalg::eigen::very_small_deviation_from_identity_issue_1368"
] |
[
"base::indexing::dimrange_range_usize",
"base::indexing::dimrange_rangefrom_dimname",
"base::indexing::dimrange_rangefrom_usize",
"base::indexing::dimrange_rangefull",
"base::indexing::dimrange_rangeto_usize",
"base::indexing::dimrange_rangeinclusive_usize",
"base::indexing::dimrange_rangetoinclusive_usize",
"base::indexing::dimrange_usize",
"base::matrix::tests::empty_display",
"base::matrix::tests::lower_exp",
"geometry::transform::tests::checks_homogeneous_invariants_of_square_identity_matrix",
"linalg::exp::tests::one_norm",
"linalg::symmetric_eigen::test::wilkinson_shift_zero",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_det",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diag_diff_and_zero_off_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_off_diagonal",
"linalg::symmetric_eigen::test::wilkinson_shift_zero_trace",
"geometry::quaternion_construction::tests::random_unit_quats_are_unit",
"linalg::symmetric_eigen::test::wilkinson_shift_random",
"core::conversion::array_matrix_conversion_2_2",
"core::conversion::array_matrix_conversion_2_3",
"core::cg::test_scaling_wrt_point_3",
"core::cg::test_scaling_wrt_point_1",
"core::cg::test_scaling_wrt_point_2",
"core::conversion::array_matrix_conversion_2_4",
"core::blas::gemm_noncommutative",
"core::conversion::array_matrix_conversion_2_5",
"core::conversion::array_matrix_conversion_2_6",
"core::conversion::array_matrix_conversion_3_2",
"core::conversion::array_matrix_conversion_3_3",
"core::conversion::array_matrix_conversion_3_4",
"core::conversion::array_matrix_conversion_3_5",
"core::conversion::array_matrix_conversion_4_2",
"core::conversion::array_matrix_conversion_4_3",
"core::conversion::array_matrix_conversion_4_6",
"core::conversion::array_matrix_conversion_3_6",
"core::conversion::array_matrix_conversion_4_4",
"core::conversion::array_matrix_conversion_5_5",
"core::conversion::array_matrix_conversion_4_5",
"core::conversion::array_matrix_conversion_5_6",
"core::conversion::array_matrix_conversion_5_2",
"core::conversion::array_matrix_conversion_5_4",
"core::conversion::array_matrix_conversion_6_2",
"core::conversion::array_matrix_conversion_5_3",
"core::conversion::array_matrix_conversion_6_3",
"core::conversion::array_matrix_conversion_6_6",
"core::conversion::array_row_vector_conversion_1",
"core::conversion::array_row_vector_conversion_2",
"core::conversion::array_row_vector_conversion_3",
"core::conversion::array_matrix_conversion_6_5",
"core::conversion::array_matrix_conversion_6_4",
"core::conversion::array_row_vector_conversion_4",
"core::conversion::array_row_vector_conversion_5",
"core::conversion::array_row_vector_conversion_6",
"core::conversion::array_vector_conversion_1",
"core::conversion::array_vector_conversion_2",
"core::conversion::array_vector_conversion_4",
"core::conversion::array_vector_conversion_5",
"core::conversion::array_vector_conversion_6",
"core::conversion::matrix_slice_from_matrix_ref",
"core::conversion::array_vector_conversion_3",
"core::edition::insert_columns",
"core::edition::insert_columns_to_empty_matrix",
"core::edition::insert_rows",
"core::edition::insert_rows_to_empty_matrix",
"core::edition::remove_columns",
"core::edition::remove_columns_at",
"core::edition::remove_rows",
"core::edition::remove_rows_at",
"core::edition::resize",
"core::blas::blas_proptest::gemv_tr",
"core::edition::resize_empty_matrix",
"core::edition::upper_lower_triangular",
"core::empty::empty_matrix_gemm",
"core::empty::empty_matrix_gemm_tr",
"core::empty::empty_matrix_mul_matrix",
"core::empty::empty_matrix_mul_vector",
"core::empty::empty_matrix_tr_mul_matrix",
"core::empty::empty_matrix_tr_mul_vector",
"core::macros::sanity_test",
"core::matrix::apply",
"core::matrix::column_iteration",
"core::matrix::column_iteration_double_ended",
"core::matrix::column_iteration_mut",
"core::matrix::column_iteration_mut_double_ended",
"core::matrix::column_iterator_double_ended_mut",
"core::matrix::components_mut",
"core::matrix::coordinates",
"core::matrix::copy_from_slice",
"core::matrix::copy_from_slice_too_large - should panic",
"core::matrix::copy_from_slice_too_small - should panic",
"core::matrix::cross_product_vector_and_row_vector",
"core::matrix::debug_output_corresponds_to_data_container",
"core::edition::swap_columns",
"core::edition::swap_rows",
"core::blas::blas_proptest::gemv_symm",
"core::blas::blas_proptest::ger_symm",
"core::conversion::rotation_conversion",
"core::conversion::translation_conversion",
"core::blas::blas_proptest::quadform_tr",
"core::conversion::unit_quaternion_conversion",
"core::blas::blas_proptest::quadform",
"core::conversion::isometry_conversion",
"core::conversion::similarity_conversion",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis1",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis4",
"core::matrix::from_columns",
"core::matrix::from_diagonal",
"core::matrix::from_not_enough_columns - should panic",
"core::matrix::from_rows",
"core::matrix::from_rows_with_different_dimensions - should panic",
"core::matrix::from_too_many_rows - should panic",
"core::matrix::identity",
"core::matrix::finite_dim_inner_space_tests::orthonormalize1",
"core::matrix::from_columns_dynamic",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis3",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis2",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim1",
"core::matrix::is_column_major",
"core::matrix::iter",
"core::matrix::iter_mut",
"core::matrix::kronecker",
"core::matrix::linear_index",
"core::matrix::map",
"core::matrix::map_with_location",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis5",
"core::matrix::finite_dim_inner_space_tests::orthonormal_subspace_basis6",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim2",
"core::matrix::normalization_tests::normalized_vec_norm_is_one",
"core::matrix::finite_dim_inner_space_tests::orthonormalize2",
"core::matrix::omatrix_to_string",
"core::matrix::partial_clamp",
"core::matrix::parallel_column_iteration",
"core::matrix::partial_eq_shape_mismatch",
"core::matrix::push",
"core::matrix::set_row_column",
"core::matrix::simple_add",
"core::matrix::simple_mul",
"core::matrix::simple_product",
"core::matrix::simple_scalar_conversion",
"core::matrix::simple_scalar_mul",
"core::matrix::partial_eq_different_types",
"core::matrix::simple_sum",
"core::matrix::simple_transpose",
"core::matrix::simple_transpose_mut",
"core::matrix::partial_cmp",
"core::matrix::swizzle",
"core::matrix::to_homogeneous",
"core::matrix::trace",
"core::matrix::trace_panic - should panic",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim4",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim3",
"core::matrix::normalization_tests::normalized_vec_norm_is_one_dyn",
"core::matrix::finite_dim_inner_space_tests::orthonormalize5",
"core::matrix::finite_dim_inner_space_tests::orthonormalize4",
"core::matrix::zip_map",
"core::matrix_view::col_view_mut",
"core::matrix::vector_index_mut",
"core::matrix_view::columns_out_of_bounds - should panic",
"core::matrix_view::column_out_of_bounds - should panic",
"core::matrix_view::columns_range_pair",
"core::matrix_view::nested_col_views",
"core::matrix_view::columns_with_step_out_of_bounds - should panic",
"core::matrix_view::nested_fixed_views",
"core::matrix_view::nested_row_views",
"core::matrix_view::new_from_slice",
"core::matrix_view::new_from_slice_mut",
"core::matrix_view::nested_views",
"core::matrix_view::row_out_of_bounds - should panic",
"core::matrix_view::rows_range_pair",
"core::matrix_view::rows_with_step_out_of_bounds - should panic",
"core::matrix_view::rows_out_of_bounds - should panic",
"core::matrix_view::view_mut",
"core::matrix_view::view_out_of_bounds - should panic",
"core::matrix_view::view_with_steps_out_of_bounds - should panic",
"core::matrixcompare::assert_matrix_eq_dense_negative_comparison - should panic",
"core::matrix_view::row_view_mut",
"core::matrix::finite_dim_inner_space_tests::orthonormalize3",
"core::mint::mint_matrix_conversion_2_2",
"core::mint::mint_matrix_conversion_2_3",
"core::matrix::parallel_column_iteration_mut",
"core::matrixcompare::assert_matrix_eq_dense_positive_comparison",
"core::mint::mint_matrix_conversion_4_4",
"core::mint::mint_matrix_conversion_3_4",
"core::mint::mint_quaternion_conversions",
"core::mint::mint_vector_conversion_2",
"core::mint::mint_vector_conversion_3",
"core::mint::mint_vector_conversion_4",
"core::reshape::reshape_owned",
"core::reshape::reshape_slice",
"core::rkyv::rkyv_diff_type_matrix3x4",
"core::rkyv::rkyv_same_type_isometry3",
"core::rkyv::rkyv_same_type_isometry_matrix2",
"core::rkyv::rkyv_same_type_isometry_matrix3",
"core::rkyv::rkyv_same_type_matrix3x4",
"core::matrix::finite_dim_inner_space_tests::orthonormalize6",
"core::rkyv::rkyv_same_type_point2",
"core::rkyv::rkyv_same_type_point3",
"core::rkyv::rkyv_same_type_quaternion",
"core::rkyv::rkyv_same_type_rotation2",
"core::rkyv::rkyv_same_type_similarity3",
"core::rkyv::rkyv_same_type_similarity_matrix3",
"core::rkyv::rkyv_same_type_rotation3",
"core::rkyv::rkyv_same_type_translation3",
"core::rkyv::rkyv_same_type_translation2",
"core::rkyv::rkyv_same_type_similarity_matrix2",
"core::mint::mint_matrix_conversion_3_3",
"core::serde::deserialize_enum",
"core::serde::serde_isometry2",
"core::serde::serde_isometry3",
"core::serde::serde_isometry_matrix2",
"core::serde::serde_isometry_matrix3",
"core::serde::serde_matrix3x4",
"core::serde::serde_point2",
"core::serde::serde_point3",
"core::serde::serde_quaternion",
"core::serde::serde_rotation2",
"core::serde::serde_rotation3",
"core::serde::serde_similarity2",
"core::serde::serde_similarity3",
"core::serde::serde_similarity_matrix2",
"core::serde::serde_similarity_matrix3",
"core::serde::serde_smatrix_invalid_len - should panic",
"core::serde::serde_translation2",
"core::serde::serde_translation3",
"core::variance::test_variance_catastrophic_cancellation",
"core::serde::serde_flat",
"core::serde::serde_dmatrix",
"core::matrix::transposition_tests::transpose_transpose_is_self",
"core::serde::serde_dmatrix_invalid_len - should panic",
"core::matrix::transposition_tests::transpose_mut_transpose_mut_is_self",
"core::matrix::inversion_tests::self_mul_inv_is_id_dim6",
"core::matrix::transposition_tests::tr_mul_is_transpose_then_mul",
"geometry::dual_quaternion::isometry_equivalence",
"geometry::dual_quaternion::multiply_equals_alga_transform",
"core::matrix::transposition_tests::check_transpose_components_dyn",
"geometry::isometry::append_rotation_wrt_point_to_id",
"geometry::dual_quaternion::inverse_is_identity",
"core::matrixcompare::matrixcompare_shape_agrees_with_matrix",
"core::matrixcompare::fetch_single_is_equivalent_to_index_f64",
"geometry::dual_quaternion::composition",
"core::matrix::transposition_tests::transpose_transpose_is_id_dyn",
"geometry::isometry::inverse_is_parts_inversion",
"geometry::point::display_fmt_respects_modifiers",
"geometry::point::point_clone",
"geometry::point::point_coordinates",
"geometry::point::point_ops",
"geometry::point::point_scale",
"geometry::point::point_vector_sum",
"geometry::point::to_homogeneous",
"geometry::projection::orthographic_inverse",
"geometry::projection::perspective_inverse",
"geometry::projection::perspective_matrix_point_transformation",
"geometry::dual_quaternion::sclerp_is_not_defined_for_opposite_orientations",
"geometry::isometry::multiply_equals_alga_transform",
"geometry::isometry::composition2",
"geometry::projection::proptest_tests::orthographic_project_unproject",
"geometry::quaternion::from_euler_angles",
"geometry::isometry::look_at_rh_3",
"geometry::projection::proptest_tests::perspective_project_unproject",
"geometry::dual_quaternion::sclerp_is_defined_for_identical_orientations",
"geometry::quaternion::euler_angles",
"geometry::isometry::inverse_is_identity",
"geometry::rotation::angle_2",
"geometry::rotation::angle_3",
"geometry::isometry::rotation_wrt_point_invariance",
"geometry::quaternion::unit_quaternion_double_covering",
"geometry::isometry::observer_frame_3",
"geometry::quaternion::unit_quaternion_rotation_conversion",
"geometry::quaternion::unit_quaternion_inv",
"geometry::rotation::proptest_tests::euler_angles_gimble_lock",
"geometry::isometry::all_op_exist",
"geometry::rotation::proptest_tests::from_euler_angles",
"geometry::dual_quaternion::all_op_exist",
"geometry::isometry::composition3",
"geometry::rotation::proptest_tests::angle_is_commutative_2",
"geometry::rotation::proptest_tests::new_rotation_2",
"geometry::rotation::proptest_tests::powf_rotation_2",
"geometry::rotation::proptest_tests::euler_angles",
"geometry::rotation::proptest_tests::new_rotation_3",
"geometry::quaternion::unit_quaternion_mul_vector",
"geometry::quaternion::unit_quaternion_transformation",
"geometry::rotation::proptest_tests::rotation_inv_2",
"geometry::rotation::proptest_tests::angle_is_commutative_3",
"geometry::rotation::proptest_tests::powf_rotation_3",
"geometry::rotation::proptest_tests::slerp_powf_agree_2",
"geometry::rotation::quaternion_euler_angles_issue_494",
"geometry::quaternion::all_op_exist",
"geometry::rotation::proptest_tests::rotation_between_is_anticommutative_2",
"geometry::rotation::proptest_tests::slerp_takes_shortest_path_2",
"geometry::rotation::proptest_tests::rotation_between_3",
"geometry::rotation::proptest_tests::rotation_inv_3",
"geometry::rotation::proptest_tests::rotation_between_2",
"geometry::unit_complex::unit_complex_inv",
"geometry::rotation::proptest_tests::slerp_takes_shortest_path_3",
"geometry::rotation::proptest_tests::slerp_powf_agree_3",
"geometry::unit_complex::unit_complex_rotation_conversion",
"geometry::rotation::proptest_tests::rotation_between_is_anticommutative_3",
"geometry::similarity::inverse_is_parts_inversion",
"geometry::rotation::proptest_tests::rotation_between_is_identity",
"linalg::bidiagonal::bidiagonal_regression_issue_1313",
"geometry::unit_complex::all_op_exist",
"linalg::bidiagonal::bidiagonal_identity",
"linalg::bidiagonal::bidiagonal_regression_issue_1313_minimal",
"geometry::similarity::inverse_is_identity",
"geometry::rotation::from_rotation_matrix",
"geometry::unit_complex::unit_complex_mul_vector",
"geometry::similarity::multiply_equals_alga_transform",
"geometry::unit_complex::unit_complex_transformation",
"linalg::balancing::balancing_parlett_reinsch_static",
"linalg::balancing::balancing_parlett_reinsch",
"linalg::bidiagonal::proptest_tests::complex::bidiagonal_static_square_2x2",
"linalg::bidiagonal::proptest_tests::f64::bidiagonal_static_square_2x2",
"linalg::cholesky::cholesky_with_substitute",
"linalg::bidiagonal::proptest_tests::f64::bidiagonal_static_3_5",
"linalg::bidiagonal::proptest_tests::f64::bidiagonal_static_5_3",
"linalg::cholesky::complex::cholesky_determinant_static",
"geometry::similarity::all_op_exist",
"geometry::similarity::composition",
"linalg::bidiagonal::proptest_tests::f64::bidiagonal_static_square",
"linalg::cholesky::complex::cholesky_rank_one_update",
"linalg::cholesky::complex::cholesky_insert_column",
"linalg::bidiagonal::proptest_tests::complex::bidiagonal_static_5_3",
"linalg::cholesky::complex::cholesky_inverse_static",
"linalg::bidiagonal::proptest_tests::f64::bidiagonal",
"linalg::bidiagonal::proptest_tests::complex::bidiagonal_static_3_5",
"linalg::bidiagonal::proptest_tests::complex::bidiagonal_static_square",
"linalg::cholesky::f64::cholesky_determinant_static",
"linalg::cholesky::complex::cholesky_solve_static",
"linalg::cholesky::complex::cholesky_static",
"linalg::cholesky::complex::cholesky_remove_column",
"linalg::cholesky::f64::cholesky_inverse_static",
"linalg::cholesky::f64::cholesky",
"linalg::cholesky::f64::cholesky_rank_one_update",
"linalg::cholesky::f64::cholesky_determinant",
"linalg::col_piv_qr::col_piv_qr",
"linalg::cholesky::f64::cholesky_insert_column",
"linalg::cholesky::f64::cholesky_solve_static",
"linalg::cholesky::f64::cholesky_static",
"linalg::cholesky::complex::cholesky_determinant",
"linalg::cholesky::f64::cholesky_remove_column",
"linalg::cholesky::f64::cholesky_inverse",
"linalg::cholesky::complex::cholesky",
"linalg::cholesky::f64::cholesky_solve",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_solve_static",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_static_3_5",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_inverse_static",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_static_5_3",
"linalg::cholesky::complex::cholesky_solve",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_inverse_static",
"linalg::cholesky::complex::cholesky_inverse",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_static_5_3",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_solve_static",
"linalg::convolution::convolve_same_check",
"linalg::convolution::convolve_full_check",
"linalg::convolution::convolve_valid_check",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_static_3_5",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_static_square",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_static_square",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_inverse",
"linalg::eigen::proptest_tests::complex::symmetric_eigen_static_square_2x2",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_inverse",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr_solve",
"linalg::eigen::proptest_tests::f64::symmetric_eigen_static_square_3x3",
"linalg::eigen::symmetric_eigen_singular_24x24",
"linalg::exp::tests::exp_complex",
"linalg::exp::tests::exp_dynamic",
"linalg::exp::tests::exp_static",
"linalg::full_piv_lu::full_piv_lu_simple",
"linalg::full_piv_lu::full_piv_lu_simple_with_pivot",
"linalg::eigen::proptest_tests::f64::symmetric_eigen_static_square_2x2",
"linalg::col_piv_qr::proptest_tests::f64::col_piv_qr_solve",
"linalg::eigen::proptest_tests::complex::symmetric_eigen_static_square_3x3",
"linalg::eigen::proptest_tests::f64::symmetric_eigen_static_square_4x4",
"linalg::eigen::proptest_tests::f64::symmetric_eigen",
"linalg::eigen::proptest_tests::f64::symmetric_eigen_singular",
"linalg::eigen::proptest_tests::complex::symmetric_eigen",
"linalg::eigen::proptest_tests::complex::symmetric_eigen_static_square_4x4",
"linalg::eigen::proptest_tests::complex::symmetric_eigen_singular",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_inverse_static",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_inverse_static",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_static_3_5",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_solve_static",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_static_square",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_static_5_3",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_solve_static",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_static_3_5",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_inverse",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_static_5_3",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_inverse",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_static_square",
"linalg::hessenberg::hessenberg_simple",
"linalg::inverse::matrix1_try_inverse",
"linalg::inverse::matrix1_try_inverse_scaled_identity",
"linalg::inverse::matrix2_try_inverse",
"linalg::inverse::matrix2_try_inverse_scaled_identity",
"linalg::inverse::matrix3_try_inverse",
"linalg::inverse::matrix3_try_inverse_scaled_identity",
"linalg::inverse::matrix4_try_inverse_issue_214",
"linalg::inverse::matrix5_try_inverse",
"linalg::inverse::matrix5_try_inverse_scaled_identity",
"linalg::lu::lu_simple",
"linalg::lu::lu_simple_with_pivot",
"linalg::full_piv_lu::proptest_tests::f64::full_piv_lu_solve",
"linalg::hessenberg::f64::hessenberg_static",
"linalg::hessenberg::f64::hessenberg_static_mat2",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu_solve",
"linalg::hessenberg::complex::hessenberg_static_mat2",
"linalg::hessenberg::complex::hessenberg_static",
"linalg::hessenberg::f64::hessenberg",
"linalg::lu::proptest_tests::complex::lu_static_3_5",
"linalg::lu::proptest_tests::f64::lu",
"linalg::lu::proptest_tests::complex::lu_inverse_static",
"linalg::lu::proptest_tests::f64::lu_inverse_static",
"linalg::lu::proptest_tests::complex::lu_solve",
"linalg::lu::proptest_tests::complex::lu_static_square",
"linalg::hessenberg::complex::hessenberg",
"linalg::lu::proptest_tests::complex::lu_solve_static",
"linalg::lu::proptest_tests::f64::lu_solve_static",
"linalg::lu::proptest_tests::f64::lu_inverse",
"linalg::lu::proptest_tests::f64::lu_static_3_5",
"linalg::lu::proptest_tests::f64::lu_static_square",
"linalg::lu::proptest_tests::f64::lu_solve",
"linalg::pow::proptest_tests::f64::pow_static_square_4x4",
"linalg::pow::proptest_tests::f64::pow",
"linalg::bidiagonal::proptest_tests::complex::bidiagonal",
"linalg::pow::proptest_tests::complex::pow",
"linalg::col_piv_qr::proptest_tests::complex::col_piv_qr",
"linalg::pow::proptest_tests::complex::pow_static_square_4x4",
"linalg::lu::proptest_tests::complex::lu_inverse",
"linalg::qr::complex::qr_static_3_5",
"linalg::qr::complex::qr_inverse_static",
"linalg::qr::f64::qr_inverse",
"linalg::qr::complex::qr_static_square",
"linalg::qr::f64::qr_solve_static",
"linalg::qr::complex::qr_solve_static",
"linalg::qr::complex::qr_solve",
"linalg::qr::f64::qr",
"linalg::qr::f64::qr_inverse_static",
"linalg::qr::f64::qr_static_3_5",
"linalg::qr::complex::qr_inverse",
"linalg::full_piv_lu::proptest_tests::complex::full_piv_lu",
"linalg::qr::f64::qr_static_5_3",
"linalg::qr::f64::qr_static_square",
"linalg::qr::complex::qr_static_5_3",
"linalg::schur::proptest_tests::f64::schur_static_mat2",
"linalg::schur::schur_simpl_mat3",
"linalg::schur::schur_static_mat3_fail",
"linalg::schur::proptest_tests::complex::schur_static_mat2",
"linalg::schur::schur_static_mat4_fail2",
"linalg::schur::schur_static_mat4_fail",
"linalg::schur::schur_singular",
"linalg::schur::proptest_tests::f64::schur_static_mat3",
"linalg::qr::f64::qr_solve",
"linalg::schur::proptest_tests::f64::schur_static_mat4",
"linalg::schur::proptest_tests::complex::schur_static_mat3",
"linalg::solve::f64::solve_upper_triangular",
"linalg::solve::f64::solve_lower_triangular",
"linalg::solve::f64::tr_solve_upper_triangular",
"linalg::solve::f64::tr_solve_lower_triangular",
"linalg::schur::proptest_tests::complex::schur_static_mat4",
"linalg::lu::proptest_tests::complex::lu",
"linalg::solve::complex::tr_solve_lower_triangular",
"linalg::solve::complex::tr_solve_upper_triangular",
"linalg::solve::complex::solve_upper_triangular",
"linalg::svd::proptest_tests::complex::svd_static_2_5",
"linalg::svd::proptest_tests::complex::svd_static_5_2",
"linalg::svd::proptest_tests::complex::svd_static_square_2x2",
"linalg::svd::proptest_tests::complex::svd_solve",
"linalg::svd::proptest_tests::complex::svd_static_5_3",
"linalg::solve::complex::solve_lower_triangular",
"linalg::svd::proptest_tests::complex::svd_static_3_5",
"linalg::svd::proptest_tests::complex::svd_static_square_3x3",
"linalg::svd::proptest_tests::complex::svd_static_square",
"linalg::svd::proptest_tests::f64::svd_static_2_5",
"linalg::svd::proptest_tests::f64::svd_static_5_2",
"linalg::svd::proptest_tests::f64::svd_solve",
"linalg::svd::proptest_tests::f64::svd_static_3_5",
"linalg::schur::proptest_tests::f64::schur",
"linalg::svd::proptest_tests::f64::svd_static_5_3",
"linalg::svd::svd3_fail",
"linalg::svd::svd_err",
"linalg::svd::svd_fail",
"linalg::svd::svd_identity",
"linalg::svd::svd_regression_issue_1072",
"linalg::svd::svd_regression_issue_1313",
"linalg::svd::proptest_tests::f64::svd_static_square_2x2",
"linalg::svd::svd_regression_issue_983",
"linalg::svd::svd_singular",
"linalg::svd::svd_singular_horizontal",
"linalg::svd::svd_sorted",
"linalg::svd::svd_singular_vertical",
"linalg::svd::svd_with_delimited_subproblem",
"linalg::svd::svd_zeros",
"linalg::svd::proptest_tests::f64::svd_static_square_3x3",
"linalg::svd::proptest_tests::f64::svd_static_square",
"linalg::svd::proptest_tests::f64::svd",
"linalg::qr::complex::qr",
"linalg::tridiagonal::complex::symm_tridiagonal_static_square_2x2",
"linalg::svd::proptest_tests::f64::svd_pseudo_inverse",
"linalg::tridiagonal::f64::symm_tridiagonal_static_square",
"linalg::tridiagonal::f64::symm_tridiagonal_static_square_2x2",
"linalg::tridiagonal::complex::symm_tridiagonal_static_square",
"linalg::udu::udu_non_sym_panic - should panic",
"linalg::udu::proptest_tests::f64::udu_static",
"linalg::udu::udu_simple",
"proptest::ensure_arbitrary_test_compiles_dmatrix",
"proptest::ensure_arbitrary_test_compiles_dvector",
"proptest::ensure_arbitrary_test_compiles_matrixmn_dynamic_u3",
"proptest::ensure_arbitrary_test_compiles_matrix3",
"proptest::ensure_arbitrary_test_compiles_matrixmn_u3_dynamic",
"proptest::matrix_shrinking_satisfies_constraints",
"proptest::ensure_arbitrary_test_compiles_vector3",
"proptest::test_matrix_0_0",
"linalg::tridiagonal::f64::symm_tridiagonal",
"proptest::test_matrix_0_1",
"proptest::test_matrix_1_0",
"linalg::tridiagonal::f64::symm_tridiagonal_singular",
"proptest::test_matrix_1_1",
"proptest::test_matrix_2_1",
"proptest::test_matrix_1_2",
"proptest::test_matrix_2_2",
"proptest::test_matrix_2_3",
"linalg::svd::proptest_tests::f64::svd_polar_decomposition",
"linalg::udu::proptest_tests::f64::udu",
"proptest::test_matrix_3_3",
"proptest::test_matrix_3_2",
"proptest::test_matrix_input_1",
"proptest::test_matrix_input_3",
"proptest::test_matrix_input_2",
"proptest::test_matrix_output_types",
"proptest::test_matrix_input_4",
"proptest::test_matrix_u0_u1",
"proptest::test_matrix_u1_u0",
"proptest::test_matrix_u1_u2",
"proptest::test_matrix_u0_u0",
"proptest::test_matrix_u2_u1",
"proptest::test_matrix_u1_u1",
"proptest::test_matrix_u2_u2",
"proptest::test_matrix_u2_u3",
"proptest::test_matrix_u3_u3",
"proptest::test_matrix_u3_u2",
"linalg::svd::proptest_tests::complex::svd",
"linalg::svd::proptest_tests::complex::svd_pseudo_inverse",
"linalg::schur::proptest_tests::complex::schur",
"linalg::svd::proptest_tests::complex::svd_polar_decomposition",
"linalg::tridiagonal::complex::symm_tridiagonal_singular",
"linalg::tridiagonal::complex::symm_tridiagonal",
"proptest::slow::matrix_samples_all_possible_outputs",
"src/base/blas.rs - base::blas::Matrix<T,R,C,S>::dotc (line 210)",
"src/base/blas.rs - base::blas::Matrix<T,R,C,S>::dot (line 179)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::ger_symm (line 910)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::gerc (line 681)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::gemm_ad (line 811)",
"src/base/blas.rs - base::blas::Matrix<T,R,C,S>::tr_dot (line 234)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::hegerc (line 982)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::ger (line 650)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::syger (line 947)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::gemm_tr (line 754)",
"src/base/blas.rs - base::blas::SquareMatrix<T,D1,S>::quadform (line 1171)",
"src/base/blas.rs - base::blas::Matrix<T,R1,C1,S>::gemm (line 714)",
"src/base/blas.rs - base::blas::SquareMatrix<T,D1,S>::quadform_tr (line 1074)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::axpy (line 308)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::gemv_ad (line 582)",
"src/base/blas.rs - base::blas::SquareMatrix<T,D1,S>::quadform_tr_with_workspace (line 1020)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::hegemv (line 465)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::axcpy (line 286)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::gemv_tr (line 548)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::gemv (line 332)",
"src/base/blas.rs - base::blas::SquareMatrix<T,D1,S>::quadform_with_workspace (line 1113)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R,C,S>::abs (line 24)",
"src/base/blas.rs - base::blas::Vector<T,D,S>::sygemv (line 423)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::cdpy (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::add_scalar_mut (line 335)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::add_scalar (line 312)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::cmpy (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_mul (line 154)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_div (line 154)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_div_mut (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_div_assign (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_mul_assign (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::component_mul_mut (line 153)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::inf_sup (line 290)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_column_slice (line 802)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::sup (line 269)",
"src/base/componentwise.rs - base::componentwise::Matrix<T,R1,C1,SA>::inf (line 248)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_fn (line 678)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_iterator (line 679)",
"src/base/construction.rs - base::construction::OMatrix<T,D,D>::from_diagonal (line 346)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_row_iterator (line 679)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_diagonal_element (line 678)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_element (line 677)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_vec (line 803)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_row_slice (line 805)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::from_partial_diagonal (line 680)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::identity (line 679)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::zeros (line 677)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,C>::repeat (line 679)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_fn (line 689)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_iterator (line 690)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_column_slice (line 807)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_element (line 688)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_diagonal_element (line 689)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_row_iterator (line 690)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_vec (line 808)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_partial_diagonal (line 691)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_column_slice (line 792)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::from_row_slice (line 810)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::identity (line 690)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::zeros (line 688)",
"src/base/construction.rs - base::construction::OMatrix<T,Dyn,Dyn>::repeat (line 690)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_fn (line 656)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_columns (line 255)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_row_iterator (line 657)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_diagonal_element (line 656)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_element (line 655)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_iterator (line 657)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_partial_diagonal (line 658)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_row_slice (line 795)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_vec (line 793)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_rows (line 213)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::from_vec_generic (line 319)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_column_slice (line 797)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::identity (line 657)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::zeros (line 655)",
"src/base/construction.rs - base::construction::OMatrix<T,R,C>::repeat (line 657)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_fn (line 667)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_diagonal_element (line 667)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_element (line 666)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_iterator (line 668)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_vec (line 798)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_row_iterator (line 668)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_partial_diagonal (line 669)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::from_row_slice (line 800)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 378)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 390)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::zeros (line 666)",
"src/base/edition.rs - base::edition::Matrix<T,R,Dyn,S>::extend (line 1180)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::identity (line 668)",
"src/base/construction.rs - base::construction::OMatrix<T,R,Dyn>::repeat (line 668)",
"src/base/edition.rs - base::edition::Matrix<T,R,Dyn,S>::extend (line 1286)",
"src/base/edition.rs - base::edition::Matrix<T,R,Dyn,S>::extend (line 1200)",
"src/base/edition.rs - base::edition::Matrix<T,R,Dyn,S>::extend (line 1274)",
"src/base/edition.rs - base::edition::Matrix<T,Dyn,U1,S>::extend (line 1227)",
"src/base/edition.rs - base::edition::Matrix<T,R,Dyn,S>::extend (line 1252)",
"src/base/edition.rs - base::edition::Matrix<T,R,C,S>::reshape_generic (line 964)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 403)",
"src/base/matrix.rs - base::matrix::Matrix::data (line 181)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 413)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 425)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 452)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 463)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::iter (line 1083)",
"src/base/indexing.rs - base::indexing::Matrix<T,R,C,S> (line 436)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::as_ptr (line 511)",
"src/base/interpolation.rs - base::interpolation::Unit<Vector<T,D,S>>::slerp (line 67)",
"src/base/interpolation.rs - base::interpolation::Vector<T,D,S>::lerp (line 17)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::column_iter (line 1120)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::column_iter_mut (line 1168)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::ncols (line 449)",
"src/base/interpolation.rs - base::interpolation::Vector<T,D,S>::slerp (line 39)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::nrows (line 435)",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::as_scalar (line 2277) - compile fail",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::cast (line 744)",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::as_scalar_mut (line 2298) - compile fail",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::row_iter (line 1104)",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::to_scalar (line 2322) - compile fail",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::row_iter_mut (line 1145)",
"src/base/matrix.rs - base::matrix::super::alias::Matrix1<T>::into_scalar (line 2349) - compile fail",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::shape (line 413)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::strides (line 463)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::vector_to_matrix_index (line 481)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::amax (line 10)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::amin (line 70)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::camax (line 29)",
"src/base/matrix.rs - base::matrix::Matrix<T,R,C,S>::try_cast (line 762)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::camin (line 89)",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::as_scalar (line 2271)",
"src/base/matrix.rs - base::matrix::Unit<Vector<T,D,S>>::cast (line 2245)",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::as_scalar_mut (line 2291)",
"src/base/matrix.rs - base::matrix::Matrix<T,U1,U1,S>::to_scalar (line 2316)",
"src/base/matrix_view.rs - base::matrix_view::Matrix<T,R,C,S>::as_view_mut (line 1170)",
"src/base/matrix_view.rs - base::matrix_view::Matrix<T,R,C,S>::as_view (line 1123)",
"src/base/matrix.rs - base::matrix::super::alias::Matrix1<T>::into_scalar (line 2342)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::min (line 113)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::argmax (line 246)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::argmin (line 328)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::icamax_full (line 135)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::max (line 50)",
"src/base/min_max.rs - base::min_max::Matrix<T,R,C,S>::iamax_full (line 175)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::iamax (line 296)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::iamin (line 378)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::imin (line 360)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::icamax (line 211)",
"src/base/min_max.rs - base::min_max::Vector<T,D,S>::imax (line 278)",
"src/base/norm.rs - base::norm::Matrix<T,R,C,S>::apply_metric_distance (line 232)",
"src/base/ops.rs - base::ops::OMatrix<T,Dyn,C>::sum (line 393)",
"src/base/par_iter.rs - base::par_iter::Matrix<T,R,Cols,S>::par_column_iter (line 171)",
"src/base/ops.rs - base::ops::OMatrix<T,Dyn,C>::sum (line 433)",
"src/base/properties.rs - base::properties::Matrix<T,R,C,S>::len (line 18)",
"src/base/properties.rs - base::properties::Matrix<T,R,C,S>::is_empty (line 34)",
"src/base/norm.rs - base::norm::Matrix<T,R,C,S>::apply_norm (line 211)",
"src/base/par_iter.rs - base::par_iter::Matrix<T,R,Cols,S>::par_column_iter_mut (line 201)",
"src/base/ops.rs - base::ops::OMatrix<T,Dyn,C>::sum (line 383)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::product (line 207)",
"src/base/ops.rs - base::ops::OMatrix<T,Dyn,C>::sum (line 423)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::column_product (line 283)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::column_mean (line 502)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::sum (line 96)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::column_sum (line 172)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::column_variance (line 394)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_mean (line 460)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_product (line 229)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_mean_tr (line 481)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_product_tr (line 256)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::mean (line 434)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_sum_tr (line 145)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::variance (line 321)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_variance (line 352)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_sum (line 118)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::conjugate (line 138)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::conjugate_mut (line 159)",
"src/base/statistics.rs - base::statistics::Matrix<T,R,C,S>::row_variance_tr (line 373)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion (line 26)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::normalize_mut (line 115)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::try_inverse (line 180)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::normalize (line 90)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::dual_quaternion (line 425)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::conjugate (line 442)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::try_inverse_mut (line 215)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::DualQuaternion<T>::lerp (line 250)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::conjugate_mut (line 462)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::inverse_transform_point (line 854)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::inverse (line 482)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::inverse_transform_unit_vector (line 905)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::inverse_mut (line 505)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::inverse_transform_vector (line 880)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::isometry_to (line 530)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::to_isometry (line 778)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::transform_point (line 804)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::to_homogeneous (line 935)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::transform_vector (line 829)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::rotation (line 731)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::sclerp (line 619)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::lerp (line 551)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::nlerp (line 584)",
"src/geometry/dual_quaternion.rs - geometry::dual_quaternion::UnitDualQuaternion<T>::translation (line 752)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::DualQuaternion<T>::identity (line 30)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::UnitDualQuaternion<T>::cast (line 153)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::DualQuaternion<T>::from_real (line 78)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::append_rotation_mut (line 220)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::DualQuaternion<T>::from_real_and_dual (line 14)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::UnitDualQuaternion<T>::identity (line 137)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::UnitDualQuaternion<T>::from_isometry (line 201)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::DualQuaternion<T>::cast (line 56)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::append_rotation_wrt_center_mut (line 265)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::UnitDualQuaternion<T>::from_parts (line 175)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::append_rotation_wrt_point_mut (line 242)",
"src/geometry/dual_quaternion_construction.rs - geometry::dual_quaternion_construction::UnitDualQuaternion<T>::from_rotation (line 223)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::from_parts (line 108)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inv_mul (line 178)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::append_translation_mut (line 201)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inverse_transform_unit_vector (line 389)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::to_homogeneous (line 419)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inverse_mut (line 157)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::transform_point (line 293)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::to_matrix (line 451)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inverse_transform_point (line 340)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inverse (line 136)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::inverse_transform_vector (line 365)",
"src/geometry/isometry.rs - geometry::isometry::Isometry<T,R,D>::transform_vector (line 317)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry2<T>::cast (line 215)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<T>::cast (line 427)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry2<T>::new (line 185)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix2<T>::new (line 134)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<T,R,D>::identity (line 41)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<T>::look_at_rh (line 483)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<T>::look_at_lh (line 483)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<T>::new (line 426)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry<T,R,D>::rotation_wrt_point (line 62)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix2<T>::cast (line 161)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::Isometry3<T>::face_towards (line 482)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<T>::new (line 449)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<T>::cast (line 450)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<T>::look_at_lh (line 490)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::Isometry2<T>::lerp_slerp (line 165)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<T>::face_towards (line 489)",
"src/geometry/isometry_construction.rs - geometry::isometry_construction::IsometryMatrix3<T>::look_at_rh (line 490)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::as_matrix (line 258)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::IsometryMatrix2<T>::lerp_slerp (line 205)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::IsometryMatrix3<T>::try_lerp_slerp (line 126)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::Isometry3<T>::lerp_slerp (line 13)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::IsometryMatrix3<T>::lerp_slerp (line 89)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::bottom (line 370)",
"src/geometry/isometry_interpolation.rs - geometry::isometry_interpolation::Isometry3<T>::try_lerp_slerp (line 50)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::as_projective (line 278)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::into_inner (line 306)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::project_point (line 443)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::inverse (line 201)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::from_matrix_unchecked (line 100)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::new (line 123)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::left (line 334)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::project_vector (line 518)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::right (line 352)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_left_and_right (line 667)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_right (line 567)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_bottom (line 587)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_bottom_and_top (line 693)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_left (line 547)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_top (line 607)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_zfar (line 647)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_znear (line 627)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::set_znear_and_zfar (line 719)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::to_projective (line 292)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::to_homogeneous (line 238)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::unproject_point (line 479)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::top (line 388)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::iter (line 294)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::zfar (line 424)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::apply (line 164)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::iter_mut (line 325)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::len (line 254)",
"src/geometry/orthographic.rs - geometry::orthographic::Orthographic3<T>::znear (line 406)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::is_empty (line 272)",
"src/geometry/point_construction.rs - geometry::point_construction::Point1<T>::new (line 199)",
"src/geometry/point_construction.rs - geometry::point_construction::Point2<T>::new (line 228)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::lerp (line 228)",
"src/geometry/point_construction.rs - geometry::point_construction::Point5<T>::new (line 228)",
"src/geometry/point_construction.rs - geometry::point_construction::Point3<T>::new (line 228)",
"src/geometry/point_construction.rs - geometry::point_construction::Point6<T>::new (line 228)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::map (line 143)",
"src/geometry/point_construction.rs - geometry::point_construction::OPoint<T,D>::cast (line 126)",
"src/geometry/point_construction.rs - geometry::point_construction::OPoint<T,D>::from_homogeneous (line 85)",
"src/geometry/point.rs - geometry::point::OPoint<T,D>::to_homogeneous (line 186)",
"src/geometry/point_construction.rs - geometry::point_construction::OPoint<T,D>::origin (line 40)",
"src/geometry/point_construction.rs - geometry::point_construction::OPoint<T,D>::from_slice (line 63)",
"src/geometry/point_construction.rs - geometry::point_construction::Point4<T>::new (line 228)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::asin (line 785)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::acosh (line 902)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::cos (line 726)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::as_vector (line 221)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::acos (line 745)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::as_vector_mut (line 565)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::atan (line 826)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::conjugate (line 158)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::atanh (line 940)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::conjugate_mut (line 600)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::asinh (line 867)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::cosh (line 885)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::ln (line 487)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::dot (line 301)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::exp_eps (line 522)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::exp (line 506)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::inner (line 369)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::lerp (line 175)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::magnitude (line 255)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::norm_squared (line 270)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::magnitude_squared (line 287)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::norm (line 237)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::normalize (line 135)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::polar_decomposition (line 457)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::normalize_mut (line 639)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::scalar (line 207)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::reject (line 433)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::powf (line 550)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::outer (line 389)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::project (line 410)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::right_div (line 705)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::tan (line 806)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::sin (line 766)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::angle (line 1060)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::axis_angle (line 1334)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::vector_mut (line 579)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::tanh (line 920)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::angle_to (line 1125)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::sinh (line 850)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::vector (line 191)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::try_inverse (line 323)",
"src/geometry/quaternion.rs - geometry::quaternion::Quaternion<T>::try_inverse_mut (line 616)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::axis (line 1280)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::euler_angles (line 1483)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::lerp (line 1163)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::inverse_transform_vector (line 1589)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::conjugate (line 1092)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::inverse_transform_point (line 1567)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::inverse_transform_unit_vector (line 1609)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::inverse (line 1108)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::inverse_mut (line 1263)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::ln (line 1370)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::nlerp (line 1180)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::quaternion (line 1078)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::powf (line 1396)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::rotation_to (line 1144)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::scaled_axis (line 1309)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<T>::cast (line 56)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<T>::from_parts (line 84)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<T>::new (line 42)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::slerp (line 1201)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::to_homogeneous (line 1504)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::to_rotation_matrix (line 1422)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::cast (line 227)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::transform_point (line 1527)",
"src/geometry/quaternion.rs - geometry::quaternion::UnitQuaternion<T>::transform_vector (line 1547)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::Quaternion<T>::identity (line 115)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::face_towards (line 589)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::from_axis_angle (line 245)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::from_euler_angles (line 288)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::from_rotation_matrix (line 327)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::identity (line 207)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::from_scaled_axis_eps (line 778)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::look_at_lh (line 661)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::look_at_rh (line 630)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::from_scaled_axis (line 748)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::new_eps (line 716)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::new (line 685)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::rotation_between_axis (line 504)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::rotation_between (line 445)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::inverse_transform_point (line 435)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::scaled_rotation_between (line 468)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::from_matrix_unchecked (line 137)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::into_inner (line 210)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::inverse (line 311)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::mean_of (line 812)",
"src/geometry/quaternion_construction.rs - geometry::quaternion_construction::UnitQuaternion<T>::scaled_rotation_between_axis (line 530)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::inverse_mut (line 362)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::inverse_transform_unit_vector (line 475)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::matrix (line 165)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::to_homogeneous (line 245)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::inverse_transform_vector (line 455)",
"src/geometry/rotation_construction.rs - geometry::rotation_construction::Rotation<T,D>::cast (line 51)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::transform_vector (line 415)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::new (line 37)",
"src/geometry/rotation_interpolation.rs - geometry::rotation_interpolation::Rotation2<T>::slerp (line 9)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::transpose (line 287)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::transform_point (line 395)",
"src/geometry/rotation.rs - geometry::rotation::Rotation<T,D>::transpose_mut (line 335)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::powf (line 213)",
"src/geometry/rotation_construction.rs - geometry::rotation_construction::Rotation<T,D>::identity (line 26)",
"src/geometry/rotation_interpolation.rs - geometry::rotation_interpolation::Rotation3<T>::slerp (line 40)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::angle (line 232)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::angle_to (line 249)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::rotation_between (line 128)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::rotation_to (line 180)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation2<T>::scaled_rotation_between (line 151)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::axis_angle (line 886)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::euler_angles (line 944)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::euler_angles_ordered (line 995)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::euler_angles_ordered (line 1021)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::angle (line 809)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::face_towards (line 465)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::axis (line 830)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::angle_to (line 912)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::from_euler_angles (line 421)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::scaled_axis (line 861)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::from_scaled_axis (line 343)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::look_at_lh (line 552)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::new (line 316)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::pseudo_inverse (line 167)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::powf (line 670)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,1>::new (line 112)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::look_at_rh (line 521)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,2>::new (line 112)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::rotation_to (line 652)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,3>::new (line 112)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::inverse_unchecked (line 137)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::scaled_rotation_between (line 605)",
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::rotation_between (line 582)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,6>::new (line 112)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,5>::new (line 112)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::try_inverse_mut (line 241)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::to_homogeneous (line 203)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,D>::identity (line 22)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::transform_point (line 280)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::try_inverse (line 105)",
"src/geometry/scale.rs - geometry::scale::Scale<T,D>::try_inverse_transform_point (line 297)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<T,R,D>::inverse_transform_vector (line 281)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,D>::cast (line 44)",
"src/geometry/scale_construction.rs - geometry::scale_construction::Scale<T,4>::new (line 112)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<T,R,D>::inverse_transform_point (line 260)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<T,R,D>::transform_vector (line 239)",
"src/geometry/similarity.rs - geometry::similarity::Similarity<T,R,D>::transform_point (line 217)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation3<T>,3>::look_at_lh (line 412)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation2<T>,2>::cast (line 167)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation3<T>,3>::cast (line 403)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,R,D>::rotation_wrt_point (line 97)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation3<T>,3>::look_at_rh (line 412)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,R,D>::identity (line 41)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation3<T>,3>::face_towards (line 413)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation2<T>,2>::new (line 147)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,Rotation3<T>,3>::new (line 404)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitComplex<T>,2>::cast (line 208)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitQuaternion<T>,3>::face_towards (line 414)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitQuaternion<T>,3>::cast (line 404)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitComplex<T>,2>::new (line 188)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitQuaternion<T>,3>::new (line 405)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitQuaternion<T>,3>::look_at_lh (line 413)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::into_inner (line 302)",
"src/geometry/similarity_construction.rs - geometry::similarity_construction::Similarity<T,UnitQuaternion<T>,3>::look_at_rh (line 413)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::matrix (line 327)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::inverse_mut (line 499)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::to_homogeneous (line 394)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::inverse (line 444)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::matrix_mut_unchecked (line 348)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,1>::new (line 118)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,3>::new (line 118)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,2>::new (line 118)",
"src/geometry/translation.rs - geometry::translation::Translation<T,D>::inverse_mut (line 167)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,6>::new (line 118)",
"src/geometry/translation.rs - geometry::translation::Translation<T,D>::inverse (line 112)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,5>::new (line 118)",
"src/geometry/transform_construction.rs - geometry::transform_construction::Transform<T,C,D>::identity (line 30)",
"src/geometry/translation.rs - geometry::translation::Translation<T,D>::inverse_transform_point (line 214)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::try_inverse_mut (line 470)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,4>::new (line 118)",
"src/geometry/translation.rs - geometry::translation::Translation<T,D>::transform_point (line 197)",
"src/geometry/transform.rs - geometry::transform::Transform<T,C,D>::try_inverse (line 413)",
"src/geometry/translation.rs - geometry::translation::Translation<T,D>::to_homogeneous (line 135)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,D>::identity (line 28)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::conjugate_mut (line 213)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::angle_to (line 157)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::angle (line 81)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::conjugate (line 180)",
"src/geometry/translation_construction.rs - geometry::translation_construction::Translation<T,D>::cast (line 50)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::inverse_transform_point (line 336)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::inverse_mut (line 232)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::inverse_transform_vector (line 355)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::sin_angle (line 95)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::inverse (line 196)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::slerp (line 396)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::transform_vector (line 319)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::inverse_transform_unit_vector (line 372)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::to_rotation_matrix (line 255)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::to_homogeneous (line 274)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::transform_point (line 300)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::cast (line 133)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::from_angle (line 80)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::from_cos_sin_unchecked (line 101)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::from_rotation_matrix (line 186)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::identity (line 37)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::rotation_between (line 292)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::rotation_to (line 247)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::powf (line 269)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::new (line 60)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::rotation_between_axis (line 351)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::scaled_rotation_between (line 315)",
"src/lib.rs - (line 27)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::scaled_rotation_between_axis (line 376)",
"src/proptest/mod.rs - proptest::matrix (line 226)",
"src/proptest/mod.rs - proptest (line 55)",
"src/proptest/mod.rs - proptest (line 30)",
"src/proptest/mod.rs - proptest (line 95)"
] |
[
"src/geometry/rotation_specialization.rs - geometry::rotation_specialization::Rotation3<T>::from_axis_angle (line 366)",
"src/geometry/unit_complex.rs - geometry::unit_complex::UnitComplex<T>::cos_angle (line 110)",
"src/geometry/unit_complex_construction.rs - geometry::unit_complex_construction::UnitComplex<T>::complex (line 152)"
] |
[] |
clockworklabs/SpacetimeDB
| 313
|
clockworklabs__SpacetimeDB-313
|
[
"308"
] |
cf2584fe8065a705d85222fffd8761e33d690f2a
|
diff --git a/crates/core/src/sql/compiler.rs b/crates/core/src/sql/compiler.rs
--- a/crates/core/src/sql/compiler.rs
+++ b/crates/core/src/sql/compiler.rs
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use crate::db::datastore::locking_tx_datastore::MutTxId;
-use crate::db::datastore::traits::{IndexSchema, TableSchema};
+use crate::db::datastore::traits::TableSchema;
use crate::db::relational_db::RelationalDB;
use crate::error::{DBError, PlanError};
use crate::sql::ast::{compile_to_ast, Column, From, Join, Selection, SqlAst};
diff --git a/crates/core/src/sql/compiler.rs b/crates/core/src/sql/compiler.rs
--- a/crates/core/src/sql/compiler.rs
+++ b/crates/core/src/sql/compiler.rs
@@ -73,30 +73,44 @@ fn check_cmp_expr(table: &From, expr: &ColumnOp) -> Result<(), PlanError> {
/// Compiles a `WHERE ...` clause
fn compile_where(mut q: QueryExpr, table: &From, filter: Selection) -> Result<QueryExpr, PlanError> {
check_cmp_expr(table, &filter.clause)?;
- let schema = &table.root;
- for op in filter.clause.to_vec() {
- match is_sargable(table, &op) {
- Some(IndexArgument::Eq { col_id, value }) => {
- q = q.with_index_eq(schema.into(), col_id, value);
- }
- Some(IndexArgument::LowerBound {
- col_id,
- value,
- inclusive,
- }) => {
- q = q.with_index_lower_bound(schema.into(), col_id, value, inclusive);
- }
- Some(IndexArgument::UpperBound {
- col_id,
- value,
- inclusive,
- }) => {
- q = q.with_index_upper_bound(schema.into(), col_id, value, inclusive);
- }
- None => {
- q = q.with_select(op);
+ 'outer: for ref op in filter.clause.to_vec() {
+ // Go through each table schema referenced in the query.
+ // Find the first sargable condition and short-circuit.
+ for schema in core::iter::once(&table.root).chain(
+ table
+ .join
+ .iter()
+ .flat_map(|v| v.iter().map(|Join::Inner { rhs, .. }| rhs)),
+ ) {
+ match is_sargable(schema, op) {
+ // found sargable equality condition for one of the table schemas
+ Some(IndexArgument::Eq { col_id, value }) => {
+ q = q.with_index_eq(schema.into(), col_id, value);
+ continue 'outer;
+ }
+ // found sargable range condition for one of the table schemas
+ Some(IndexArgument::LowerBound {
+ col_id,
+ value,
+ inclusive,
+ }) => {
+ q = q.with_index_lower_bound(schema.into(), col_id, value, inclusive);
+ continue 'outer;
+ }
+ // found sargable range condition for one of the table schemas
+ Some(IndexArgument::UpperBound {
+ col_id,
+ value,
+ inclusive,
+ }) => {
+ q = q.with_index_upper_bound(schema.into(), col_id, value, inclusive);
+ continue 'outer;
+ }
+ None => {}
}
}
+ // filter condition cannot be answered using an index
+ q = q.with_select(op.clone());
}
Ok(q)
}
diff --git a/crates/core/src/sql/compiler.rs b/crates/core/src/sql/compiler.rs
--- a/crates/core/src/sql/compiler.rs
+++ b/crates/core/src/sql/compiler.rs
@@ -122,7 +136,7 @@ pub enum IndexArgument {
// Sargable stands for Search ARGument ABLE.
// A sargable predicate is one that can be answered using an index.
-fn is_sargable(table: &From, op: &ColumnOp) -> Option<IndexArgument> {
+fn is_sargable(table: &TableSchema, op: &ColumnOp) -> Option<IndexArgument> {
if let ColumnOp::Cmp {
op: OpQuery::Cmp(op),
lhs,
diff --git a/crates/core/src/sql/compiler.rs b/crates/core/src/sql/compiler.rs
--- a/crates/core/src/sql/compiler.rs
+++ b/crates/core/src/sql/compiler.rs
@@ -138,12 +152,10 @@ fn is_sargable(table: &From, op: &ColumnOp) -> Option<IndexArgument> {
return None;
};
// lhs field must exist
- let column = table.root.get_column_by_field(name)?;
+ let column = table.get_column_by_field(name)?;
// lhs field must have an index
- let index =
- table.root.indexes.iter().find(|IndexSchema { table_id, col_id, .. }| {
- *table_id == column.table_id && *col_id == column.col_id
- })?;
+ let index = table.indexes.iter().find(|index| index.col_id == column.col_id)?;
+
match op {
OpCmp::Eq => Some(IndexArgument::Eq {
col_id: index.col_id,
diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs
--- a/crates/vm/src/expr.rs
+++ b/crates/vm/src/expr.rs
@@ -532,6 +532,31 @@ impl QueryExpr {
return self;
};
match query {
+ // try to push below join's lhs
+ Query::JoinInner(JoinExpr {
+ rhs:
+ QueryExpr {
+ source:
+ SourceExpr::DbTable(DbTable {
+ table_id: rhs_table_id, ..
+ }),
+ ..
+ },
+ ..
+ }) if table.table_id != rhs_table_id => {
+ self = self.with_index_eq(table, col_id, value);
+ self.query.push(query);
+ self
+ }
+ // try to push below join's rhs
+ Query::JoinInner(JoinExpr { rhs, col_lhs, col_rhs }) => {
+ self.query.push(Query::JoinInner(JoinExpr {
+ rhs: rhs.with_index_eq(table, col_id, value),
+ col_lhs,
+ col_rhs,
+ }));
+ self
+ }
// merge with a preceding select
Query::Select(filter) => {
self.query.push(Query::Select(ColumnOp::Cmp {
diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs
--- a/crates/vm/src/expr.rs
+++ b/crates/vm/src/expr.rs
@@ -585,6 +610,31 @@ impl QueryExpr {
return self;
};
match query {
+ // try to push below join's lhs
+ Query::JoinInner(JoinExpr {
+ rhs:
+ QueryExpr {
+ source:
+ SourceExpr::DbTable(DbTable {
+ table_id: rhs_table_id, ..
+ }),
+ ..
+ },
+ ..
+ }) if table.table_id != rhs_table_id => {
+ self = self.with_index_lower_bound(table, col_id, value, inclusive);
+ self.query.push(query);
+ self
+ }
+ // try to push below join's rhs
+ Query::JoinInner(JoinExpr { rhs, col_lhs, col_rhs }) => {
+ self.query.push(Query::JoinInner(JoinExpr {
+ rhs: rhs.with_index_lower_bound(table, col_id, value, inclusive),
+ col_lhs,
+ col_rhs,
+ }));
+ self
+ }
// merge with a preceding upper bounded index scan (inclusive)
Query::IndexScan(IndexScan {
col_id: lhs_col_id,
diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs
--- a/crates/vm/src/expr.rs
+++ b/crates/vm/src/expr.rs
@@ -668,6 +718,31 @@ impl QueryExpr {
return self;
};
match query {
+ // try to push below join's lhs
+ Query::JoinInner(JoinExpr {
+ rhs:
+ QueryExpr {
+ source:
+ SourceExpr::DbTable(DbTable {
+ table_id: rhs_table_id, ..
+ }),
+ ..
+ },
+ ..
+ }) if table.table_id != rhs_table_id => {
+ self = self.with_index_upper_bound(table, col_id, value, inclusive);
+ self.query.push(query);
+ self
+ }
+ // try to push below join's rhs
+ Query::JoinInner(JoinExpr { rhs, col_lhs, col_rhs }) => {
+ self.query.push(Query::JoinInner(JoinExpr {
+ rhs: rhs.with_index_upper_bound(table, col_id, value, inclusive),
+ col_lhs,
+ col_rhs,
+ }));
+ self
+ }
// merge with a preceding lower bounded index scan (inclusive)
Query::IndexScan(IndexScan {
col_id: lhs_col_id,
diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs
--- a/crates/vm/src/expr.rs
+++ b/crates/vm/src/expr.rs
@@ -940,7 +1015,7 @@ impl fmt::Display for Query {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Query::IndexScan(op) => {
- write!(f, "ixscan {:?}", op)
+ write!(f, "index_scan {:?}", op)
}
Query::Select(q) => {
write!(f, "select {q}")
|
diff --git a/crates/core/src/sql/compiler.rs b/crates/core/src/sql/compiler.rs
--- a/crates/core/src/sql/compiler.rs
+++ b/crates/core/src/sql/compiler.rs
@@ -386,8 +398,8 @@ mod tests {
auth::{StAccess, StTableType},
error::ResultTest,
};
- use spacetimedb_sats::AlgebraicType;
- use spacetimedb_vm::expr::{IndexScan, Query};
+ use spacetimedb_sats::{AlgebraicType, BuiltinValue};
+ use spacetimedb_vm::expr::{IndexScan, JoinExpr, Query};
use crate::db::{
datastore::traits::{ColumnDef, IndexDef, TableDef},
diff --git a/crates/core/src/sql/compiler.rs b/crates/core/src/sql/compiler.rs
--- a/crates/core/src/sql/compiler.rs
+++ b/crates/core/src/sql/compiler.rs
@@ -400,7 +412,7 @@ mod tests {
name: &str,
schema: &[(&str, AlgebraicType)],
indexes: &[(u32, &str)],
- ) -> ResultTest<()> {
+ ) -> ResultTest<u32> {
let table_name = name.to_string();
let table_type = StTableType::User;
let table_access = StAccess::Public;
diff --git a/crates/core/src/sql/compiler.rs b/crates/core/src/sql/compiler.rs
--- a/crates/core/src/sql/compiler.rs
+++ b/crates/core/src/sql/compiler.rs
@@ -432,8 +444,7 @@ mod tests {
table_access,
};
- db.create_table(tx, schema)?;
- Ok(())
+ Ok(db.create_table(tx, schema)?)
}
#[test]
diff --git a/crates/core/src/sql/compiler.rs b/crates/core/src/sql/compiler.rs
--- a/crates/core/src/sql/compiler.rs
+++ b/crates/core/src/sql/compiler.rs
@@ -716,4 +727,168 @@ mod tests {
};
Ok(())
}
+
+ #[test]
+ fn compile_join_lhs_push_down() -> ResultTest<()> {
+ let (db, _) = make_test_db()?;
+ let mut tx = db.begin_tx();
+
+ // Create table [lhs] with index on [a]
+ let schema = &[("a", AlgebraicType::U64), ("b", AlgebraicType::U64)];
+ let indexes = &[(0, "a")];
+ let lhs_id = create_table(&db, &mut tx, "lhs", schema, indexes)?;
+
+ // Create table [rhs] with no indexes
+ let schema = &[("b", AlgebraicType::U64), ("c", AlgebraicType::U64)];
+ let indexes = &[];
+ let rhs_id = create_table(&db, &mut tx, "rhs", schema, indexes)?;
+
+ // Should push sargable equality condition below join
+ let sql = "select * from lhs join rhs on lhs.b = rhs.b where lhs.a = 3";
+ let exp = compile_sql(&db, &tx, sql)?.remove(0);
+
+ let CrudExpr::Query(QueryExpr {
+ source: SourceExpr::DbTable(DbTable { table_id, .. }),
+ query,
+ ..
+ }) = exp
+ else {
+ panic!("unexpected expression: {:#?}", exp);
+ };
+
+ assert_eq!(table_id, lhs_id);
+ assert_eq!(query.len(), 2);
+
+ // First operation in the pipeline should be an index scan
+ let Query::IndexScan(IndexScan {
+ table: DbTable { table_id, .. },
+ col_id: 0,
+ lower_bound: Bound::Included(AlgebraicValue::Builtin(BuiltinValue::U64(3))),
+ upper_bound: Bound::Included(AlgebraicValue::Builtin(BuiltinValue::U64(3))),
+ }) = query[0]
+ else {
+ panic!("unexpected operator {:#?}", query[0]);
+ };
+
+ assert_eq!(table_id, lhs_id);
+
+ // Followed by a join with the rhs table
+ let Query::JoinInner(JoinExpr {
+ rhs:
+ QueryExpr {
+ source: SourceExpr::DbTable(DbTable { table_id, .. }),
+ ..
+ },
+ col_lhs:
+ FieldName::Name {
+ table: ref lhs_table,
+ field: ref lhs_field,
+ },
+ col_rhs:
+ FieldName::Name {
+ table: ref rhs_table,
+ field: ref rhs_field,
+ },
+ }) = query[1]
+ else {
+ panic!("unexpected operator {:#?}", query[1]);
+ };
+
+ assert_eq!(table_id, rhs_id);
+ assert_eq!(lhs_field, "b");
+ assert_eq!(rhs_field, "b");
+ assert_eq!(lhs_table, "lhs");
+ assert_eq!(rhs_table, "rhs");
+ Ok(())
+ }
+
+ #[test]
+ fn compile_join_lhs_and_rhs_push_down() -> ResultTest<()> {
+ let (db, _) = make_test_db()?;
+ let mut tx = db.begin_tx();
+
+ // Create table [lhs] with index on [a]
+ let schema = &[("a", AlgebraicType::U64), ("b", AlgebraicType::U64)];
+ let indexes = &[(0, "a")];
+ let lhs_id = create_table(&db, &mut tx, "lhs", schema, indexes)?;
+
+ // Create table [rhs] with index on [c]
+ let schema = &[("b", AlgebraicType::U64), ("c", AlgebraicType::U64)];
+ let indexes = &[(1, "c")];
+ let rhs_id = create_table(&db, &mut tx, "rhs", schema, indexes)?;
+
+ // Should push the sargable equality condition into the join's left arg.
+ // Should push the sargable range condition into the join's right arg.
+ let sql = "select * from lhs join rhs on lhs.b = rhs.b where lhs.a = 3 and rhs.c < 4";
+ let exp = compile_sql(&db, &tx, sql)?.remove(0);
+
+ let CrudExpr::Query(QueryExpr {
+ source: SourceExpr::DbTable(DbTable { table_id, .. }),
+ query,
+ ..
+ }) = exp
+ else {
+ panic!("unexpected result from compilation: {:?}", exp);
+ };
+
+ assert_eq!(table_id, lhs_id);
+ assert_eq!(query.len(), 2);
+
+ // First operation in the pipeline should be an index scan
+ let Query::IndexScan(IndexScan {
+ table: DbTable { table_id, .. },
+ col_id: 0,
+ lower_bound: Bound::Included(AlgebraicValue::Builtin(BuiltinValue::U64(3))),
+ upper_bound: Bound::Included(AlgebraicValue::Builtin(BuiltinValue::U64(3))),
+ }) = query[0]
+ else {
+ panic!("unexpected operator {:#?}", query[0]);
+ };
+
+ assert_eq!(table_id, lhs_id);
+
+ // Followed by a join
+ let Query::JoinInner(JoinExpr {
+ rhs:
+ QueryExpr {
+ source: SourceExpr::DbTable(DbTable { table_id, .. }),
+ query: ref rhs,
+ },
+ col_lhs:
+ FieldName::Name {
+ table: ref lhs_table,
+ field: ref lhs_field,
+ },
+ col_rhs:
+ FieldName::Name {
+ table: ref rhs_table,
+ field: ref rhs_field,
+ },
+ }) = query[1]
+ else {
+ panic!("unexpected operator {:#?}", query[1]);
+ };
+
+ assert_eq!(table_id, rhs_id);
+ assert_eq!(lhs_field, "b");
+ assert_eq!(rhs_field, "b");
+ assert_eq!(lhs_table, "lhs");
+ assert_eq!(rhs_table, "rhs");
+
+ assert_eq!(1, rhs.len());
+
+ // The right side of the join should be an index scan
+ let Query::IndexScan(IndexScan {
+ table: DbTable { table_id, .. },
+ col_id: 1,
+ lower_bound: Bound::Unbounded,
+ upper_bound: Bound::Excluded(AlgebraicValue::Builtin(BuiltinValue::U64(4))),
+ }) = rhs[0]
+ else {
+ panic!("unexpected operator {:#?}", rhs[0]);
+ };
+
+ assert_eq!(table_id, rhs_id);
+ Ok(())
+ }
}
|
Push index scans below joins
|
2023-09-21T09:16:00Z
|
1.0
|
2023-09-22T16:14:38Z
|
e395e4ee30c7b4f142bf927d1151662ecedc763b
|
[
"sql::compiler::tests::compile_join_lhs_push_down",
"sql::compiler::tests::compile_join_lhs_and_rhs_push_down"
] |
[
"client::message_handlers::tests::parse_one_off_query",
"db::datastore::locking_tx_datastore::tests::test_bootstrapping_sets_up_tables",
"db::datastore::locking_tx_datastore::tests::test_create_table_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_create_table_post_commit",
"db::datastore::locking_tx_datastore::tests::test_create_index_post_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_delete_insert_delete_insert",
"db::datastore::locking_tx_datastore::tests::test_insert_commit_delete_insert",
"db::datastore::locking_tx_datastore::tests::test_create_index_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_create_index_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_create_table_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_post_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_wrong_schema_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_post_commit",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_alter_indexes",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_update_reinsert",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_rollback",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_post_commit",
"db::message_log::tests::test_message_log",
"db::ostorage::hashmap_object_db::tests::test_flush",
"db::ostorage::hashmap_object_db::tests::test_flush_sync_all",
"db::ostorage::hashmap_object_db::tests::test_miss",
"db::ostorage::hashmap_object_db::tests::test_size",
"db::ostorage::hashmap_object_db::tests::test_add_and_get",
"db::relational_db::tests::test_auto_inc",
"db::relational_db::tests::test",
"db::relational_db::tests::test_auto_inc_disable",
"db::relational_db::tests::test_cascade_drop_table",
"db::relational_db::tests::test_auto_inc_reload",
"db::relational_db::tests::test_column_name",
"db::relational_db::tests::test_create_table_pre_commit",
"db::relational_db::tests::test_create_table_rollback",
"db::relational_db::tests::test_filter_range_post_commit",
"db::relational_db::tests::test_filter_range_pre_commit",
"db::relational_db::tests::test_identity",
"db::relational_db::tests::test_open_twice",
"db::relational_db::tests::test_indexed",
"db::relational_db::tests::test_post_commit",
"db::relational_db::tests::test_pre_commit",
"db::relational_db::tests::test_rename_table",
"db::relational_db::tests::test_unique",
"db::relational_db::tests::test_rollback",
"db::relational_db::tests::test_table_name",
"sql::compiler::tests::compile_eq",
"sql::compiler::tests::compile_eq_and_eq",
"sql::compiler::tests::compile_index_eq_and_eq",
"sql::compiler::tests::compile_index_eq_select_range",
"sql::compiler::tests::compile_eq_or_eq",
"sql::compiler::tests::compile_index_eq",
"sql::compiler::tests::compile_index_range_closed",
"sql::compiler::tests::compile_index_range_open",
"sql::execute::tests::test_big_sql",
"sql::execute::tests::test_column_constraints",
"sql::execute::tests::test_create_table",
"sql::execute::tests::test_inner_join",
"sql::execute::tests::test_delete",
"sql::execute::tests::test_drop_table",
"sql::execute::tests::test_insert",
"sql::execute::tests::test_nested",
"sql::execute::tests::test_or",
"sql::execute::tests::test_select_catalog",
"sql::execute::tests::test_select_scalar",
"sql::execute::tests::test_select_column",
"sql::execute::tests::test_select_multiple",
"sql::execute::tests::test_select_star",
"sql::execute::tests::test_select_star_table",
"subscription::query::tests::test_eval_incr_maintains_row_ids",
"sql::execute::tests::test_update",
"sql::execute::tests::test_where",
"subscription::query::tests::test_subscribe",
"subscription::query::tests::test_subscribe_commutative",
"subscription::query::tests::test_subscribe_all",
"subscription::query::tests::test_subscribe_private",
"subscription::query::tests::test_subscribe_dedup",
"subscription::query::tests::test_subscribe_sql",
"vm::tests::test_db_query",
"vm::tests::test_query_catalog_columns",
"vm::tests::test_query_catalog_indexes",
"vm::tests::test_query_catalog_tables",
"vm::tests::test_query_catalog_sequences",
"control_db::tests::test_register_tld",
"db::ostorage::sled_object_db::tests::test_miss",
"db::ostorage::sled_object_db::tests::test_flush",
"control_db::tests::test_domain",
"db::ostorage::sled_object_db::tests::test_add_and_get",
"db::ostorage::sled_object_db::tests::test_flush_sync_all",
"db::message_log::tests::test_message_log_reopen"
] |
[] |
[] |
|
clockworklabs/SpacetimeDB
| 1,894
|
clockworklabs__SpacetimeDB-1894
|
[
"1818"
] |
9c64d1fbd17e99bbb8db1479492d88ba7578acc9
|
diff --git a/crates/bindings-macro/src/lib.rs b/crates/bindings-macro/src/lib.rs
--- a/crates/bindings-macro/src/lib.rs
+++ b/crates/bindings-macro/src/lib.rs
@@ -45,6 +45,7 @@ mod sym {
symbol!(public);
symbol!(sats);
symbol!(scheduled);
+ symbol!(scheduled_at);
symbol!(unique);
symbol!(update);
diff --git a/crates/bindings-macro/src/lib.rs b/crates/bindings-macro/src/lib.rs
--- a/crates/bindings-macro/src/lib.rs
+++ b/crates/bindings-macro/src/lib.rs
@@ -154,7 +155,7 @@ mod sym {
pub fn reducer(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream {
cvt_attr::<ItemFn>(args, item, quote!(), |args, original_function| {
let args = reducer::ReducerArgs::parse(args)?;
- reducer::reducer_impl(args, &original_function)
+ reducer::reducer_impl(args, original_function)
})
}
diff --git a/crates/bindings-macro/src/lib.rs b/crates/bindings-macro/src/lib.rs
--- a/crates/bindings-macro/src/lib.rs
+++ b/crates/bindings-macro/src/lib.rs
@@ -241,7 +242,7 @@ pub fn table(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream {
/// Provides helper attributes for `#[spacetimedb::table]`, so that we don't get unknown attribute errors.
#[doc(hidden)]
-#[proc_macro_derive(__TableHelper, attributes(sats, unique, auto_inc, primary_key, index))]
+#[proc_macro_derive(__TableHelper, attributes(sats, unique, auto_inc, primary_key, index, scheduled_at))]
pub fn table_helper(_input: StdTokenStream) -> StdTokenStream {
Default::default()
}
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -1,6 +1,6 @@
use crate::sats::{self, derive_deserialize, derive_satstype, derive_serialize};
use crate::sym;
-use crate::util::{check_duplicate, check_duplicate_msg, ident_to_litstr, match_meta, MutItem};
+use crate::util::{check_duplicate, check_duplicate_msg, ident_to_litstr, match_meta};
use heck::ToSnakeCase;
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, quote_spanned, ToTokens};
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -36,21 +36,6 @@ impl TableAccess {
}
}
-// add scheduled_id and scheduled_at fields to the struct
-fn add_scheduled_fields(item: &mut syn::DeriveInput) {
- if let syn::Data::Struct(struct_data) = &mut item.data {
- if let syn::Fields::Named(fields) = &mut struct_data.fields {
- let extra_fields: syn::FieldsNamed = parse_quote!({
- #[primary_key]
- #[auto_inc]
- pub scheduled_id: u64,
- pub scheduled_at: spacetimedb::spacetimedb_lib::ScheduleAt,
- });
- fields.named.extend(extra_fields.named);
- }
- }
-}
-
struct IndexArg {
name: Ident,
kind: IndexType,
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -365,6 +350,7 @@ enum ColumnAttr {
AutoInc(Span),
PrimaryKey(Span),
Index(IndexArg),
+ ScheduledAt(Span),
}
impl ColumnAttr {
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -384,23 +370,18 @@ impl ColumnAttr {
} else if ident == sym::primary_key {
attr.meta.require_path_only()?;
Some(ColumnAttr::PrimaryKey(ident.span()))
+ } else if ident == sym::scheduled_at {
+ attr.meta.require_path_only()?;
+ Some(ColumnAttr::ScheduledAt(ident.span()))
} else {
None
})
}
}
-pub(crate) fn table_impl(mut args: TableArgs, mut item: MutItem<syn::DeriveInput>) -> syn::Result<TokenStream> {
- let scheduled_reducer_type_check = args.scheduled.as_ref().map(|reducer| {
- add_scheduled_fields(&mut item);
- let struct_name = &item.ident;
- quote! {
- const _: () = spacetimedb::rt::scheduled_reducer_typecheck::<#struct_name>(#reducer);
- }
- });
-
+pub(crate) fn table_impl(mut args: TableArgs, item: &syn::DeriveInput) -> syn::Result<TokenStream> {
let vis = &item.vis;
- let sats_ty = sats::sats_type_from_derive(&item, quote!(spacetimedb::spacetimedb_lib))?;
+ let sats_ty = sats::sats_type_from_derive(item, quote!(spacetimedb::spacetimedb_lib))?;
let original_struct_ident = sats_ty.ident;
let table_ident = &args.name;
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -429,7 +410,7 @@ pub(crate) fn table_impl(mut args: TableArgs, mut item: MutItem<syn::DeriveInput
if fields.len() > u16::MAX.into() {
return Err(syn::Error::new_spanned(
- &*item,
+ item,
"too many columns; the most a table can have is 2^16",
));
}
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -438,6 +419,7 @@ pub(crate) fn table_impl(mut args: TableArgs, mut item: MutItem<syn::DeriveInput
let mut unique_columns = vec![];
let mut sequenced_columns = vec![];
let mut primary_key_column = None;
+ let mut scheduled_at_column = None;
for (i, field) in fields.iter().enumerate() {
let col_num = i as u16;
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -446,6 +428,7 @@ pub(crate) fn table_impl(mut args: TableArgs, mut item: MutItem<syn::DeriveInput
let mut unique = None;
let mut auto_inc = None;
let mut primary_key = None;
+ let mut scheduled_at = None;
for attr in field.original_attrs {
let Some(attr) = ColumnAttr::parse(attr, field_ident)? else {
continue;
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -464,6 +447,10 @@ pub(crate) fn table_impl(mut args: TableArgs, mut item: MutItem<syn::DeriveInput
primary_key = Some(span);
}
ColumnAttr::Index(index_arg) => args.indices.push(index_arg),
+ ColumnAttr::ScheduledAt(span) => {
+ check_duplicate(&scheduled_at, span)?;
+ scheduled_at = Some(span);
+ }
}
}
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -489,10 +476,27 @@ pub(crate) fn table_impl(mut args: TableArgs, mut item: MutItem<syn::DeriveInput
check_duplicate_msg(&primary_key_column, span, "can only have one primary key per table")?;
primary_key_column = Some(column);
}
+ if let Some(span) = scheduled_at {
+ check_duplicate_msg(
+ &scheduled_at_column,
+ span,
+ "can only have one scheduled_at column per table",
+ )?;
+ scheduled_at_column = Some(column);
+ }
columns.push(column);
}
+ let scheduled_at_typecheck = scheduled_at_column.map(|col| {
+ let ty = col.ty;
+ quote!(let _ = |x: #ty| { let _: spacetimedb::ScheduleAt = x; };)
+ });
+ let scheduled_id_typecheck = primary_key_column.filter(|_| args.scheduled.is_some()).map(|col| {
+ let ty = col.ty;
+ quote!(spacetimedb::rt::assert_scheduled_table_primary_key::<#ty>();)
+ });
+
let row_type = quote!(#original_struct_ident);
let mut indices = args
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -540,17 +544,46 @@ pub(crate) fn table_impl(mut args: TableArgs, mut item: MutItem<syn::DeriveInput
let primary_col_id = primary_key_column.iter().map(|col| col.index);
let sequence_col_ids = sequenced_columns.iter().map(|col| col.index);
+ let scheduled_reducer_type_check = args.scheduled.as_ref().map(|reducer| {
+ quote! {
+ spacetimedb::rt::scheduled_reducer_typecheck::<#original_struct_ident>(#reducer);
+ }
+ });
let schedule = args
.scheduled
.as_ref()
.map(|reducer| {
- // scheduled_at was inserted as the last field
- let scheduled_at_id = (fields.len() - 1) as u16;
- quote!(spacetimedb::table::ScheduleDesc {
+ // better error message when both are missing
+ if scheduled_at_column.is_none() && primary_key_column.is_none() {
+ return Err(syn::Error::new(
+ original_struct_ident.span(),
+ "scheduled table missing required columns; add these to your struct:\n\
+ #[primary_key]\n\
+ #[auto_inc]\n\
+ scheduled_id: u64,\n\
+ #[scheduled_at]\n\
+ scheduled_at: spacetimedb::ScheduleAt,",
+ ));
+ }
+ let scheduled_at_column = scheduled_at_column.ok_or_else(|| {
+ syn::Error::new(
+ original_struct_ident.span(),
+ "scheduled tables must have a `#[scheduled_at] scheduled_at: spacetimedb::ScheduleAt` column.",
+ )
+ })?;
+ let scheduled_at_id = scheduled_at_column.index;
+ if primary_key_column.is_none() {
+ return Err(syn::Error::new(
+ original_struct_ident.span(),
+ "scheduled tables should have a `#[primary_key] #[auto_inc] scheduled_id: u64` column",
+ ));
+ }
+ Ok(quote!(spacetimedb::table::ScheduleDesc {
reducer_name: <#reducer as spacetimedb::rt::ReducerInfo>::NAME,
scheduled_at_column: #scheduled_at_id,
- })
+ }))
})
+ .transpose()?
.into_iter();
let unique_err = if !unique_columns.is_empty() {
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -564,7 +597,6 @@ pub(crate) fn table_impl(mut args: TableArgs, mut item: MutItem<syn::DeriveInput
quote!(::core::convert::Infallible)
};
- let field_names = fields.iter().map(|f| f.ident.unwrap()).collect::<Vec<_>>();
let field_types = fields.iter().map(|f| f.ty).collect::<Vec<_>>();
let tabletype_impl = quote! {
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -599,16 +631,6 @@ pub(crate) fn table_impl(mut args: TableArgs, mut item: MutItem<syn::DeriveInput
}
};
- let col_num = 0u16..;
- let field_access_impls = quote! {
- #(impl spacetimedb::table::FieldAccess<#col_num> for #original_struct_ident {
- type Field = #field_types;
- fn get_field(&self) -> &Self::Field {
- &self.#field_names
- }
- })*
- };
-
let row_type_to_table = quote!(<#row_type as spacetimedb::table::__MapRowTypeToTable>::Table);
// Output all macro data
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -635,6 +657,9 @@ pub(crate) fn table_impl(mut args: TableArgs, mut item: MutItem<syn::DeriveInput
let emission = quote! {
const _: () = {
#(let _ = <#field_types as spacetimedb::rt::TableColumn>::_ITEM;)*
+ #scheduled_reducer_type_check
+ #scheduled_at_typecheck
+ #scheduled_id_typecheck
};
#trait_def
diff --git a/crates/bindings-macro/src/table.rs b/crates/bindings-macro/src/table.rs
--- a/crates/bindings-macro/src/table.rs
+++ b/crates/bindings-macro/src/table.rs
@@ -669,10 +694,6 @@ pub(crate) fn table_impl(mut args: TableArgs, mut item: MutItem<syn::DeriveInput
#schema_impl
#deserialize_impl
#serialize_impl
-
- #field_access_impls
-
- #scheduled_reducer_type_check
};
if std::env::var("PROC_MACRO_DEBUG").is_ok() {
diff --git a/crates/bindings-macro/src/util.rs b/crates/bindings-macro/src/util.rs
--- a/crates/bindings-macro/src/util.rs
+++ b/crates/bindings-macro/src/util.rs
@@ -10,24 +10,14 @@ pub(crate) fn cvt_attr<Item: Parse + quote::ToTokens>(
args: StdTokenStream,
item: StdTokenStream,
extra_attr: TokenStream,
- f: impl FnOnce(TokenStream, MutItem<'_, Item>) -> syn::Result<TokenStream>,
+ f: impl FnOnce(TokenStream, &Item) -> syn::Result<TokenStream>,
) -> StdTokenStream {
let item: TokenStream = item.into();
- let mut parsed_item = match syn::parse2::<Item>(item.clone()) {
+ let parsed_item = match syn::parse2::<Item>(item.clone()) {
Ok(i) => i,
Err(e) => return TokenStream::from_iter([item, e.into_compile_error()]).into(),
};
- let mut modified = false;
- let mut_item = MutItem {
- val: &mut parsed_item,
- modified: &mut modified,
- };
- let generated = f(args.into(), mut_item).unwrap_or_else(syn::Error::into_compile_error);
- let item = if modified {
- parsed_item.into_token_stream()
- } else {
- item
- };
+ let generated = f(args.into(), &parsed_item).unwrap_or_else(syn::Error::into_compile_error);
TokenStream::from_iter([extra_attr, item, generated]).into()
}
diff --git a/crates/bindings-macro/src/util.rs b/crates/bindings-macro/src/util.rs
--- a/crates/bindings-macro/src/util.rs
+++ b/crates/bindings-macro/src/util.rs
@@ -35,23 +25,6 @@ pub(crate) fn ident_to_litstr(ident: &Ident) -> syn::LitStr {
syn::LitStr::new(&ident.to_string(), ident.span())
}
-pub(crate) struct MutItem<'a, T> {
- val: &'a mut T,
- modified: &'a mut bool,
-}
-impl<T> std::ops::Deref for MutItem<'_, T> {
- type Target = T;
- fn deref(&self) -> &Self::Target {
- self.val
- }
-}
-impl<T> std::ops::DerefMut for MutItem<'_, T> {
- fn deref_mut(&mut self) -> &mut Self::Target {
- *self.modified = true;
- self.val
- }
-}
-
pub(crate) trait ErrorSource {
fn error(self, msg: impl std::fmt::Display) -> syn::Error;
}
diff --git a/crates/bindings/src/table.rs b/crates/bindings/src/table.rs
--- a/crates/bindings/src/table.rs
+++ b/crates/bindings/src/table.rs
@@ -262,19 +262,6 @@ impl MaybeError for AutoIncOverflow {
}
}
-/// A trait for types exposing an operation to access their `N`th field.
-///
-/// In other words, a type implementing `FieldAccess<N>` allows
-/// shared projection from `self` to its `N`th field.
-#[doc(hidden)]
-pub trait FieldAccess<const N: u16> {
- /// The type of the field at the `N`th position.
- type Field;
-
- /// Project to the value of the field at position `N`.
- fn get_field(&self) -> &Self::Field;
-}
-
pub trait Column {
type Row;
type ColType;
|
diff --git a/crates/bindings/tests/ui/reducers.rs b/crates/bindings/tests/ui/reducers.rs
--- a/crates/bindings/tests/ui/reducers.rs
+++ b/crates/bindings/tests/ui/reducers.rs
@@ -25,8 +25,22 @@ fn missing_ctx(_a: u8) {}
#[spacetimedb::reducer]
fn ctx_by_val(_ctx: ReducerContext, _a: u8) {}
+#[spacetimedb::table(name = scheduled_table_missing_rows, scheduled(scheduled_table_missing_rows_reducer))]
+struct ScheduledTableMissingRows {
+ x: u8,
+ y: u8,
+}
+
+// #[spacetimedb::reducer]
+// fn scheduled_table_missing_rows_reducer(_ctx: &ReducerContext, _: &ScheduledTableMissingRows) {}
+
#[spacetimedb::table(name = scheduled_table, scheduled(scheduled_table_reducer))]
struct ScheduledTable {
+ #[primary_key]
+ #[auto_inc]
+ scheduled_id: u64,
+ #[scheduled_at]
+ scheduled_at: spacetimedb::ScheduleAt,
x: u8,
y: u8,
}
diff --git a/crates/bindings/tests/ui/reducers.stderr b/crates/bindings/tests/ui/reducers.stderr
--- a/crates/bindings/tests/ui/reducers.stderr
+++ b/crates/bindings/tests/ui/reducers.stderr
@@ -10,16 +10,27 @@ error: const parameters are not allowed on reducers
20 | fn const_param<const X: u8>() {}
| ^^^^^^^^^^^
+error: scheduled table missing required columns; add these to your struct:
+ #[primary_key]
+ #[auto_inc]
+ scheduled_id: u64,
+ #[scheduled_at]
+ scheduled_at: spacetimedb::ScheduleAt,
+ --> tests/ui/reducers.rs:29:8
+ |
+29 | struct ScheduledTableMissingRows {
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^
+
error[E0593]: function is expected to take 2 arguments, but it takes 3 arguments
- --> tests/ui/reducers.rs:28:56
+ --> tests/ui/reducers.rs:37:56
|
-28 | #[spacetimedb::table(name = scheduled_table, scheduled(scheduled_table_reducer))]
+37 | #[spacetimedb::table(name = scheduled_table, scheduled(scheduled_table_reducer))]
| -------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^---
| | |
| | expected function that takes 2 arguments
| required by a bound introduced by this call
...
-35 | fn scheduled_table_reducer(_ctx: &ReducerContext, _x: u8, _y: u8) {}
+49 | fn scheduled_table_reducer(_ctx: &ReducerContext, _x: u8, _y: u8) {}
| ----------------------------------------------------------------- takes 3 arguments
|
= note: required for `for<'a> fn(&'a ReducerContext, u8, u8) {scheduled_table_reducer}` to implement `Reducer<'_, (ScheduledTable,)>`
diff --git a/crates/cli/tests/snapshots/codegen__codegen_csharp.snap b/crates/cli/tests/snapshots/codegen__codegen_csharp.snap
--- a/crates/cli/tests/snapshots/codegen__codegen_csharp.snap
+++ b/crates/cli/tests/snapshots/codegen__codegen_csharp.snap
@@ -372,22 +372,22 @@ namespace SpacetimeDB
[DataContract]
public partial class RepeatingTestArg : IDatabaseRow
{
- [DataMember(Name = "prev_time")]
- public ulong PrevTime;
[DataMember(Name = "scheduled_id")]
public ulong ScheduledId;
[DataMember(Name = "scheduled_at")]
public SpacetimeDB.ScheduleAt ScheduledAt;
+ [DataMember(Name = "prev_time")]
+ public ulong PrevTime;
public RepeatingTestArg(
- ulong PrevTime,
ulong ScheduledId,
- SpacetimeDB.ScheduleAt ScheduledAt
+ SpacetimeDB.ScheduleAt ScheduledAt,
+ ulong PrevTime
)
{
- this.PrevTime = PrevTime;
this.ScheduledId = ScheduledId;
this.ScheduledAt = ScheduledAt;
+ this.PrevTime = PrevTime;
}
public RepeatingTestArg()
diff --git a/crates/cli/tests/snapshots/codegen__codegen_rust.snap b/crates/cli/tests/snapshots/codegen__codegen_rust.snap
--- a/crates/cli/tests/snapshots/codegen__codegen_rust.snap
+++ b/crates/cli/tests/snapshots/codegen__codegen_rust.snap
@@ -2003,9 +2003,9 @@ pub(super) fn parse_table_update(
#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)]
#[sats(crate = __lib)]
pub struct RepeatingTestArg {
- pub prev_time: u64,
pub scheduled_id: u64,
pub scheduled_at: __sdk::ScheduleAt,
+ pub prev_time: u64,
}
diff --git a/crates/cli/tests/snapshots/codegen__codegen_typescript.snap b/crates/cli/tests/snapshots/codegen__codegen_typescript.snap
--- a/crates/cli/tests/snapshots/codegen__codegen_typescript.snap
+++ b/crates/cli/tests/snapshots/codegen__codegen_typescript.snap
@@ -2165,9 +2165,9 @@ import {
deepEqual,
} from "@clockworklabs/spacetimedb-sdk";
export type RepeatingTestArg = {
- prevTime: bigint,
scheduledId: bigint,
scheduledAt: { tag: "Interval", value: bigint } | { tag: "Time", value: bigint },
+ prevTime: bigint,
};
/**
diff --git a/crates/cli/tests/snapshots/codegen__codegen_typescript.snap b/crates/cli/tests/snapshots/codegen__codegen_typescript.snap
--- a/crates/cli/tests/snapshots/codegen__codegen_typescript.snap
+++ b/crates/cli/tests/snapshots/codegen__codegen_typescript.snap
@@ -2180,9 +2180,9 @@ export namespace RepeatingTestArg {
*/
export function getTypeScriptAlgebraicType(): AlgebraicType {
return AlgebraicType.createProductType([
- new ProductTypeElement("prevTime", AlgebraicType.createU64Type()),
new ProductTypeElement("scheduledId", AlgebraicType.createU64Type()),
new ProductTypeElement("scheduledAt", AlgebraicType.createScheduleAtType()),
+ new ProductTypeElement("prevTime", AlgebraicType.createU64Type()),
]);
}
diff --git a/modules/rust-wasm-test/src/lib.rs b/modules/rust-wasm-test/src/lib.rs
--- a/modules/rust-wasm-test/src/lib.rs
+++ b/modules/rust-wasm-test/src/lib.rs
@@ -104,6 +104,11 @@ pub type TestAlias = TestA;
#[spacetimedb::table(name = repeating_test_arg, scheduled(repeating_test))]
pub struct RepeatingTestArg {
+ #[primary_key]
+ #[auto_inc]
+ scheduled_id: u64,
+ #[scheduled_at]
+ scheduled_at: spacetimedb::ScheduleAt,
prev_time: Timestamp,
}
diff --git a/smoketests/tests/modules.py b/smoketests/tests/modules.py
--- a/smoketests/tests/modules.py
+++ b/smoketests/tests/modules.py
@@ -144,6 +144,11 @@ class UploadModule2(Smoketest):
#[spacetimedb::table(name = scheduled_message, public, scheduled(my_repeating_reducer))]
pub struct ScheduledMessage {
+ #[primary_key]
+ #[auto_inc]
+ scheduled_id: u64,
+ #[scheduled_at]
+ scheduled_at: spacetimedb::ScheduleAt,
prev: Timestamp,
}
diff --git a/smoketests/tests/schedule_reducer.py b/smoketests/tests/schedule_reducer.py
--- a/smoketests/tests/schedule_reducer.py
+++ b/smoketests/tests/schedule_reducer.py
@@ -25,6 +25,11 @@ class CancelReducer(Smoketest):
#[spacetimedb::table(name = scheduled_reducer_args, public, scheduled(reducer))]
pub struct ScheduledReducerArgs {
+ #[primary_key]
+ #[auto_inc]
+ scheduled_id: u64,
+ #[scheduled_at]
+ scheduled_at: spacetimedb::ScheduleAt,
num: i32,
}
diff --git a/smoketests/tests/schedule_reducer.py b/smoketests/tests/schedule_reducer.py
--- a/smoketests/tests/schedule_reducer.py
+++ b/smoketests/tests/schedule_reducer.py
@@ -53,6 +58,11 @@ class SubscribeScheduledTable(Smoketest):
#[spacetimedb::table(name = scheduled_table, public, scheduled(my_reducer))]
pub struct ScheduledTable {
+ #[primary_key]
+ #[auto_inc]
+ scheduled_id: u64,
+ #[scheduled_at]
+ scheduled_at: spacetimedb::ScheduleAt,
prev: Timestamp,
}
|
`#[spacetimedb::table(scheduled())]` should probably not autogen the scheduled_id/at fields for you - should just require they already be present
UX story:
> Someone new comes to the codebase and wants to insert a row into the table. the compiler complains "missing fields scheduled_id and schedule_at" and so they go to the struct definition but they're not there. what the heck are they?? what do they do?? how is the compiler complaining about these fields that don't exist??
|
2024-10-24T02:23:38Z
|
1.78
|
2025-02-11T02:53:30Z
|
8075567da42408ecf53146fb3f72832e41d8a956
|
[
"ui"
] |
[
"deptree_snapshot",
"tests/ui/tables.rs",
"crates/bindings/src/rng.rs - rng::ReducerContext::rng (line 30)"
] |
[] |
[] |
|
clockworklabs/SpacetimeDB
| 336
|
clockworklabs__SpacetimeDB-336
|
[
"332"
] |
c71d24c1f9356fea95c9641ff521fda048a141f0
|
diff --git a/crates/core/src/vm.rs b/crates/core/src/vm.rs
--- a/crates/core/src/vm.rs
+++ b/crates/core/src/vm.rs
@@ -46,16 +46,20 @@ pub fn build_query<'a>(
let iter = result.select(move |row| cmp.compare(row, &header));
Box::new(iter)
}
- Query::IndexJoin(join) => Box::new(IndexSemiJoin {
- probe_side: build_query(stdb, tx, join.probe_side.into())?,
- probe_field: join.probe_field,
- index_header: join.index_header,
- index_table: join.index_table,
- index_col: join.index_col,
- index_iter: None,
- db: stdb,
+ Query::IndexJoin(join) if db_table => Box::new(IndexSemiJoin::new(
+ stdb,
tx,
- }) as Box<IterRows<'_>>,
+ build_query(stdb, tx, join.probe_side.into())?,
+ join.probe_field,
+ join.index_header,
+ join.index_table,
+ join.index_col,
+ )),
+ Query::IndexJoin(join) => {
+ let join: JoinExpr = join.into();
+ let iter = join_inner(stdb, tx, result, join, true)?;
+ Box::new(iter)
+ }
Query::Select(cmp) => {
let header = result.head().clone();
let iter = result.select(move |row| cmp.compare(row, &header));
diff --git a/crates/core/src/vm.rs b/crates/core/src/vm.rs
--- a/crates/core/src/vm.rs
+++ b/crates/core/src/vm.rs
@@ -70,36 +74,8 @@ pub fn build_query<'a>(
Box::new(iter)
}
}
- Query::JoinInner(q) => {
- //Pick the smaller set to be at the left
- let col_lhs = FieldExpr::Name(q.col_lhs);
- let col_rhs = FieldExpr::Name(q.col_rhs);
- let key_lhs = col_lhs.clone();
- let key_rhs = col_rhs.clone();
-
- let rhs = build_query(stdb, tx, q.rhs.into())?;
- let lhs = result;
- let key_lhs_header = lhs.head().clone();
- let key_rhs_header = rhs.head().clone();
- let col_lhs_header = lhs.head().clone();
- let col_rhs_header = rhs.head().clone();
-
- let iter = lhs.join_inner(
- rhs,
- move |row| {
- let f = row.get(&key_lhs, &key_lhs_header);
- Ok(f.into())
- },
- move |row| {
- let f = row.get(&key_rhs, &key_rhs_header);
- Ok(f.into())
- },
- move |l, r| {
- let l = l.get(&col_lhs, &col_lhs_header);
- let r = r.get(&col_rhs, &col_rhs_header);
- Ok(l == r)
- },
- )?;
+ Query::JoinInner(join) => {
+ let iter = join_inner(stdb, tx, result, join, false)?;
Box::new(iter)
}
}
diff --git a/crates/core/src/vm.rs b/crates/core/src/vm.rs
--- a/crates/core/src/vm.rs
+++ b/crates/core/src/vm.rs
@@ -107,6 +83,56 @@ pub fn build_query<'a>(
Ok(result)
}
+fn join_inner<'a>(
+ db: &'a RelationalDB,
+ tx: &'a MutTxId,
+ lhs: impl RelOps + 'a,
+ rhs: JoinExpr,
+ semi: bool,
+) -> Result<impl RelOps + 'a, ErrorVm> {
+ let col_lhs = FieldExpr::Name(rhs.col_lhs);
+ let col_rhs = FieldExpr::Name(rhs.col_rhs);
+ let key_lhs = col_lhs.clone();
+ let key_rhs = col_rhs.clone();
+
+ let rhs = build_query(db, tx, rhs.rhs.into())?;
+ let key_lhs_header = lhs.head().clone();
+ let key_rhs_header = rhs.head().clone();
+ let col_lhs_header = lhs.head().clone();
+ let col_rhs_header = rhs.head().clone();
+
+ let header = if semi {
+ col_lhs_header.clone()
+ } else {
+ col_lhs_header.extend(&col_rhs_header)
+ };
+
+ lhs.join_inner(
+ rhs,
+ header,
+ move |row| {
+ let f = row.get(&key_lhs, &key_lhs_header);
+ Ok(f.into())
+ },
+ move |row| {
+ let f = row.get(&key_rhs, &key_rhs_header);
+ Ok(f.into())
+ },
+ move |l, r| {
+ let l = l.get(&col_lhs, &col_lhs_header);
+ let r = r.get(&col_rhs, &col_rhs_header);
+ Ok(l == r)
+ },
+ move |l, r| {
+ if semi {
+ l
+ } else {
+ l.extend(r)
+ }
+ },
+ )
+}
+
fn get_table<'a>(stdb: &'a RelationalDB, tx: &'a MutTxId, query: SourceExpr) -> Result<Box<dyn RelOps + 'a>, ErrorVm> {
let head = query.head();
let row_count = query.row_count();
diff --git a/crates/core/src/vm.rs b/crates/core/src/vm.rs
--- a/crates/core/src/vm.rs
+++ b/crates/core/src/vm.rs
@@ -153,6 +179,29 @@ pub struct IndexSemiJoin<'a, Rhs: RelOps> {
pub tx: &'a MutTxId,
}
+impl<'a, Rhs: RelOps> IndexSemiJoin<'a, Rhs> {
+ pub fn new(
+ db: &'a RelationalDB,
+ tx: &'a MutTxId,
+ probe_side: Rhs,
+ probe_field: FieldName,
+ index_header: Header,
+ index_table: u32,
+ index_col: u32,
+ ) -> Self {
+ IndexSemiJoin {
+ db,
+ tx,
+ probe_side,
+ probe_field,
+ index_header,
+ index_table,
+ index_col,
+ index_iter: None,
+ }
+ }
+}
+
impl<'a, Rhs: RelOps> RelOps for IndexSemiJoin<'a, Rhs> {
fn head(&self) -> &Header {
&self.index_header
diff --git a/crates/vm/src/eval.rs b/crates/vm/src/eval.rs
--- a/crates/vm/src/eval.rs
+++ b/crates/vm/src/eval.rs
@@ -457,6 +457,7 @@ pub fn build_query(mut result: Box<IterRows>, query: Vec<Query>) -> Result<Box<I
let iter = lhs.join_inner(
rhs,
+ col_lhs_header.extend(&col_rhs_header),
move |row| {
let f = row.get(&key_lhs, &key_lhs_header);
Ok(f.into())
diff --git a/crates/vm/src/eval.rs b/crates/vm/src/eval.rs
--- a/crates/vm/src/eval.rs
+++ b/crates/vm/src/eval.rs
@@ -470,6 +471,7 @@ pub fn build_query(mut result: Box<IterRows>, query: Vec<Query>) -> Result<Box<I
let r = r.get(&col_rhs, &col_rhs_header);
Ok(l == r)
},
+ move |l, r| l.extend(r),
)?;
Box::new(iter)
}
diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs
--- a/crates/vm/src/expr.rs
+++ b/crates/vm/src/expr.rs
@@ -366,6 +366,16 @@ pub struct JoinExpr {
pub col_rhs: FieldName,
}
+impl From<IndexJoin> for JoinExpr {
+ fn from(value: IndexJoin) -> Self {
+ let pos = value.index_col as usize;
+ let rhs = value.probe_side;
+ let col_lhs = value.index_header.fields[pos].field.clone();
+ let col_rhs = value.probe_field;
+ JoinExpr::new(rhs, col_lhs, col_rhs)
+ }
+}
+
impl JoinExpr {
pub fn new(rhs: QueryExpr, col_lhs: FieldName, col_rhs: FieldName) -> Self {
Self { rhs, col_lhs, col_rhs }
diff --git a/crates/vm/src/rel_ops.rs b/crates/vm/src/rel_ops.rs
--- a/crates/vm/src/rel_ops.rs
+++ b/crates/vm/src/rel_ops.rs
@@ -80,22 +80,24 @@ pub trait RelOps {
///
/// It is the equivalent of a `INNER JOIN` clause on SQL.
#[inline]
- fn join_inner<P, KeyLhs, KeyRhs, Rhs>(
+ fn join_inner<Pred, Proj, KeyLhs, KeyRhs, Rhs>(
self,
with: Rhs,
+ head: Header,
key_lhs: KeyLhs,
key_rhs: KeyRhs,
- predicate: P,
- ) -> Result<JoinInner<Self, Rhs, KeyLhs, KeyRhs, P>, ErrorVm>
+ predicate: Pred,
+ project: Proj,
+ ) -> Result<JoinInner<Self, Rhs, KeyLhs, KeyRhs, Pred, Proj>, ErrorVm>
where
Self: Sized,
- P: FnMut(RelValueRef, RelValueRef) -> Result<bool, ErrorVm>,
+ Pred: FnMut(RelValueRef, RelValueRef) -> Result<bool, ErrorVm>,
+ Proj: FnMut(RelValue, RelValue) -> RelValue,
KeyLhs: FnMut(RelValueRef) -> Result<ProductValue, ErrorVm>,
KeyRhs: FnMut(RelValueRef) -> Result<ProductValue, ErrorVm>,
Rhs: RelOps,
{
- let head = self.head().extend(with.head());
- Ok(JoinInner::new(head, self, with, key_lhs, key_rhs, predicate))
+ Ok(JoinInner::new(head, self, with, key_lhs, key_rhs, predicate, project))
}
/// Utility to collect the results into a [Vec]
diff --git a/crates/vm/src/rel_ops.rs b/crates/vm/src/rel_ops.rs
--- a/crates/vm/src/rel_ops.rs
+++ b/crates/vm/src/rel_ops.rs
@@ -218,21 +220,30 @@ where
}
#[derive(Clone, Debug)]
-pub struct JoinInner<Lhs, Rhs, KeyLhs, KeyRhs, P> {
+pub struct JoinInner<Lhs, Rhs, KeyLhs, KeyRhs, Pred, Proj> {
pub(crate) head: Header,
pub(crate) count: RowCount,
pub(crate) lhs: Lhs,
pub(crate) rhs: Rhs,
pub(crate) key_lhs: KeyLhs,
pub(crate) key_rhs: KeyRhs,
- pub(crate) predicate: P,
+ pub(crate) predicate: Pred,
+ pub(crate) projection: Proj,
map: HashMap<ProductValue, Vec<RelValue>>,
filled: bool,
left: Option<RelValue>,
}
-impl<Lhs, Rhs, KeyLhs, KeyRhs, P> JoinInner<Lhs, Rhs, KeyLhs, KeyRhs, P> {
- pub fn new(head: Header, lhs: Lhs, rhs: Rhs, key_lhs: KeyLhs, key_rhs: KeyRhs, predicate: P) -> Self {
+impl<Lhs, Rhs, KeyLhs, KeyRhs, Pred, Proj> JoinInner<Lhs, Rhs, KeyLhs, KeyRhs, Pred, Proj> {
+ pub fn new(
+ head: Header,
+ lhs: Lhs,
+ rhs: Rhs,
+ key_lhs: KeyLhs,
+ key_rhs: KeyRhs,
+ predicate: Pred,
+ projection: Proj,
+ ) -> Self {
Self {
head,
count: RowCount::unknown(),
diff --git a/crates/vm/src/rel_ops.rs b/crates/vm/src/rel_ops.rs
--- a/crates/vm/src/rel_ops.rs
+++ b/crates/vm/src/rel_ops.rs
@@ -242,19 +253,21 @@ impl<Lhs, Rhs, KeyLhs, KeyRhs, P> JoinInner<Lhs, Rhs, KeyLhs, KeyRhs, P> {
key_lhs,
key_rhs,
predicate,
+ projection,
filled: false,
left: None,
}
}
}
-impl<Lhs, Rhs, KeyLhs, KeyRhs, P> RelOps for JoinInner<Lhs, Rhs, KeyLhs, KeyRhs, P>
+impl<Lhs, Rhs, KeyLhs, KeyRhs, Pred, Proj> RelOps for JoinInner<Lhs, Rhs, KeyLhs, KeyRhs, Pred, Proj>
where
Lhs: RelOps,
Rhs: RelOps,
KeyLhs: FnMut(RelValueRef) -> Result<ProductValue, ErrorVm>,
KeyRhs: FnMut(RelValueRef) -> Result<ProductValue, ErrorVm>,
- P: FnMut(RelValueRef, RelValueRef) -> Result<bool, ErrorVm>,
+ Pred: FnMut(RelValueRef, RelValueRef) -> Result<bool, ErrorVm>,
+ Proj: FnMut(RelValue, RelValue) -> RelValue,
{
fn head(&self) -> &Header {
&self.head
diff --git a/crates/vm/src/rel_ops.rs b/crates/vm/src/rel_ops.rs
--- a/crates/vm/src/rel_ops.rs
+++ b/crates/vm/src/rel_ops.rs
@@ -293,7 +306,7 @@ where
if let Some(rhs) = rvv.pop() {
if (self.predicate)(lhs.as_val_ref(), rhs.as_val_ref())? {
self.count.add_exact(1);
- return Ok(Some(lhs.clone().extend(rhs)));
+ return Ok(Some((self.projection)(lhs, rhs)));
}
}
}
|
diff --git a/crates/core/src/subscription/query.rs b/crates/core/src/subscription/query.rs
--- a/crates/core/src/subscription/query.rs
+++ b/crates/core/src/subscription/query.rs
@@ -448,6 +448,88 @@ mod tests {
Ok(())
}
+ #[test]
+ fn test_eval_incr_for_index_join() -> ResultTest<()> {
+ let (db, _) = make_test_db()?;
+ let mut tx = db.begin_tx();
+
+ // Create table [lhs] with index on [b]
+ let schema = &[("a", AlgebraicType::U64), ("b", AlgebraicType::U64)];
+ let indexes = &[(1, "b")];
+ let lhs_id = create_table(&db, &mut tx, "lhs", schema, indexes)?;
+
+ // Create table [rhs] with no indexes
+ let schema = &[("b", AlgebraicType::U64), ("c", AlgebraicType::U64)];
+ let rhs_id = create_table(&db, &mut tx, "rhs", schema, &[])?;
+
+ // Should be answered using an index semijion
+ let sql = "select lhs.* from lhs join rhs on lhs.b = rhs.b where rhs.c = 3";
+ let mut exp = compile_sql(&db, &tx, sql)?;
+
+ let Some(CrudExpr::Query(query)) = exp.pop() else {
+ panic!("unexpected query {:#?}", exp[0]);
+ };
+
+ let query = QuerySet(vec![Query { queries: vec![query] }]);
+
+ for i in 0..10 {
+ // Insert into lhs
+ let row = product!(i as u64, i as u64);
+ db.insert(&mut tx, lhs_id, row)?;
+
+ // Insert into rhs
+ let row = product!(i as u64, i as u64);
+ db.insert(&mut tx, rhs_id, row)?;
+ }
+
+ let mut updates = Vec::new();
+
+ // An update event for the left table that matches the query
+ let lhs_row = product!(11u64, 3u64);
+ let lhs_key = lhs_row.to_data_key().to_bytes();
+ let lhs_op = TableOp {
+ op_type: 0,
+ row: lhs_row,
+ row_pk: lhs_key,
+ };
+ updates.push(DatabaseTableUpdate {
+ table_id: lhs_id,
+ table_name: "lhs".into(),
+ ops: vec![lhs_op],
+ });
+
+ // An update event for the right table that matches the query
+ let rhs_row = product!(12u64, 3u64);
+ let rhs_key = rhs_row.to_data_key().to_bytes();
+ let rhs_op = TableOp {
+ op_type: 0,
+ row: rhs_row,
+ row_pk: rhs_key,
+ };
+ updates.push(DatabaseTableUpdate {
+ table_id: rhs_id,
+ table_name: "rhs".into(),
+ ops: vec![rhs_op],
+ });
+
+ let update = DatabaseUpdate { tables: updates };
+ let result = query.eval_incr(&db, &mut tx, &update, AuthCtx::for_testing())?;
+
+ assert_eq!(result.tables.len(), 1);
+
+ let update = &result.tables[0];
+
+ assert_eq!(update.ops.len(), 1);
+ assert_eq!(update.table_id, lhs_id);
+
+ let op = &update.ops[0];
+
+ assert_eq!(op.op_type, 0);
+ assert_eq!(op.row, product!(11u64, 3u64));
+ assert_eq!(op.row_pk, product!(11u64, 3u64).to_data_key().to_bytes());
+ Ok(())
+ }
+
#[test]
fn test_subscribe() -> ResultTest<()> {
let (db, _tmp_dir) = make_test_db()?;
|
Support incremental evaluation of index joins
|
2023-09-28T04:03:56Z
|
1.0
|
2023-09-28T16:47:40Z
|
e395e4ee30c7b4f142bf927d1151662ecedc763b
|
[
"subscription::query::tests::test_eval_incr_for_index_join"
] |
[
"client::message_handlers::tests::parse_one_off_query",
"db::datastore::locking_tx_datastore::tests::test_insert_post_commit",
"db::datastore::locking_tx_datastore::tests::test_create_table_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_create_table_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_create_table_post_commit",
"db::datastore::locking_tx_datastore::tests::test_create_index_post_commit",
"db::datastore::locking_tx_datastore::tests::test_create_index_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_insert_delete_insert_delete_insert",
"db::datastore::locking_tx_datastore::tests::test_insert_commit_delete_insert",
"db::datastore::locking_tx_datastore::tests::test_create_index_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_bootstrapping_sets_up_tables",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_wrong_schema_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_alter_indexes",
"db::datastore::locking_tx_datastore::tests::test_insert_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_rollback",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_post_commit",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_post_commit",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_update_reinsert",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_pre_commit",
"db::message_log::tests::test_message_log",
"db::ostorage::hashmap_object_db::tests::test_add_and_get",
"db::ostorage::hashmap_object_db::tests::test_miss",
"db::ostorage::hashmap_object_db::tests::test_size",
"db::ostorage::hashmap_object_db::tests::test_flush",
"db::ostorage::hashmap_object_db::tests::test_flush_sync_all",
"db::relational_db::tests::test",
"db::relational_db::tests::test_auto_inc",
"db::relational_db::tests::test_auto_inc_disable",
"db::relational_db::tests::test_cascade_drop_table",
"db::relational_db::tests::test_create_table_pre_commit",
"db::relational_db::tests::test_create_table_rollback",
"db::relational_db::tests::test_column_name",
"db::relational_db::tests::test_filter_range_post_commit",
"db::relational_db::tests::test_filter_range_pre_commit",
"db::relational_db::tests::test_identity",
"db::relational_db::tests::test_indexed",
"db::message_log::tests::test_message_log_reopen",
"db::relational_db::tests::test_open_twice",
"db::relational_db::tests::test_pre_commit",
"db::relational_db::tests::test_rename_table",
"db::relational_db::tests::test_post_commit",
"db::relational_db::tests::test_rollback",
"db::relational_db::tests::test_table_name",
"db::relational_db::tests::test_unique",
"sql::compiler::tests::compile_eq",
"sql::compiler::tests::compile_eq_and_eq",
"sql::compiler::tests::compile_eq_or_eq",
"sql::compiler::tests::compile_index_eq",
"sql::compiler::tests::compile_index_eq_and_eq",
"sql::compiler::tests::compile_index_range_closed",
"sql::compiler::tests::compile_index_range_open",
"sql::compiler::tests::compile_index_eq_select_range",
"sql::compiler::tests::compile_index_join",
"sql::compiler::tests::compile_join_lhs_and_rhs_push_down",
"sql::compiler::tests::compile_join_lhs_push_down",
"sql::compiler::tests::compile_join_lhs_push_down_no_index",
"sql::compiler::tests::compile_join_rhs_push_down_no_index",
"sql::execute::tests::test_big_sql",
"sql::execute::tests::test_column_constraints",
"sql::execute::tests::test_create_table",
"sql::execute::tests::test_delete",
"sql::execute::tests::test_drop_table",
"sql::execute::tests::test_inner_join",
"sql::execute::tests::test_insert",
"db::relational_db::tests::test_auto_inc_reload",
"sql::execute::tests::test_or",
"sql::execute::tests::test_select_catalog",
"sql::execute::tests::test_nested",
"sql::execute::tests::test_select_column",
"sql::execute::tests::test_select_multiple",
"sql::execute::tests::test_select_scalar",
"sql::execute::tests::test_select_star_table",
"sql::execute::tests::test_update",
"sql::execute::tests::test_select_star",
"sql::execute::tests::test_where",
"subscription::query::tests::test_eval_incr_for_index_scan",
"subscription::query::tests::test_eval_incr_maintains_row_ids",
"subscription::query::tests::test_subscribe",
"subscription::query::tests::test_subscribe_commutative",
"subscription::query::tests::test_subscribe_dedup",
"subscription::query::tests::test_subscribe_all",
"subscription::query::tests::test_subscribe_private",
"subscription::query::tests::test_subscribe_sql",
"vm::tests::test_query_catalog_columns",
"vm::tests::test_db_query",
"vm::tests::test_query_catalog_sequences",
"vm::tests::test_query_catalog_tables",
"vm::tests::test_query_catalog_indexes",
"control_db::tests::test_domain",
"control_db::tests::test_register_tld",
"db::ostorage::sled_object_db::tests::test_add_and_get",
"db::ostorage::sled_object_db::tests::test_miss",
"db::ostorage::sled_object_db::tests::test_flush",
"db::ostorage::sled_object_db::tests::test_flush_sync_all"
] |
[] |
[] |
|
clockworklabs/SpacetimeDB
| 321
|
clockworklabs__SpacetimeDB-321
|
[
"320"
] |
9aecc256de48dd210f6be201f6688c1fba5e0b62
|
diff --git a/crates/core/src/vm.rs b/crates/core/src/vm.rs
--- a/crates/core/src/vm.rs
+++ b/crates/core/src/vm.rs
@@ -29,36 +29,22 @@ pub fn build_query<'a>(
tx: &'a MutTxId,
query: QueryCode,
) -> Result<Box<IterRows<'a>>, ErrorVm> {
- let q = match &query.table {
- Table::MemTable(x) => SourceExpr::MemTable(x.clone()),
- Table::DbTable(x) => SourceExpr::DbTable(x.clone()),
- };
-
- let mut ops = query.query.into_iter();
- let first = ops.next();
-
- // If the first operation is an index scan, open an index cursor, else a table cursor.
- let (mut result, ops) = if let Some(Query::IndexScan(IndexScan {
- table,
- col_id,
- lower_bound,
- upper_bound,
- })) = first
- {
- (
- iter_by_col_range(stdb, tx, table, col_id, (lower_bound, upper_bound))?,
- ops.collect(),
- )
- } else if let Some(op) = first {
- (get_table(stdb, tx, q)?, std::iter::once(op).chain(ops).collect())
- } else {
- (get_table(stdb, tx, q)?, vec![])
- };
+ let db_table = matches!(&query.table, Table::DbTable(_));
+ let mut result = get_table(stdb, tx, query.table.into())?;
- for op in ops {
+ for op in query.query {
result = match op {
- Query::IndexScan(_) => {
- unreachable!()
+ Query::IndexScan(IndexScan {
+ table,
+ col_id,
+ lower_bound,
+ upper_bound,
+ }) if db_table => iter_by_col_range(stdb, tx, table, col_id, (lower_bound, upper_bound))?,
+ Query::IndexScan(index_scan) => {
+ let header = result.head().clone();
+ let cmp: ColumnOp = index_scan.into();
+ let iter = result.select(move |row| cmp.compare(row, &header));
+ Box::new(iter)
}
Query::Select(cmp) => {
let header = result.head().clone();
diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs
--- a/crates/vm/src/expr.rs
+++ b/crates/vm/src/expr.rs
@@ -246,12 +246,6 @@ impl From<IndexScan> for ColumnOp {
lhs: field.into(),
rhs: value.into(),
},
- // Inclusive lower bound => field >= value
- (Bound::Included(lower), Bound::Included(upper)) if lower == upper => ColumnOp::Cmp {
- op: OpQuery::Cmp(OpCmp::Eq),
- lhs: field.into(),
- rhs: lower.into(),
- },
(Bound::Unbounded, Bound::Unbounded) => unreachable!(),
(lower_bound, upper_bound) => {
let lhs = IndexScan {
diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs
--- a/crates/vm/src/expr.rs
+++ b/crates/vm/src/expr.rs
@@ -282,6 +276,15 @@ pub enum SourceExpr {
DbTable(DbTable),
}
+impl From<Table> for SourceExpr {
+ fn from(value: Table) -> Self {
+ match value {
+ Table::MemTable(t) => SourceExpr::MemTable(t),
+ Table::DbTable(t) => SourceExpr::DbTable(t),
+ }
+ }
+}
+
impl From<SourceExpr> for Table {
fn from(value: SourceExpr) -> Self {
match value {
|
diff --git a/crates/core/src/subscription/query.rs b/crates/core/src/subscription/query.rs
--- a/crates/core/src/subscription/query.rs
+++ b/crates/core/src/subscription/query.rs
@@ -146,13 +146,14 @@ pub fn compile_read_only_query(
#[cfg(test)]
mod tests {
use super::*;
- use crate::db::datastore::traits::TableSchema;
+ use crate::db::datastore::traits::{ColumnDef, IndexDef, TableDef, TableSchema};
use crate::db::relational_db::tests_utils::make_test_db;
use crate::host::module_host::{DatabaseTableUpdate, DatabaseUpdate, TableOp};
use crate::sql::execute::run;
use crate::subscription::subscription::QuerySet;
use crate::vm::tests::create_table_with_rows;
use itertools::Itertools;
+ use nonempty::NonEmpty;
use spacetimedb_lib::auth::{StAccess, StTableType};
use spacetimedb_lib::data_key::ToDataKey;
use spacetimedb_lib::error::ResultTest;
diff --git a/crates/core/src/subscription/query.rs b/crates/core/src/subscription/query.rs
--- a/crates/core/src/subscription/query.rs
+++ b/crates/core/src/subscription/query.rs
@@ -162,6 +163,47 @@ mod tests {
use spacetimedb_vm::dsl::{db_table, mem_table, scalar};
use spacetimedb_vm::operator::OpCmp;
+ fn create_table(
+ db: &RelationalDB,
+ tx: &mut MutTxId,
+ name: &str,
+ schema: &[(&str, AlgebraicType)],
+ indexes: &[(u32, &str)],
+ ) -> ResultTest<u32> {
+ let table_name = name.to_string();
+ let table_type = StTableType::User;
+ let table_access = StAccess::Public;
+
+ let columns = schema
+ .iter()
+ .map(|(col_name, col_type)| ColumnDef {
+ col_name: col_name.to_string(),
+ col_type: col_type.clone(),
+ is_autoinc: false,
+ })
+ .collect_vec();
+
+ let indexes = indexes
+ .iter()
+ .map(|(col_id, index_name)| IndexDef {
+ table_id: 0,
+ cols: NonEmpty::new(*col_id),
+ name: index_name.to_string(),
+ is_unique: false,
+ })
+ .collect_vec();
+
+ let schema = TableDef {
+ table_name,
+ columns,
+ indexes,
+ table_type,
+ table_access,
+ };
+
+ Ok(db.create_table(tx, schema)?)
+ }
+
fn make_data(
db: &RelationalDB,
tx: &mut MutTxId,
diff --git a/crates/core/src/subscription/query.rs b/crates/core/src/subscription/query.rs
--- a/crates/core/src/subscription/query.rs
+++ b/crates/core/src/subscription/query.rs
@@ -349,6 +391,63 @@ mod tests {
Ok(())
}
+ #[test]
+ fn test_eval_incr_for_index_scan() -> ResultTest<()> {
+ let (db, _) = make_test_db()?;
+ let mut tx = db.begin_tx();
+
+ // Create table [test] with index on [b]
+ let schema = &[("a", AlgebraicType::U64), ("b", AlgebraicType::U64)];
+ let indexes = &[(1, "b")];
+ let table_id = create_table(&db, &mut tx, "test", schema, indexes)?;
+
+ let sql = "select * from test where b = 3";
+ let mut exp = compile_sql(&db, &tx, sql)?;
+
+ let Some(CrudExpr::Query(query)) = exp.pop() else {
+ panic!("unexpected query {:#?}", exp[0]);
+ };
+
+ let query = QuerySet(vec![Query { queries: vec![query] }]);
+
+ let mut ops = Vec::new();
+ for i in 0u64..9u64 {
+ let row = product!(i, i);
+ db.insert(&mut tx, table_id, row)?;
+
+ let row = product!(i + 10, i);
+ let row_pk = row.to_data_key().to_bytes();
+ ops.push(TableOp {
+ op_type: 0,
+ row_pk,
+ row,
+ })
+ }
+
+ let update = DatabaseUpdate {
+ tables: vec![DatabaseTableUpdate {
+ table_id,
+ table_name: "test".into(),
+ ops,
+ }],
+ };
+
+ let result = query.eval_incr(&db, &mut tx, &update, AuthCtx::for_testing())?;
+
+ assert_eq!(result.tables.len(), 1);
+
+ let update = &result.tables[0];
+
+ assert_eq!(update.ops.len(), 1);
+
+ let op = &update.ops[0];
+
+ assert_eq!(op.op_type, 0);
+ assert_eq!(op.row, product!(13u64, 3u64));
+ assert_eq!(op.row_pk, product!(13u64, 3u64).to_data_key().to_bytes());
+ Ok(())
+ }
+
#[test]
fn test_subscribe() -> ResultTest<()> {
let (db, _tmp_dir) = make_test_db()?;
|
Fix incremental evaluation of queries that use indexes
`eval_incr` panics for index scan plans with the following error
```
failed to locate `__op_type`
```
|
2023-09-26T16:30:34Z
|
1.0
|
2023-09-26T17:19:29Z
|
e395e4ee30c7b4f142bf927d1151662ecedc763b
|
[
"subscription::query::tests::test_eval_incr_for_index_scan"
] |
[
"client::message_handlers::tests::parse_one_off_query",
"db::datastore::locking_tx_datastore::tests::test_bootstrapping_sets_up_tables",
"db::datastore::locking_tx_datastore::tests::test_create_table_post_commit",
"db::datastore::locking_tx_datastore::tests::test_create_table_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_create_table_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_create_index_post_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_delete_insert_delete_insert",
"db::datastore::locking_tx_datastore::tests::test_insert_commit_delete_insert",
"db::datastore::locking_tx_datastore::tests::test_insert_post_commit",
"db::datastore::locking_tx_datastore::tests::test_create_index_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_create_index_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_wrong_schema_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_post_commit",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_alter_indexes",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_rollback",
"db::datastore::locking_tx_datastore::tests::test_insert_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_post_commit",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_update_reinsert",
"db::message_log::tests::test_message_log",
"db::ostorage::hashmap_object_db::tests::test_flush",
"db::ostorage::hashmap_object_db::tests::test_add_and_get",
"db::ostorage::hashmap_object_db::tests::test_flush_sync_all",
"db::ostorage::hashmap_object_db::tests::test_miss",
"db::ostorage::hashmap_object_db::tests::test_size",
"db::relational_db::tests::test",
"db::relational_db::tests::test_auto_inc",
"db::relational_db::tests::test_auto_inc_disable",
"db::relational_db::tests::test_cascade_drop_table",
"db::relational_db::tests::test_auto_inc_reload",
"db::relational_db::tests::test_column_name",
"db::relational_db::tests::test_create_table_pre_commit",
"db::relational_db::tests::test_create_table_rollback",
"db::relational_db::tests::test_filter_range_post_commit",
"db::relational_db::tests::test_filter_range_pre_commit",
"db::relational_db::tests::test_identity",
"db::relational_db::tests::test_indexed",
"db::relational_db::tests::test_post_commit",
"db::relational_db::tests::test_open_twice",
"db::relational_db::tests::test_pre_commit",
"db::relational_db::tests::test_rename_table",
"db::relational_db::tests::test_rollback",
"db::relational_db::tests::test_table_name",
"db::relational_db::tests::test_unique",
"sql::compiler::tests::compile_eq",
"sql::compiler::tests::compile_eq_and_eq",
"sql::compiler::tests::compile_eq_or_eq",
"sql::compiler::tests::compile_index_eq",
"sql::compiler::tests::compile_index_eq_and_eq",
"sql::compiler::tests::compile_index_eq_select_range",
"sql::compiler::tests::compile_index_range_closed",
"sql::compiler::tests::compile_index_range_open",
"sql::compiler::tests::compile_join_lhs_push_down",
"sql::compiler::tests::compile_join_lhs_and_rhs_push_down",
"sql::execute::tests::test_big_sql",
"sql::execute::tests::test_column_constraints",
"sql::execute::tests::test_create_table",
"sql::execute::tests::test_delete",
"sql::execute::tests::test_drop_table",
"sql::execute::tests::test_inner_join",
"sql::execute::tests::test_insert",
"sql::execute::tests::test_nested",
"sql::execute::tests::test_or",
"sql::execute::tests::test_select_multiple",
"sql::execute::tests::test_select_catalog",
"sql::execute::tests::test_select_column",
"sql::execute::tests::test_select_scalar",
"sql::execute::tests::test_select_star",
"sql::execute::tests::test_select_star_table",
"sql::execute::tests::test_update",
"subscription::query::tests::test_eval_incr_maintains_row_ids",
"sql::execute::tests::test_where",
"subscription::query::tests::test_subscribe",
"subscription::query::tests::test_subscribe_all",
"subscription::query::tests::test_subscribe_commutative",
"subscription::query::tests::test_subscribe_private",
"subscription::query::tests::test_subscribe_dedup",
"db::message_log::tests::test_message_log_reopen",
"vm::tests::test_db_query",
"subscription::query::tests::test_subscribe_sql",
"vm::tests::test_query_catalog_sequences",
"vm::tests::test_query_catalog_tables",
"vm::tests::test_query_catalog_columns",
"vm::tests::test_query_catalog_indexes",
"control_db::tests::test_register_tld",
"control_db::tests::test_domain",
"db::ostorage::sled_object_db::tests::test_miss",
"db::ostorage::sled_object_db::tests::test_flush_sync_all",
"db::ostorage::sled_object_db::tests::test_flush",
"db::ostorage::sled_object_db::tests::test_add_and_get"
] |
[] |
[] |
|
clockworklabs/SpacetimeDB
| 319
|
clockworklabs__SpacetimeDB-319
|
[
"318"
] |
8a80600c836736a9310cf3b235efd521e3b1d5e1
|
diff --git a/crates/core/src/sql/ast.rs b/crates/core/src/sql/ast.rs
--- a/crates/core/src/sql/ast.rs
+++ b/crates/core/src/sql/ast.rs
@@ -106,7 +106,7 @@ pub struct Selection {
impl Selection {
pub fn with_cmp(op: OpQuery, lhs: ColumnOp, rhs: ColumnOp) -> Self {
- let cmp = ColumnOp::cmp(op, lhs, rhs);
+ let cmp = ColumnOp::new(op, lhs, rhs);
Selection { clause: cmp }
}
}
diff --git a/crates/core/src/sql/ast.rs b/crates/core/src/sql/ast.rs
--- a/crates/core/src/sql/ast.rs
+++ b/crates/core/src/sql/ast.rs
@@ -310,7 +310,7 @@ fn compile_expr_value(table: &From, field: Option<&ProductTypeElement>, of: SqlE
SqlExpr::BinaryOp { left, op, right } => {
let (op, lhs, rhs) = compile_bin_op(table, op, left, right)?;
- return Ok(ColumnOp::cmp(op, lhs, rhs));
+ return Ok(ColumnOp::new(op, lhs, rhs));
}
SqlExpr::Nested(x) => {
return compile_expr_value(table, field, *x);
diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs
--- a/crates/vm/src/expr.rs
+++ b/crates/vm/src/expr.rs
@@ -82,7 +82,7 @@ pub enum ColumnOp {
}
impl ColumnOp {
- pub fn cmp(op: OpQuery, lhs: ColumnOp, rhs: ColumnOp) -> Self {
+ pub fn new(op: OpQuery, lhs: ColumnOp, rhs: ColumnOp) -> Self {
Self::Cmp {
op,
lhs: Box::new(lhs),
diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs
--- a/crates/vm/src/expr.rs
+++ b/crates/vm/src/expr.rs
@@ -90,6 +90,14 @@ impl ColumnOp {
}
}
+ pub fn cmp(field: FieldName, op: OpCmp, value: AlgebraicValue) -> Self {
+ Self::Cmp {
+ op: OpQuery::Cmp(op),
+ lhs: Box::new(ColumnOp::Field(FieldExpr::Name(field))),
+ rhs: Box::new(ColumnOp::Field(FieldExpr::Value(value))),
+ }
+ }
+
fn reduce(&self, row: RelValueRef, value: &ColumnOp, header: &Header) -> Result<AlgebraicValue, ErrorLang> {
match value {
ColumnOp::Field(field) => Ok(row.get(field, header).clone()),
diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs
--- a/crates/vm/src/expr.rs
+++ b/crates/vm/src/expr.rs
@@ -816,18 +824,49 @@ impl QueryExpr {
self.query.push(Query::Select(op.into()));
return self;
};
- match query {
- Query::Select(filter) => {
- self.query.push(Query::Select(ColumnOp::Cmp {
- op: OpQuery::Logic(OpLogic::And),
- lhs: filter.into(),
- rhs: Box::new(op.into()),
- }));
+
+ match (query, op.into()) {
+ (
+ Query::JoinInner(JoinExpr { rhs, col_lhs, col_rhs }),
+ ColumnOp::Cmp {
+ op: OpQuery::Cmp(cmp),
+ lhs: field,
+ rhs: value,
+ },
+ ) => match (*field, *value) {
+ (ColumnOp::Field(FieldExpr::Name(field)), ColumnOp::Field(FieldExpr::Value(value)))
+ // Field is from lhs, so push onto join's left arg
+ if self.source.head().column(&field).is_some() =>
+ {
+ self = self.with_select(ColumnOp::cmp(field, cmp, value));
+ self.query.push(Query::JoinInner(JoinExpr { rhs, col_lhs, col_rhs }));
+ self
+ }
+ (ColumnOp::Field(FieldExpr::Name(field)), ColumnOp::Field(FieldExpr::Value(value)))
+ // Field is from rhs, so push onto join's right arg
+ if rhs.source.head().column(&field).is_some() =>
+ {
+ self.query.push(Query::JoinInner(JoinExpr {
+ rhs: rhs.with_select(ColumnOp::cmp(field, cmp, value)),
+ col_lhs,
+ col_rhs,
+ }));
+ self
+ }
+ (field, value) => {
+ self.query.push(Query::JoinInner(JoinExpr { rhs, col_lhs, col_rhs }));
+ self.query.push(Query::Select(ColumnOp::new(OpQuery::Cmp(cmp), field, value)));
+ self
+ }
+ },
+ (Query::Select(filter), op) => {
+ self.query
+ .push(Query::Select(ColumnOp::new(OpQuery::Logic(OpLogic::And), filter, op)));
self
}
- query => {
+ (query, op) => {
self.query.push(query);
- self.query.push(Query::Select(op.into()));
+ self.query.push(Query::Select(op));
self
}
}
diff --git a/crates/vm/src/expr.rs b/crates/vm/src/expr.rs
--- a/crates/vm/src/expr.rs
+++ b/crates/vm/src/expr.rs
@@ -839,7 +878,7 @@ impl QueryExpr {
RHS: Into<FieldExpr>,
O: Into<OpQuery>,
{
- let op = ColumnOp::cmp(op.into(), ColumnOp::Field(lhs.into()), ColumnOp::Field(rhs.into()));
+ let op = ColumnOp::new(op.into(), ColumnOp::Field(lhs.into()), ColumnOp::Field(rhs.into()));
self.with_select(op)
}
|
diff --git a/crates/core/src/sql/compiler.rs b/crates/core/src/sql/compiler.rs
--- a/crates/core/src/sql/compiler.rs
+++ b/crates/core/src/sql/compiler.rs
@@ -808,6 +808,167 @@ mod tests {
Ok(())
}
+ #[test]
+ fn compile_join_lhs_push_down_no_index() -> ResultTest<()> {
+ let (db, _) = make_test_db()?;
+ let mut tx = db.begin_tx();
+
+ // Create table [lhs] with no indexes
+ let schema = &[("a", AlgebraicType::U64), ("b", AlgebraicType::U64)];
+ let lhs_id = create_table(&db, &mut tx, "lhs", schema, &[])?;
+
+ // Create table [rhs] with no indexes
+ let schema = &[("b", AlgebraicType::U64), ("c", AlgebraicType::U64)];
+ let rhs_id = create_table(&db, &mut tx, "rhs", schema, &[])?;
+
+ // Should push equality condition below join
+ let sql = "select * from lhs join rhs on lhs.b = rhs.b where lhs.a = 3";
+ let exp = compile_sql(&db, &tx, sql)?.remove(0);
+
+ let CrudExpr::Query(QueryExpr {
+ source: SourceExpr::DbTable(DbTable { table_id, .. }),
+ query,
+ ..
+ }) = exp
+ else {
+ panic!("unexpected expression: {:#?}", exp);
+ };
+
+ assert_eq!(table_id, lhs_id);
+ assert_eq!(query.len(), 2);
+
+ // The first operation in the pipeline should be a selection
+ let Query::Select(ColumnOp::Cmp {
+ op: OpQuery::Cmp(OpCmp::Eq),
+ ref lhs,
+ ref rhs,
+ }) = query[0]
+ else {
+ panic!("unexpected operator {:#?}", query[0]);
+ };
+
+ let ColumnOp::Field(FieldExpr::Name(FieldName::Name { ref table, ref field })) = **lhs else {
+ panic!("unexpected left hand side {:#?}", **lhs);
+ };
+
+ assert_eq!(table, "lhs");
+ assert_eq!(field, "a");
+
+ let ColumnOp::Field(FieldExpr::Value(AlgebraicValue::Builtin(BuiltinValue::U64(3)))) = **rhs else {
+ panic!("unexpected right hand side {:#?}", **rhs);
+ };
+
+ // The join should follow the selection
+ let Query::JoinInner(JoinExpr {
+ rhs:
+ QueryExpr {
+ source: SourceExpr::DbTable(DbTable { table_id, .. }),
+ query: ref rhs,
+ },
+ col_lhs:
+ FieldName::Name {
+ table: ref lhs_table,
+ field: ref lhs_field,
+ },
+ col_rhs:
+ FieldName::Name {
+ table: ref rhs_table,
+ field: ref rhs_field,
+ },
+ }) = query[1]
+ else {
+ panic!("unexpected operator {:#?}", query[1]);
+ };
+
+ assert_eq!(table_id, rhs_id);
+ assert_eq!(lhs_field, "b");
+ assert_eq!(rhs_field, "b");
+ assert_eq!(lhs_table, "lhs");
+ assert_eq!(rhs_table, "rhs");
+ assert!(rhs.is_empty());
+ Ok(())
+ }
+
+ #[test]
+ fn compile_join_rhs_push_down_no_index() -> ResultTest<()> {
+ let (db, _) = make_test_db()?;
+ let mut tx = db.begin_tx();
+
+ // Create table [lhs] with no indexes
+ let schema = &[("a", AlgebraicType::U64), ("b", AlgebraicType::U64)];
+ let lhs_id = create_table(&db, &mut tx, "lhs", schema, &[])?;
+
+ // Create table [rhs] with no indexes
+ let schema = &[("b", AlgebraicType::U64), ("c", AlgebraicType::U64)];
+ let rhs_id = create_table(&db, &mut tx, "rhs", schema, &[])?;
+
+ // Should push equality condition below join
+ let sql = "select * from lhs join rhs on lhs.b = rhs.b where rhs.c = 3";
+ let exp = compile_sql(&db, &tx, sql)?.remove(0);
+
+ let CrudExpr::Query(QueryExpr {
+ source: SourceExpr::DbTable(DbTable { table_id, .. }),
+ query,
+ ..
+ }) = exp
+ else {
+ panic!("unexpected expression: {:#?}", exp);
+ };
+
+ assert_eq!(table_id, lhs_id);
+ assert_eq!(query.len(), 1);
+
+ // First and only operation in the pipeline should be a join
+ let Query::JoinInner(JoinExpr {
+ rhs:
+ QueryExpr {
+ source: SourceExpr::DbTable(DbTable { table_id, .. }),
+ query: ref rhs,
+ },
+ col_lhs:
+ FieldName::Name {
+ table: ref lhs_table,
+ field: ref lhs_field,
+ },
+ col_rhs:
+ FieldName::Name {
+ table: ref rhs_table,
+ field: ref rhs_field,
+ },
+ }) = query[0]
+ else {
+ panic!("unexpected operator {:#?}", query[0]);
+ };
+
+ assert_eq!(table_id, rhs_id);
+ assert_eq!(lhs_field, "b");
+ assert_eq!(rhs_field, "b");
+ assert_eq!(lhs_table, "lhs");
+ assert_eq!(rhs_table, "rhs");
+
+ // The selection should be pushed onto the rhs of the join
+ let Query::Select(ColumnOp::Cmp {
+ op: OpQuery::Cmp(OpCmp::Eq),
+ ref lhs,
+ ref rhs,
+ }) = rhs[0]
+ else {
+ panic!("unexpected operator {:#?}", rhs[0]);
+ };
+
+ let ColumnOp::Field(FieldExpr::Name(FieldName::Name { ref table, ref field })) = **lhs else {
+ panic!("unexpected left hand side {:#?}", **lhs);
+ };
+
+ assert_eq!(table, "rhs");
+ assert_eq!(field, "c");
+
+ let ColumnOp::Field(FieldExpr::Value(AlgebraicValue::Builtin(BuiltinValue::U64(3)))) = **rhs else {
+ panic!("unexpected right hand side {:#?}", **rhs);
+ };
+ Ok(())
+ }
+
#[test]
fn compile_join_lhs_and_rhs_push_down() -> ResultTest<()> {
let (db, _) = make_test_db()?;
|
Push selections below joins
Push selections below joins in general.
|
2023-09-26T08:29:57Z
|
1.0
|
2023-09-26T19:01:30Z
|
e395e4ee30c7b4f142bf927d1151662ecedc763b
|
[
"sql::compiler::tests::compile_join_lhs_push_down_no_index",
"sql::compiler::tests::compile_join_rhs_push_down_no_index"
] |
[
"client::message_handlers::tests::parse_one_off_query",
"db::datastore::locking_tx_datastore::tests::test_create_table_post_commit",
"db::datastore::locking_tx_datastore::tests::test_create_table_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_insert_post_commit",
"db::datastore::locking_tx_datastore::tests::test_create_index_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_insert_commit_delete_insert",
"db::datastore::locking_tx_datastore::tests::test_bootstrapping_sets_up_tables",
"db::datastore::locking_tx_datastore::tests::test_create_index_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_create_index_post_commit",
"db::datastore::locking_tx_datastore::tests::test_create_table_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_delete_insert_delete_insert",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_alter_indexes",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_rollback",
"db::datastore::locking_tx_datastore::tests::test_schema_for_table_post_commit",
"db::datastore::locking_tx_datastore::tests::test_insert_wrong_schema_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_post_commit",
"db::datastore::locking_tx_datastore::tests::test_unique_constraint_pre_commit",
"db::datastore::locking_tx_datastore::tests::test_update_reinsert",
"db::datastore::locking_tx_datastore::tests::test_insert_post_rollback",
"db::datastore::locking_tx_datastore::tests::test_insert_pre_commit",
"db::message_log::tests::test_message_log",
"db::ostorage::hashmap_object_db::tests::test_add_and_get",
"db::ostorage::hashmap_object_db::tests::test_flush_sync_all",
"db::ostorage::hashmap_object_db::tests::test_miss",
"db::ostorage::hashmap_object_db::tests::test_flush",
"db::ostorage::hashmap_object_db::tests::test_size",
"db::relational_db::tests::test",
"db::relational_db::tests::test_auto_inc",
"db::relational_db::tests::test_auto_inc_disable",
"db::relational_db::tests::test_auto_inc_reload",
"db::relational_db::tests::test_cascade_drop_table",
"db::relational_db::tests::test_column_name",
"db::relational_db::tests::test_filter_range_post_commit",
"db::relational_db::tests::test_create_table_pre_commit",
"db::relational_db::tests::test_create_table_rollback",
"db::relational_db::tests::test_filter_range_pre_commit",
"db::relational_db::tests::test_identity",
"db::relational_db::tests::test_indexed",
"db::relational_db::tests::test_open_twice",
"db::relational_db::tests::test_post_commit",
"db::relational_db::tests::test_pre_commit",
"db::relational_db::tests::test_rename_table",
"db::relational_db::tests::test_unique",
"db::relational_db::tests::test_rollback",
"sql::compiler::tests::compile_eq",
"db::relational_db::tests::test_table_name",
"sql::compiler::tests::compile_eq_and_eq",
"sql::compiler::tests::compile_eq_or_eq",
"sql::compiler::tests::compile_index_eq_and_eq",
"sql::compiler::tests::compile_index_eq",
"sql::compiler::tests::compile_index_eq_select_range",
"sql::compiler::tests::compile_index_range_closed",
"sql::compiler::tests::compile_index_range_open",
"sql::compiler::tests::compile_join_lhs_and_rhs_push_down",
"sql::compiler::tests::compile_join_lhs_push_down",
"sql::execute::tests::test_big_sql",
"sql::execute::tests::test_column_constraints",
"sql::execute::tests::test_delete",
"sql::execute::tests::test_create_table",
"sql::execute::tests::test_drop_table",
"sql::execute::tests::test_inner_join",
"sql::execute::tests::test_insert",
"sql::execute::tests::test_or",
"sql::execute::tests::test_nested",
"sql::execute::tests::test_select_catalog",
"sql::execute::tests::test_select_column",
"sql::execute::tests::test_select_multiple",
"sql::execute::tests::test_select_scalar",
"sql::execute::tests::test_select_star",
"db::ostorage::sled_object_db::tests::test_add_and_get",
"db::ostorage::sled_object_db::tests::test_flush",
"control_db::tests::test_register_tld",
"control_db::tests::test_domain",
"db::ostorage::sled_object_db::tests::test_flush_sync_all",
"sql::execute::tests::test_select_star_table",
"subscription::query::tests::test_eval_incr_maintains_row_ids",
"subscription::query::tests::test_eval_incr_for_index_scan",
"sql::execute::tests::test_where",
"subscription::query::tests::test_subscribe_private",
"subscription::query::tests::test_subscribe",
"subscription::query::tests::test_subscribe_commutative",
"subscription::query::tests::test_subscribe_dedup",
"sql::execute::tests::test_update",
"subscription::query::tests::test_subscribe_all",
"subscription::query::tests::test_subscribe_sql",
"vm::tests::test_db_query",
"vm::tests::test_query_catalog_columns",
"vm::tests::test_query_catalog_sequences",
"vm::tests::test_query_catalog_indexes",
"vm::tests::test_query_catalog_tables",
"db::message_log::tests::test_message_log_reopen",
"db::ostorage::sled_object_db::tests::test_miss"
] |
[] |
[] |
|
RustPython/RustPython
| 4,711
|
RustPython__RustPython-4711
|
[
"4588",
"4593",
"4588"
] |
38172469151f21bae1ec868c548f2ca537146dad
|
diff --git a/common/src/format.rs b/common/src/format.rs
--- a/common/src/format.rs
+++ b/common/src/format.rs
@@ -335,10 +335,11 @@ impl FormatSpec {
let offset = (disp_digit_cnt % (inter + 1) == 0) as i32;
let disp_digit_cnt = disp_digit_cnt + offset;
let pad_cnt = disp_digit_cnt - magnitude_len;
- if pad_cnt > 0 {
+ let sep_cnt = disp_digit_cnt / (inter + 1);
+ let diff = pad_cnt - sep_cnt;
+ if pad_cnt > 0 && diff > 0 {
// separate with 0 padding
- let sep_cnt = disp_digit_cnt / (inter + 1);
- let padding = "0".repeat((pad_cnt - sep_cnt) as usize);
+ let padding = "0".repeat(diff as usize);
let padded_num = format!("{padding}{magnitude_str}");
FormatSpec::insert_separator(padded_num, inter, sep, sep_cnt)
} else {
|
diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py
--- a/Lib/test/test_types.py
+++ b/Lib/test/test_types.py
@@ -403,7 +403,6 @@ def test_float__format__locale(self):
self.assertEqual(locale.format_string('%g', x, grouping=True), format(x, 'n'))
self.assertEqual(locale.format_string('%.10g', x, grouping=True), format(x, '.10n'))
- @unittest.skip("TODO: RustPython format code n is not integrated with locale")
@run_with_locale('LC_NUMERIC', 'en_US.UTF8')
def test_int__format__locale(self):
# test locale support for __format__ code 'n' for integers
diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py
--- a/Lib/test/test_types.py
+++ b/Lib/test/test_types.py
@@ -422,6 +421,9 @@ def test_int__format__locale(self):
self.assertEqual(len(format(0, rfmt)), len(format(x, rfmt)))
self.assertEqual(len(format(0, lfmt)), len(format(x, lfmt)))
self.assertEqual(len(format(0, cfmt)), len(format(x, cfmt)))
+
+ if sys.platform != "darwin":
+ test_int__format__locale = unittest.expectedFailure(test_int__format__locale)
def test_float__format__(self):
def test(f, format_spec, result):
diff --git a/common/src/format.rs b/common/src/format.rs
--- a/common/src/format.rs
+++ b/common/src/format.rs
@@ -1027,6 +1028,16 @@ mod tests {
);
}
+ #[test]
+ fn test_format_int_sep() {
+ let spec = FormatSpec::parse(",").expect("");
+ assert_eq!(spec.grouping_option, Some(FormatGrouping::Comma));
+ assert_eq!(
+ spec.format_int(&BigInt::from_str("1234567890123456789012345678").unwrap()),
+ Ok("1,234,567,890,123,456,789,012,345,678".to_owned())
+ );
+ }
+
#[test]
fn test_format_parse() {
let expected = Ok(FormatString {
diff --git a/extra_tests/snippets/builtin_format.py b/extra_tests/snippets/builtin_format.py
--- a/extra_tests/snippets/builtin_format.py
+++ b/extra_tests/snippets/builtin_format.py
@@ -133,3 +133,9 @@ def test_zero_padding():
assert f"{3.1415:#.2}" == "3.1"
assert f"{3.1415:#.3}" == "3.14"
assert f"{3.1415:#.4}" == "3.142"
+
+# test issue 4558
+x = 123456789012345678901234567890
+for i in range(0, 30):
+ format(x, ',')
+ x = x // 10
|
Format panic in test_int__format__locale
## Issues
In `Lib/test/test_types.py``test_int__format__locale`, if you change from `format(x, 'n')` to `format(x, ',')` and run the test, RustPython will panic! It doesn't crash in CPython!
See #4593 for test case
broken test case of FormatSpec::format_int
test case of #4588
Format panic in test_int__format__locale
## Issues
In `Lib/test/test_types.py``test_int__format__locale`, if you change from `format(x, 'n')` to `format(x, ',')` and run the test, RustPython will panic! It doesn't crash in CPython!
See #4593 for test case
|
not reproducible
not reproducible
|
2023-03-18T12:44:26Z
|
0.2
|
2023-03-23T07:38:32Z
|
7e66db0d43b6fd93bc114773ac8e896b7eda62c9
|
[
"format::tests::test_format_int_sep"
] |
[
"cformat::tests::test_format_parse_key_fail",
"cformat::tests::test_fill_and_align",
"float_ops::test_maybe_remove_trailing_redundant_chars",
"float_ops::test_remove_trailing_zeros",
"cformat::tests::test_parse_and_format_number",
"cformat::tests::test_parse_and_format_string",
"cformat::tests::test_format_parse_type_fail",
"format::tests::test_all",
"cformat::tests::test_parse_and_format_float",
"format::tests::test_fill_and_align",
"cformat::tests::test_format_parse",
"cformat::tests::test_parse_flags",
"cformat::tests::test_parse_and_format_unicode_string",
"format::tests::test_fill_and_width",
"format::tests::test_format_parse",
"format::tests::test_format_invalid_specification",
"format::tests::test_format_int",
"format::tests::test_format_parse_escape",
"cformat::tests::test_parse_key",
"format::tests::test_format_parse_multi_byte_char",
"int::test_bytes_to_int",
"format::tests::test_width_only",
"format::tests::test_parse_field_name",
"format::tests::test_format_parse_fail",
"cformat::tests::test_incomplete_format_fail",
"float_ops::test_to_hex",
"str::tests::test_get_chars",
"float_ops::test_remove_trailing_decimal_point",
"common/src/float_ops.rs - float_ops::eq_int (line 22)"
] |
[] |
[] |
RustPython/RustPython
| 4,582
|
RustPython__RustPython-4582
|
[
"4566"
] |
e082d8cc75060ce44b609f7d8eb6455d732fe90e
|
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2933,9 +2933,11 @@ checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
[[package]]
name = "unicode_names2"
-version = "0.5.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "029df4cc8238cefc911704ff8fa210853a0f3bce2694d8f51181dd41ee0f3301"
+version = "0.6.0"
+source = "git+https://github.com/youknowone/unicode_names2.git?tag=v0.6.0+character-alias#4ce16aa85cbcdd9cc830410f1a72ef9a235f2fde"
+dependencies = [
+ "phf",
+]
[[package]]
name = "utf8parse"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -55,6 +55,7 @@ static_assertions = "1.1"
syn = "1.0.91"
thiserror = "1.0"
thread_local = "1.1.4"
+unicode_names2 = { version = "0.6.0", git = "https://github.com/youknowone/unicode_names2.git", tag = "v0.6.0+character-alias" }
widestring = "0.5.1"
[features]
diff --git a/compiler/parser/Cargo.toml b/compiler/parser/Cargo.toml
--- a/compiler/parser/Cargo.toml
+++ b/compiler/parser/Cargo.toml
@@ -27,10 +27,10 @@ log = { workspace = true }
num-bigint = { workspace = true }
num-traits = { workspace = true }
thiserror = { workspace = true }
+unicode_names2 = { workspace = true }
unic-emoji-char = "0.9.0"
unic-ucd-ident = "0.9.0"
-unicode_names2 = "0.5.0"
lalrpop-util = "0.19.8"
phf = "0.11.1"
rustc-hash = "1.1.0"
diff --git a/stdlib/Cargo.toml b/stdlib/Cargo.toml
--- a/stdlib/Cargo.toml
+++ b/stdlib/Cargo.toml
@@ -57,7 +57,7 @@ sha3 = "0.10.1"
blake2 = "0.10.4"
## unicode stuff
-unicode_names2 = "0.5.0"
+unicode_names2 = { workspace = true }
# TODO: use unic for this; needed for title case:
# https://github.com/RustPython/RustPython/pull/832#discussion_r275428939
unicode-casing = "0.1.0"
diff --git a/vm/Cargo.toml b/vm/Cargo.toml
--- a/vm/Cargo.toml
+++ b/vm/Cargo.toml
@@ -81,7 +81,7 @@ sre-engine = "0.4.1"
# sre-engine = { path = "../../sre-engine" }
## unicode stuff
-unicode_names2 = "0.5.1"
+unicode_names2 = { workspace = true }
# TODO: use unic for this; needed for title case:
# https://github.com/RustPython/RustPython/pull/832#discussion_r275428939
unicode-casing = "0.1.0"
|
diff --git /dev/null b/compiler/parser/src/snapshots/rustpython_parser__string__tests__backspace_alias.snap
new file mode 100644
--- /dev/null
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__backspace_alias.snap
@@ -0,0 +1,40 @@
+---
+source: compiler/parser/src/string.rs
+expression: parse_ast
+---
+[
+ Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 15,
+ },
+ ),
+ custom: (),
+ node: Expr {
+ value: Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 15,
+ },
+ ),
+ custom: (),
+ node: Constant {
+ value: Str(
+ "\u{8}",
+ ),
+ kind: None,
+ },
+ },
+ },
+ },
+]
diff --git /dev/null b/compiler/parser/src/snapshots/rustpython_parser__string__tests__bell_alias.snap
new file mode 100644
--- /dev/null
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__bell_alias.snap
@@ -0,0 +1,40 @@
+---
+source: compiler/parser/src/string.rs
+expression: parse_ast
+---
+[
+ Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 9,
+ },
+ ),
+ custom: (),
+ node: Expr {
+ value: Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 9,
+ },
+ ),
+ custom: (),
+ node: Constant {
+ value: Str(
+ "\u{7}",
+ ),
+ kind: None,
+ },
+ },
+ },
+ },
+]
diff --git /dev/null b/compiler/parser/src/snapshots/rustpython_parser__string__tests__carriage_return_alias.snap
new file mode 100644
--- /dev/null
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__carriage_return_alias.snap
@@ -0,0 +1,40 @@
+---
+source: compiler/parser/src/string.rs
+expression: parse_ast
+---
+[
+ Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 21,
+ },
+ ),
+ custom: (),
+ node: Expr {
+ value: Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 21,
+ },
+ ),
+ custom: (),
+ node: Constant {
+ value: Str(
+ "\r",
+ ),
+ kind: None,
+ },
+ },
+ },
+ },
+]
diff --git /dev/null b/compiler/parser/src/snapshots/rustpython_parser__string__tests__character_tabulation_with_justification_alias.snap
new file mode 100644
--- /dev/null
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__character_tabulation_with_justification_alias.snap
@@ -0,0 +1,40 @@
+---
+source: compiler/parser/src/string.rs
+expression: parse_ast
+---
+[
+ Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 45,
+ },
+ ),
+ custom: (),
+ node: Expr {
+ value: Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 45,
+ },
+ ),
+ custom: (),
+ node: Constant {
+ value: Str(
+ "\u{89}",
+ ),
+ kind: None,
+ },
+ },
+ },
+ },
+]
diff --git /dev/null b/compiler/parser/src/snapshots/rustpython_parser__string__tests__delete_alias.snap
new file mode 100644
--- /dev/null
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__delete_alias.snap
@@ -0,0 +1,40 @@
+---
+source: compiler/parser/src/string.rs
+expression: parse_ast
+---
+[
+ Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 12,
+ },
+ ),
+ custom: (),
+ node: Expr {
+ value: Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 12,
+ },
+ ),
+ custom: (),
+ node: Constant {
+ value: Str(
+ "\u{7f}",
+ ),
+ kind: None,
+ },
+ },
+ },
+ },
+]
diff --git /dev/null b/compiler/parser/src/snapshots/rustpython_parser__string__tests__escape_alias.snap
new file mode 100644
--- /dev/null
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__escape_alias.snap
@@ -0,0 +1,40 @@
+---
+source: compiler/parser/src/string.rs
+expression: parse_ast
+---
+[
+ Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 12,
+ },
+ ),
+ custom: (),
+ node: Expr {
+ value: Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 12,
+ },
+ ),
+ custom: (),
+ node: Constant {
+ value: Str(
+ "\u{1b}",
+ ),
+ kind: None,
+ },
+ },
+ },
+ },
+]
diff --git /dev/null b/compiler/parser/src/snapshots/rustpython_parser__string__tests__form_feed_alias.snap
new file mode 100644
--- /dev/null
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__form_feed_alias.snap
@@ -0,0 +1,40 @@
+---
+source: compiler/parser/src/string.rs
+expression: parse_ast
+---
+[
+ Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 15,
+ },
+ ),
+ custom: (),
+ node: Expr {
+ value: Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 15,
+ },
+ ),
+ custom: (),
+ node: Constant {
+ value: Str(
+ "\u{c}",
+ ),
+ kind: None,
+ },
+ },
+ },
+ },
+]
diff --git /dev/null b/compiler/parser/src/snapshots/rustpython_parser__string__tests__hts_alias.snap
new file mode 100644
--- /dev/null
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__hts_alias.snap
@@ -0,0 +1,40 @@
+---
+source: compiler/parser/src/string.rs
+expression: parse_ast
+---
+[
+ Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 9,
+ },
+ ),
+ custom: (),
+ node: Expr {
+ value: Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 9,
+ },
+ ),
+ custom: (),
+ node: Constant {
+ value: Str(
+ "\u{88}",
+ ),
+ kind: None,
+ },
+ },
+ },
+ },
+]
diff --git a/compiler/parser/src/string.rs b/compiler/parser/src/string.rs
--- a/compiler/parser/src/string.rs
+++ b/compiler/parser/src/string.rs
@@ -1048,4 +1048,28 @@ mod tests {
let parse_ast = parse_program(source, "<test>").unwrap();
insta::assert_debug_snapshot!(parse_ast);
}
+
+ macro_rules! test_aliases_parse {
+ ($($name:ident: $alias:expr,)*) => {
+ $(
+ #[test]
+ fn $name() {
+ let source = format!(r#""\N{{{0}}}""#, $alias);
+ let parse_ast = parse_program(&source, "<test>").unwrap();
+ insta::assert_debug_snapshot!(parse_ast);
+ }
+ )*
+ }
+ }
+
+ test_aliases_parse! {
+ test_backspace_alias: "BACKSPACE",
+ test_bell_alias: "BEL",
+ test_carriage_return_alias: "CARRIAGE RETURN",
+ test_delete_alias: "DELETE",
+ test_escape_alias: "ESCAPE",
+ test_form_feed_alias: "FORM FEED",
+ test_hts_alias: "HTS",
+ test_character_tabulation_with_justification_alias: "CHARACTER TABULATION WITH JUSTIFICATION",
+ }
}
|
Some valid named unicode characters cause syntax errors
`"\N{BACKSPACE}another cool trick"` yields a syntax error in RustPython, but runs without error on CPython.
See: https://github.com/charliermarsh/ruff/issues/3207.
|
For reference, Python does throw errors on obviously-invalid named unicode characters like `"\N{AAA} another cool trick"`.
Seems like this is coming from `unicode_names2`. `unicode_names2::character("BACKSPACE")` doesn't return a character.
Related question (out of curiosity): What does `unicode_names2::name('\x08')` return?
It's also a `None`, it doesn't support any of the control characters (so `'\N{LINE FEED}'`, `'\N{NUL}'` etc, all raise SyntaxErrors, this is probably intentional).
After a bit of searching it appears it doesn't support [name aliases](http://www.unicode.org/Public/12.1.0/ucd/NameAliases.txt) (which all these control characters fall into). I personally don't know of any libs that support it but we could just grab that file, parse it and have `unicodedata` and the string parser fall back to it. (or, even better, just build a static map for it)
[unic-ucd-name_aliases](https://docs.rs/unic-ucd-name_aliases/) supports getting alias from the name but not the other way.
https://github.com/progval/unicode_names2/issues/11
unicode_names2 will take patch
https://github.com/progval/unicode_names2/issues/11#issuecomment-1445037320
|
2023-02-26T18:12:04Z
|
0.2
|
2023-02-28T13:33:29Z
|
7e66db0d43b6fd93bc114773ac8e896b7eda62c9
|
[
"string::tests::test_bell_alias",
"string::tests::test_backspace_alias",
"string::tests::test_carriage_return_alias",
"string::tests::test_delete_alias",
"string::tests::test_character_tabulation_with_justification_alias",
"string::tests::test_escape_alias",
"string::tests::test_form_feed_alias",
"string::tests::test_hts_alias"
] |
[
"context::tests::test_ann_assign_name",
"context::tests::test_assign_named_expr",
"context::tests::test_assign_name",
"context::tests::test_assign_for",
"context::tests::test_assign_list",
"context::tests::test_assign_attribute",
"context::tests::test_assign_with",
"context::tests::test_assign_set_comp",
"context::tests::test_assign_list_comp",
"context::tests::test_assign_starred",
"context::tests::test_assign_subscript",
"context::tests::test_assign_tuple",
"function::tests::test_default_arg_error_f",
"context::tests::test_del_name",
"function::tests::test_default_arg_error_l",
"context::tests::test_aug_assign_name",
"context::tests::test_del_subscript",
"context::tests::test_del_attribute",
"function::tests::test_duplicates_f2",
"context::tests::test_aug_assign_attribute",
"context::tests::test_aug_assign_subscript",
"function::tests::test_duplicates_f3",
"function::tests::test_duplicate_kw_f1",
"function::tests::test_duplicates_f4",
"function::tests::test_duplicates_l1",
"function::tests::test_duplicates_f1",
"function::tests::test_duplicates_f5",
"function::tests::test_duplicates_l2",
"function::tests::test_duplicates_l3",
"function::tests::test_duplicates_l5",
"function::tests::test_function_no_args",
"function::tests::test_duplicates_l4",
"function::tests::test_function_kw_only_args_with_defaults",
"function::tests::test_function_pos_and_kw_only_args",
"function::tests::test_function_kw_only_args",
"function::tests::test_function_pos_and_kw_only_args_with_defaults",
"function::tests::test_lambda_no_args",
"function::tests::test_positional_arg_error_f",
"function::tests::test_function_pos_args",
"function::tests::test_unpacked_arg_error_f",
"function::tests::test_function_pos_args_with_defaults",
"function::tests::test_lambda_kw_only_args",
"function::tests::test_function_pos_and_kw_only_args_with_defaults_and_varargs",
"lexer::tests::test_assignment",
"lexer::tests::test_comment_until_unix_eol",
"function::tests::test_lambda_pos_and_kw_only_args",
"lexer::tests::test_comment_until_mac_eol",
"function::tests::test_function_pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs",
"function::tests::test_lambda_kw_only_args_with_defaults",
"lexer::tests::test_comment_until_windows_eol",
"lexer::tests::test_double_dedent_mac_eol",
"lexer::tests::test_double_dedent_tabs_mac_eol",
"function::tests::test_lambda_pos_args_with_defaults",
"lexer::tests::test_double_dedent_tabs_unix_eol",
"function::tests::test_lambda_pos_args",
"lexer::tests::test_double_dedent_tabs_windows_eol",
"lexer::tests::test_double_dedent_unix_eol",
"lexer::tests::test_double_dedent_windows_eol",
"lexer::tests::test_escape_unicode_name",
"lexer::tests::test_indentation_mac_eol",
"lexer::tests::test_indentation_unix_eol",
"lexer::tests::test_indentation_windows_eol",
"lexer::tests::test_line_comment_empty",
"lexer::tests::test_line_comment_long",
"lexer::tests::test_line_comment_single_whitespace",
"lexer::tests::test_line_comment_whitespace",
"lexer::tests::test_logical_newline_line_comment",
"lexer::tests::test_newline_in_brackets_mac_eol",
"lexer::tests::test_newline_in_brackets_unix_eol",
"lexer::tests::test_newline_in_brackets_windows_eol",
"lexer::tests::test_non_logical_newline_in_string_continuation",
"lexer::tests::test_operators",
"lexer::tests::test_string",
"lexer::tests::test_numbers",
"lexer::tests::test_string_continuation_mac_eol",
"lexer::tests::test_string_continuation_unix_eol",
"lexer::tests::test_string_continuation_windows_eol",
"lexer::tests::test_triple_quoted_mac_eol",
"lexer::tests::test_triple_quoted_windows_eol",
"lexer::tests::test_triple_quoted_unix_eol",
"parser::tests::test_dict_unpacking",
"parser::tests::test_modes",
"parser::tests::test_parse_boolop_and",
"parser::tests::test_parse_boolop_or",
"parser::tests::test_parse_dict_comprehension",
"parser::tests::test_parse_empty",
"parser::tests::test_parse_f_string",
"parser::tests::test_parse_generator_comprehension",
"parser::tests::test_parse_class",
"parser::tests::test_parse_if_else_generator_comprehension",
"parser::tests::test_parse_kwargs",
"parser::tests::test_generator_expression_argument",
"parser::tests::test_parse_print_2",
"parser::tests::test_parse_double_list_comprehension",
"parser::tests::test_parse_if_elif_else",
"parser::tests::test_parse_string",
"parser::tests::test_parse_print_hello",
"parser::tests::test_parse_lambda",
"parser::tests::test_parse_list_comprehension",
"parser::tests::test_parse_tuples",
"parser::tests::test_parse_named_expression_generator_comprehension",
"parser::tests::test_slice",
"parser::tests::test_with_statement_invalid",
"parser::tests::test_variadic_generics",
"parser::tests::test_match",
"string::tests::test_escape_octet",
"string::tests::test_escape_char_in_byte_literal",
"parser::tests::test_star_index",
"string::tests::test_double_quoted_byte",
"string::tests::test_fstring_parse_selfdocumenting_base",
"string::tests::test_fstring_line_continuation",
"string::tests::test_fstring_escaped_character",
"string::tests::test_fstring_parse_selfdocumenting_base_more",
"string::tests::test_fstring_escaped_newline",
"string::tests::test_fstring_unescaped_newline",
"string::tests::test_parse_empty_fstring",
"parser::tests::test_match_as_identifier",
"parser::tests::test_try",
"string::tests::test_fstring_parse_selfdocumenting_format",
"string::tests::test_parse_f_string_concat_1",
"string::tests::test_parse_f_string_concat_2",
"string::tests::test_parse_fstring",
"string::tests::test_parse_fstring_equals",
"string::tests::test_parse_f_string_concat_3",
"string::tests::test_parse_fstring_not_equals",
"string::tests::test_parse_fstring_not_nested_spec",
"string::tests::test_parse_fstring_nested_spec",
"string::tests::test_parse_fstring_selfdoc_trailing_space",
"string::tests::test_parse_fstring_selfdoc_prec_space",
"string::tests::test_parse_fstring_yield_expr",
"string::tests::test_parse_invalid_fstring",
"string::tests::test_parse_string_triple_quotes_with_kind",
"string::tests::test_parse_string_concat",
"string::tests::test_parse_u_f_string_concat_1",
"string::tests::test_parse_u_string_concat_1",
"string::tests::test_parse_u_f_string_concat_2",
"string::tests::test_parse_u_string_concat_2",
"string::tests::test_raw_byte_literal_1",
"string::tests::test_raw_byte_literal_2",
"string::tests::test_raw_fstring",
"string::tests::test_triple_quoted_raw_fstring",
"string::tests::test_single_quoted_byte",
"parser::tests::test_try_star",
"parser::tests::test_with_statement",
"parser::tests::test_patma",
"compiler/parser/src/parser.rs - parser::parse_expression (line 63)",
"compiler/parser/src/parser.rs - parser::parse_expression_located (line 85)",
"compiler/parser/src/lexer.rs - lexer::lex (line 198)",
"compiler/parser/src/parser.rs - parser::parse_program (line 36)",
"compiler/parser/src/parser.rs - parser::parse (line 121)",
"compiler/parser/src/lib.rs - (line 96)",
"compiler/parser/src/lexer.rs - lexer (line 14)",
"compiler/parser/src/lib.rs - (line 67)",
"compiler/parser/src/parser.rs - parser::parse_located (line 144)",
"compiler/parser/src/parser.rs - parser::parse (line 112)",
"compiler/parser/src/lib.rs - (line 80)",
"compiler/parser/src/parser.rs - parser::parse_tokens (line 178)"
] |
[] |
[] |
RustPython/RustPython
| 4,306
|
RustPython__RustPython-4306
|
[
"4305"
] |
39bed0df510770a31345f83a381217fe434692f8
|
diff --git a/compiler/parser/python.lalrpop b/compiler/parser/python.lalrpop
--- a/compiler/parser/python.lalrpop
+++ b/compiler/parser/python.lalrpop
@@ -756,7 +756,7 @@ LambdaDef: ast::Expr = {
}
OrTest: ast::Expr = {
- <e1:AndTest> <location:@L> <e2:("or" AndTest)*> <end_location:@R> => {
+ <location:@L> <e1:AndTest> <e2:("or" AndTest)*> <end_location:@R> => {
if e2.is_empty() {
e1
} else {
diff --git a/compiler/parser/python.lalrpop b/compiler/parser/python.lalrpop
--- a/compiler/parser/python.lalrpop
+++ b/compiler/parser/python.lalrpop
@@ -773,7 +773,7 @@ OrTest: ast::Expr = {
};
AndTest: ast::Expr = {
- <e1:NotTest> <location:@L> <e2:("and" NotTest)*> <end_location:@R> => {
+ <location:@L> <e1:NotTest> <e2:("and" NotTest)*> <end_location:@R> => {
if e2.is_empty() {
e1
} else {
|
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -2100,8 +2100,6 @@ def test_binop(self):
self._check_content(s, binop.left, '1 * 2 + (3 )')
self._check_content(s, binop.left.right, '3')
- # TODO: RUSTPYTHON
- @unittest.expectedFailure
def test_boolop(self):
s = dedent('''
if (one_condition and
diff --git a/compiler/parser/src/parser.rs b/compiler/parser/src/parser.rs
--- a/compiler/parser/src/parser.rs
+++ b/compiler/parser/src/parser.rs
@@ -218,4 +218,18 @@ class Foo(A, B):
let parse_ast = parse_expression(&source, "<test>").unwrap();
insta::assert_debug_snapshot!(parse_ast);
}
+
+ #[test]
+ fn test_parse_boolop_or() {
+ let source = String::from("x or y");
+ let parse_ast = parse_expression(&source, "<test>").unwrap();
+ insta::assert_debug_snapshot!(parse_ast);
+ }
+
+ #[test]
+ fn test_parse_boolop_and() {
+ let source = String::from("x and y");
+ let parse_ast = parse_expression(&source, "<test>").unwrap();
+ insta::assert_debug_snapshot!(parse_ast);
+ }
}
diff --git /dev/null b/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_boolop_and.snap
new file mode 100644
--- /dev/null
+++ b/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_boolop_and.snap
@@ -0,0 +1,56 @@
+---
+source: compiler/parser/src/parser.rs
+expression: parse_ast
+---
+Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 7,
+ },
+ ),
+ custom: (),
+ node: BoolOp {
+ op: And,
+ values: [
+ Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 1,
+ },
+ ),
+ custom: (),
+ node: Name {
+ id: "x",
+ ctx: Load,
+ },
+ },
+ Located {
+ location: Location {
+ row: 1,
+ column: 6,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 7,
+ },
+ ),
+ custom: (),
+ node: Name {
+ id: "y",
+ ctx: Load,
+ },
+ },
+ ],
+ },
+}
diff --git /dev/null b/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_boolop_or.snap
new file mode 100644
--- /dev/null
+++ b/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_boolop_or.snap
@@ -0,0 +1,56 @@
+---
+source: compiler/parser/src/parser.rs
+expression: parse_ast
+---
+Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 6,
+ },
+ ),
+ custom: (),
+ node: BoolOp {
+ op: Or,
+ values: [
+ Located {
+ location: Location {
+ row: 1,
+ column: 0,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 1,
+ },
+ ),
+ custom: (),
+ node: Name {
+ id: "x",
+ ctx: Load,
+ },
+ },
+ Located {
+ location: Location {
+ row: 1,
+ column: 5,
+ },
+ end_location: Some(
+ Location {
+ row: 1,
+ column: 6,
+ },
+ ),
+ custom: (),
+ node: Name {
+ id: "y",
+ ctx: Load,
+ },
+ },
+ ],
+ },
+}
|
Is the start location of `ExprKind::BoolOp` correct?
In https://github.com/charliermarsh/ruff/pull/1009, I found the start location of `ExprKind::BoolOp` points to `or` or `and`.
Example:
```python
foo or bar
^
foo and bar
^
# ^ represents the start location of this BoolOp expression
```
Is this intended? Should the start location point to `foo` in the example above?
```python
foo or bar
^
foo and bar
^
```
|
Not sure if this works, but can we move `<location:@L>` before `<e1:AndTest>`?
https://github.com/RustPython/RustPython/blob/18af44b7c7410c3448df1f3b080bd358e586d265/compiler/parser/python.lalrpop#L758-L766
Thank for you reporting. That seems going to be working.
@youknowone Thanks for the comment. I'll file a PR.
|
2022-12-04T04:46:03Z
|
0.1
|
2022-12-05T00:49:37Z
|
3a5716da2ac26ebebe40a1de2b9bfd63b0508519
|
[
"parser::tests::test_parse_boolop_or",
"parser::tests::test_parse_boolop_and"
] |
[
"context::tests::test_assign_attribute",
"context::tests::test_assign_named_expr",
"context::tests::test_ann_assign_name",
"context::tests::test_assign_for",
"context::tests::test_assign_name",
"context::tests::test_assign_list",
"context::tests::test_assign_with",
"context::tests::test_assign_starred",
"context::tests::test_assign_subscript",
"context::tests::test_assign_tuple",
"context::tests::test_assign_list_comp",
"context::tests::test_assign_set_comp",
"context::tests::test_del_attribute",
"fstring::tests::test_parse_empty_fstring",
"context::tests::test_aug_assign_subscript",
"context::tests::test_del_name",
"fstring::tests::test_fstring_parse_selfdocumenting_format",
"fstring::tests::test_fstring_parse_selfdocumenting_base_more",
"fstring::tests::test_fstring_parse_selfdocumenting_base",
"context::tests::test_aug_assign_attribute",
"context::tests::test_aug_assign_name",
"context::tests::test_del_subscript",
"fstring::tests::test_parse_fstring",
"fstring::tests::test_parse_fstring_equals",
"fstring::tests::test_parse_fstring_not_equals",
"fstring::tests::test_parse_fstring_nested_spec",
"lexer::tests::test_assignment",
"fstring::tests::test_parse_fstring_selfdoc_prec_space",
"fstring::tests::test_parse_fstring_selfdoc_trailing_space",
"fstring::tests::test_parse_fstring_not_nested_spec",
"lexer::tests::test_comment_until_mac_eol",
"lexer::tests::test_comment_until_unix_eol",
"lexer::tests::test_comment_until_windows_eol",
"lexer::tests::test_double_dedent_mac_eol",
"lexer::tests::test_double_dedent_tabs_mac_eol",
"lexer::tests::test_double_dedent_tabs_unix_eol",
"lexer::tests::test_double_dedent_windows_eol",
"fstring::tests::test_parse_invalid_fstring",
"lexer::tests::test_double_dedent_tabs_windows_eol",
"lexer::tests::test_escape_char_in_byte_literal",
"lexer::tests::test_escape_octet",
"lexer::tests::test_double_quoted_byte",
"lexer::tests::test_double_dedent_unix_eol",
"lexer::tests::test_escape_unicode_name",
"fstring::tests::test_parse_fstring_yield_expr",
"lexer::tests::test_indentation_mac_eol",
"lexer::tests::test_indentation_windows_eol",
"lexer::tests::test_line_comment_empty",
"lexer::tests::test_line_comment_single_whitespace",
"lexer::tests::test_indentation_unix_eol",
"lexer::tests::test_line_comment_whitespace",
"lexer::tests::test_newline_in_brackets_mac_eol",
"lexer::tests::test_newline_in_brackets_unix_eol",
"lexer::tests::test_newline_in_brackets_windows_eol",
"lexer::tests::test_newline_processor",
"lexer::tests::test_operators",
"lexer::tests::test_numbers",
"lexer::tests::test_raw_byte_literal",
"lexer::tests::test_raw_string",
"lexer::tests::test_string",
"lexer::tests::test_string_continuation_mac_eol",
"lexer::tests::test_string_continuation_unix_eol",
"lexer::tests::test_single_quoted_byte",
"lexer::tests::test_string_continuation_windows_eol",
"parser::tests::test_parse_dict_comprehension",
"parser::tests::test_parse_f_string",
"parser::tests::test_parse_generator_comprehension",
"lexer::tests::test_line_comment_long",
"parser::tests::test_parse_kwargs",
"parser::tests::test_parse_if_else_generator_comprehension",
"parser::tests::test_parse_named_expression_generator_comprehension",
"parser::tests::test_parse_lambda",
"parser::tests::test_parse_double_list_comprehension",
"parser::tests::test_parse_if_elif_else",
"parser::tests::test_parse_class",
"parser::tests::test_parse_empty",
"string::tests::test_parse_string_triple_quotes_with_kind",
"string::tests::test_parse_f_string_concat_1",
"parser::tests::test_parse_print_hello",
"parser::tests::test_parse_list_comprehension",
"string::tests::test_parse_f_string_concat_3",
"string::tests::test_parse_string_concat",
"parser::tests::test_parse_print_2",
"string::tests::test_parse_f_string_concat_2",
"parser::tests::test_parse_tuples",
"parser::tests::test_parse_string",
"string::tests::test_parse_u_f_string_concat_1",
"string::tests::test_parse_u_f_string_concat_2",
"string::tests::test_parse_u_string_concat_1",
"string::tests::test_parse_u_string_concat_2",
"compiler/parser/src/lib.rs - (line 10)",
"compiler/parser/src/parser.rs - parser::parse_expression (line 31)"
] |
[] |
[] |
RustPython/RustPython
| 4,220
|
RustPython__RustPython-4220
|
[
"4219"
] |
1cb7f4dcf8a6670064d2f86e2a5055f8a77d89f3
|
diff --git a/compiler/parser/src/lexer.rs b/compiler/parser/src/lexer.rs
--- a/compiler/parser/src/lexer.rs
+++ b/compiler/parser/src/lexer.rs
@@ -205,7 +205,9 @@ where
// Check if we have a string:
if self.chr0 == Some('"') || self.chr0 == Some('\'') {
- return self.lex_string(saw_b, saw_r, saw_u, saw_f);
+ return self
+ .lex_string(saw_b, saw_r, saw_u, saw_f)
+ .map(|(_, tok, end_pos)| (start_pos, tok, end_pos));
}
}
|
diff --git a/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_f_string.snap b/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_f_string.snap
--- a/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_f_string.snap
+++ b/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_f_string.snap
@@ -1,19 +1,19 @@
---
-source: parser/src/parser.rs
+source: compiler/parser/src/parser.rs
expression: parse_ast
---
[
Located {
location: Location {
row: 1,
- column: 3,
+ column: 1,
},
custom: (),
node: Expr {
value: Located {
location: Location {
row: 1,
- column: 3,
+ column: 1,
},
custom: (),
node: JoinedStr {
diff --git a/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_f_string.snap b/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_f_string.snap
--- a/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_f_string.snap
+++ b/compiler/parser/src/snapshots/rustpython_parser__parser__tests__parse_f_string.snap
@@ -21,7 +21,7 @@ expression: parse_ast
Located {
location: Location {
row: 1,
- column: 3,
+ column: 1,
},
custom: (),
node: Constant {
diff --git a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_f_string_concat_3.snap b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_f_string_concat_3.snap
--- a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_f_string_concat_3.snap
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_f_string_concat_3.snap
@@ -1,5 +1,5 @@
---
-source: parser/src/string.rs
+source: compiler/parser/src/string.rs
expression: parse_ast
---
[
diff --git a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_f_string_concat_3.snap b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_f_string_concat_3.snap
--- a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_f_string_concat_3.snap
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_f_string_concat_3.snap
@@ -34,7 +34,7 @@ expression: parse_ast
Located {
location: Location {
row: 1,
- column: 12,
+ column: 10,
},
custom: (),
node: FormattedValue {
diff --git /dev/null b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_string_triple_quotes_with_kind.snap
new file mode 100644
--- /dev/null
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_string_triple_quotes_with_kind.snap
@@ -0,0 +1,30 @@
+---
+source: compiler/parser/src/string.rs
+expression: parse_ast
+---
+[
+ Located {
+ location: Location {
+ row: 1,
+ column: 1,
+ },
+ custom: (),
+ node: Expr {
+ value: Located {
+ location: Location {
+ row: 1,
+ column: 1,
+ },
+ custom: (),
+ node: Constant {
+ value: Str(
+ "Hello, world!",
+ ),
+ kind: Some(
+ "u",
+ ),
+ },
+ },
+ },
+ },
+]
diff --git a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_1.snap b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_1.snap
--- a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_1.snap
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_1.snap
@@ -1,19 +1,19 @@
---
-source: parser/src/string.rs
+source: compiler/parser/src/string.rs
expression: parse_ast
---
[
Located {
location: Location {
row: 1,
- column: 3,
+ column: 1,
},
custom: (),
node: Expr {
value: Located {
location: Location {
row: 1,
- column: 3,
+ column: 1,
},
custom: (),
node: JoinedStr {
diff --git a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_1.snap b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_1.snap
--- a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_1.snap
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_1.snap
@@ -21,7 +21,7 @@ expression: parse_ast
Located {
location: Location {
row: 1,
- column: 3,
+ column: 1,
},
custom: (),
node: Constant {
diff --git a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_2.snap b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_2.snap
--- a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_2.snap
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_2.snap
@@ -1,19 +1,19 @@
---
-source: parser/src/string.rs
+source: compiler/parser/src/string.rs
expression: parse_ast
---
[
Located {
location: Location {
row: 1,
- column: 3,
+ column: 1,
},
custom: (),
node: Expr {
value: Located {
location: Location {
row: 1,
- column: 3,
+ column: 1,
},
custom: (),
node: JoinedStr {
diff --git a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_2.snap b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_2.snap
--- a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_2.snap
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_f_string_concat_2.snap
@@ -21,7 +21,7 @@ expression: parse_ast
Located {
location: Location {
row: 1,
- column: 3,
+ column: 1,
},
custom: (),
node: Constant {
diff --git a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_string_concat_2.snap b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_string_concat_2.snap
--- a/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_string_concat_2.snap
+++ b/compiler/parser/src/snapshots/rustpython_parser__string__tests__parse_u_string_concat_2.snap
@@ -1,19 +1,19 @@
---
-source: parser/src/string.rs
+source: compiler/parser/src/string.rs
expression: parse_ast
---
[
Located {
location: Location {
row: 1,
- column: 3,
+ column: 1,
},
custom: (),
node: Expr {
value: Located {
location: Location {
row: 1,
- column: 3,
+ column: 1,
},
custom: (),
node: Constant {
diff --git a/compiler/parser/src/string.rs b/compiler/parser/src/string.rs
--- a/compiler/parser/src/string.rs
+++ b/compiler/parser/src/string.rs
@@ -131,4 +131,11 @@ mod tests {
let parse_ast = parse_program(&source, "<test>").unwrap();
insta::assert_debug_snapshot!(parse_ast);
}
+
+ #[test]
+ fn test_parse_string_triple_quotes_with_kind() {
+ let source = String::from("u'''Hello, world!'''");
+ let parse_ast = parse_program(&source, "<test>").unwrap();
+ insta::assert_debug_snapshot!(parse_ast);
+ }
}
|
Parsed string start location differs from CPython's AST parser
If you parse `x = u"""abc"""`, RustPython reports that the `Constant` starts at one-indexed column 7 (just after the first `"`):
```
[
Located {
location: Location {
row: 1,
column: 1,
},
end_location: Location {
row: 1,
column: 15,
},
custom: (),
node: Assign {
targets: [
Located {
location: Location {
row: 1,
column: 1,
},
end_location: Location {
row: 1,
column: 2,
},
custom: (),
node: Name {
id: "x",
ctx: Store,
},
},
],
value: Located {
location: Location {
row: 1,
column: 7,
},
end_location: Location {
row: 1,
column: 15,
},
custom: (),
node: Constant {
value: Str(
"abc",
),
kind: Some(
"u",
),
},
},
type_comment: None,
},
},
]
```
CPython reports that the `Constant` starts at one-indexed column 5 (at the `u`).
|
2022-10-15T23:04:08Z
|
0.1
|
2022-10-15T15:51:20Z
|
3a5716da2ac26ebebe40a1de2b9bfd63b0508519
|
[
"parser::tests::test_parse_f_string",
"string::tests::test_parse_string_triple_quotes_with_kind",
"string::tests::test_parse_u_f_string_concat_1",
"string::tests::test_parse_u_string_concat_2",
"string::tests::test_parse_u_f_string_concat_2",
"string::tests::test_parse_f_string_concat_3"
] |
[
"fstring::tests::test_parse_empty_fstring",
"fstring::tests::test_fstring_parse_selfdocumenting_base",
"fstring::tests::test_parse_fstring",
"fstring::tests::test_fstring_parse_selfdocumenting_base_more",
"fstring::tests::test_fstring_parse_selfdocumenting_format",
"fstring::tests::test_parse_fstring_not_equals",
"fstring::tests::test_parse_fstring_equals",
"lexer::tests::test_assignment",
"fstring::tests::test_parse_fstring_selfdoc_trailing_space",
"fstring::tests::test_parse_fstring_not_nested_spec",
"fstring::tests::test_parse_fstring_nested_spec",
"fstring::tests::test_parse_fstring_yield_expr",
"lexer::tests::test_comment_until_mac_eol",
"fstring::tests::test_parse_fstring_selfdoc_prec_space",
"lexer::tests::test_comment_until_unix_eol",
"lexer::tests::test_double_dedent_mac_eol",
"lexer::tests::test_double_dedent_tabs_mac_eol",
"lexer::tests::test_double_dedent_tabs_unix_eol",
"lexer::tests::test_double_dedent_tabs_windows_eol",
"lexer::tests::test_double_dedent_windows_eol",
"lexer::tests::test_comment_until_windows_eol",
"lexer::tests::test_escape_char_in_byte_literal",
"lexer::tests::test_double_quoted_byte",
"lexer::tests::test_escape_octet",
"lexer::tests::test_double_dedent_unix_eol",
"fstring::tests::test_parse_invalid_fstring",
"lexer::tests::test_escape_unicode_name",
"lexer::tests::test_indentation_mac_eol",
"lexer::tests::test_indentation_unix_eol",
"lexer::tests::test_line_comment_empty",
"lexer::tests::test_indentation_windows_eol",
"lexer::tests::test_line_comment_long",
"lexer::tests::test_line_comment_single_whitespace",
"lexer::tests::test_line_comment_whitespace",
"lexer::tests::test_newline_in_brackets_mac_eol",
"lexer::tests::test_newline_in_brackets_unix_eol",
"lexer::tests::test_newline_in_brackets_windows_eol",
"lexer::tests::test_newline_processor",
"lexer::tests::test_numbers",
"lexer::tests::test_operators",
"lexer::tests::test_raw_byte_literal",
"lexer::tests::test_raw_string",
"lexer::tests::test_single_quoted_byte",
"lexer::tests::test_string",
"lexer::tests::test_string_continuation_mac_eol",
"lexer::tests::test_string_continuation_unix_eol",
"lexer::tests::test_string_continuation_windows_eol",
"parser::tests::test_parse_empty",
"parser::tests::test_parse_dict_comprehension",
"parser::tests::test_parse_generator_comprehension",
"parser::tests::test_parse_if_elif_else",
"parser::tests::test_parse_list_comprehension",
"parser::tests::test_parse_class",
"parser::tests::test_parse_if_else_generator_comprehension",
"parser::tests::test_parse_double_list_comprehension",
"parser::tests::test_parse_lambda",
"parser::tests::test_parse_kwargs",
"parser::tests::test_parse_named_expression_generator_comprehension",
"parser::tests::test_parse_print_2",
"parser::tests::test_parse_tuples",
"parser::tests::test_parse_string",
"string::tests::test_parse_f_string_concat_1",
"string::tests::test_parse_f_string_concat_2",
"parser::tests::test_parse_print_hello",
"string::tests::test_parse_string_concat",
"string::tests::test_parse_u_string_concat_1",
"compiler/parser/src/lib.rs - (line 10)",
"compiler/parser/src/parser.rs - parser::parse_expression (line 29)"
] |
[] |
[] |
|
RustScan/RustScan
| 246
|
RustScan__RustScan-246
|
[
"239"
] |
739e9716fc22e62b53c0ed5a5998bd743152978f
|
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1,5 +1,20 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
+[[package]]
+name = "addr2line"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b6a2d3371669ab3ca9797670853d61402b03d0b4b9ebf33d677dfa720203072"
+dependencies = [
+ "gimli",
+]
+
+[[package]]
+name = "adler"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee2a4ec343196209d6594e19543ae87a39f96d5534d7174822a3ad825dd6ed7e"
+
[[package]]
name = "aho-corasick"
version = "0.7.13"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -15,7 +30,7 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
dependencies = [
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -24,7 +39,7 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2"
dependencies = [
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -95,7 +110,7 @@ dependencies = [
"vec-arena",
"waker-fn",
"wepoll-sys-stjepang",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -141,6 +156,17 @@ version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c17772156ef2829aadc587461c7753af20b7e8db1529bc66855add962a3b35d3"
+[[package]]
+name = "async-trait"
+version = "0.1.40"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "687c230d85c0a52504709705fc8a53e4a692b83a2184f03dae73e38e1e93a783"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "atomic-waker"
version = "1.0.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -155,7 +181,7 @@ checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi",
"libc",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -164,6 +190,20 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d"
+[[package]]
+name = "backtrace"
+version = "0.3.50"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46254cf2fdcdf1badb5934448c1bcbe046a56537b3987d96c51a7afc5d03f293"
+dependencies = [
+ "addr2line",
+ "cfg-if",
+ "libc",
+ "miniz_oxide",
+ "object",
+ "rustc-demangle",
+]
+
[[package]]
name = "base64"
version = "0.11.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -261,7 +307,7 @@ checksum = "b3616f750b84d8f0de8a58bda93e08e2a81ad3f523089b05f1dffecab48c6cbd"
dependencies = [
"atty",
"lazy_static",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -319,7 +365,7 @@ checksum = "8e93d7f5705de3e49895a2b5e0b8855a1c27f080192ae9c32a6432d50741a57a"
dependencies = [
"libc",
"redox_users",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -328,6 +374,18 @@ version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457"
+[[package]]
+name = "enum-as-inner"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c5f0096a91d210159eceb2ff5e1c4da18388a170e1e3ce948aac9c8fdbbf595"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "env_logger"
version = "0.7.1"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -353,6 +411,22 @@ version = "1.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c85295147490b8fcf2ea3d104080a105a8b2c63f9c319e82c02d8e952388919"
+[[package]]
+name = "fuchsia-zircon"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82"
+dependencies = [
+ "bitflags",
+ "fuchsia-zircon-sys",
+]
+
+[[package]]
+name = "fuchsia-zircon-sys"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7"
+
[[package]]
name = "futures"
version = "0.3.5"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -480,6 +554,12 @@ dependencies = [
"wasi",
]
+[[package]]
+name = "gimli"
+version = "0.22.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aaf91faf136cb47367fa430cd46e37a788775e7fa104f8b4bcb3861dc389b724"
+
[[package]]
name = "gloo-timers"
version = "0.2.1"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -511,6 +591,17 @@ dependencies = [
"libc",
]
+[[package]]
+name = "hostname"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c731c3e10504cc8ed35cfe2f1db4c9274c3d35fa486e3b31df46f068ef3e867"
+dependencies = [
+ "libc",
+ "match_cfg",
+ "winapi 0.3.9",
+]
+
[[package]]
name = "humantime"
version = "1.3.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -520,6 +611,38 @@ dependencies = [
"quick-error",
]
+[[package]]
+name = "idna"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02e2673c30ee86b5b96a9cb52ad15718aa1f966f5ab9ad54a8b95d5ca33120a9"
+dependencies = [
+ "matches",
+ "unicode-bidi",
+ "unicode-normalization",
+]
+
+[[package]]
+name = "iovec"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "ipconfig"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7e2f18aece9709094573a9f24f483c4f65caa4298e2f7ae1b71cc65d853fad7"
+dependencies = [
+ "socket2",
+ "widestring",
+ "winapi 0.3.9",
+ "winreg",
+]
+
[[package]]
name = "itertools"
version = "0.9.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -538,6 +661,16 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "kernel32-sys"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"
+dependencies = [
+ "winapi 0.2.8",
+ "winapi-build",
+]
+
[[package]]
name = "kv-log-macro"
version = "1.0.7"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -559,6 +692,12 @@ version = "0.2.77"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f96b10ec2560088a8e76961b00d47107b3a625fecb76dedb29ee7ccbf98235"
+[[package]]
+name = "linked-hash-map"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8dd5a6d5999d9907cda8ed67bbd137d3af8085216c2ac62de5be860bd41f304a"
+
[[package]]
name = "log"
version = "0.4.11"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -568,12 +707,85 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "lru-cache"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31e24f1ad8321ca0e8a1e0ac13f23cb668e6f5466c2c57319f6a5cf1cc8e3b1c"
+dependencies = [
+ "linked-hash-map",
+]
+
+[[package]]
+name = "match_cfg"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffbee8634e0d45d258acb448e7eaab3fce7a0a467395d4d9f228e3c1f01fb2e4"
+
+[[package]]
+name = "matches"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08"
+
[[package]]
name = "memchr"
version = "2.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400"
+[[package]]
+name = "miniz_oxide"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c60c0dfe32c10b43a144bad8fc83538c52f58302c92300ea7ec7bf7b38d5a7b9"
+dependencies = [
+ "adler",
+ "autocfg",
+]
+
+[[package]]
+name = "mio"
+version = "0.6.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fce347092656428bc8eaf6201042cb551b8d67855af7374542a92a0fbfcac430"
+dependencies = [
+ "cfg-if",
+ "fuchsia-zircon",
+ "fuchsia-zircon-sys",
+ "iovec",
+ "kernel32-sys",
+ "libc",
+ "log",
+ "miow",
+ "net2",
+ "slab",
+ "winapi 0.2.8",
+]
+
+[[package]]
+name = "miow"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919"
+dependencies = [
+ "kernel32-sys",
+ "net2",
+ "winapi 0.2.8",
+ "ws2_32-sys",
+]
+
+[[package]]
+name = "net2"
+version = "0.2.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ebc3ec692ed7c9a255596c67808dee269f64655d8baf7b4f0638e51ba1d6853"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "winapi 0.3.9",
+]
+
[[package]]
name = "num-bigint"
version = "0.3.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -614,6 +826,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "object"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ab52be62400ca80aa00285d25253d7f7c437b7375c4de678f5405d3afe82ca5"
+
[[package]]
name = "once_cell"
version = "1.4.1"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -626,6 +844,12 @@ version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72"
+[[package]]
+name = "percent-encoding"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e"
+
[[package]]
name = "pin-project"
version = "0.4.23"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -668,7 +892,7 @@ dependencies = [
"libc",
"log",
"wepoll-sys-stjepang",
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -813,6 +1037,31 @@ version = "0.6.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26412eb97c6b088a6997e05f69403a802a92d520de2f8e63c2b65f9e0f47c4e8"
+[[package]]
+name = "resolv-conf"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11834e137f3b14e309437a8276714eed3a80d1ef894869e510f2c0c0b98b9f4a"
+dependencies = [
+ "hostname",
+ "quick-error",
+]
+
+[[package]]
+name = "ring"
+version = "0.16.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "952cd6b98c85bbc30efa1ba5783b8abf12fec8b3287ffa52605b9432313e34e4"
+dependencies = [
+ "cc",
+ "libc",
+ "once_cell",
+ "spin",
+ "untrusted",
+ "web-sys",
+ "winapi 0.3.9",
+]
+
[[package]]
name = "rlimit"
version = "0.4.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -835,6 +1084,25 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "rustc-demangle"
+version = "0.1.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783"
+
+[[package]]
+name = "rustls"
+version = "0.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0d4a31f5d68413404705d6982529b0e11a9aacd4839d1d6222ee3b8cb4015e1"
+dependencies = [
+ "base64",
+ "log",
+ "ring",
+ "sct",
+ "webpki",
+]
+
[[package]]
name = "rustscan"
version = "1.9.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -857,6 +1125,17 @@ dependencies = [
"shell-words",
"structopt",
"toml",
+ "trust-dns-resolver",
+]
+
+[[package]]
+name = "sct"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3042af939fca8c3453b7af0f1c66e533a15a86169e39de2657310ade8f98d3c"
+dependencies = [
+ "ring",
+ "untrusted",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -888,6 +1167,12 @@ version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8"
+[[package]]
+name = "smallvec"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fbee7696b84bbf3d89a1c2eccff0850e3047ed46bfcd2e92c29a2d074d57e252"
+
[[package]]
name = "socket2"
version = "0.3.12"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -897,9 +1182,15 @@ dependencies = [
"cfg-if",
"libc",
"redox_syscall",
- "winapi",
+ "winapi 0.3.9",
]
+[[package]]
+name = "spin"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
+
[[package]]
name = "strsim"
version = "0.8.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -968,6 +1279,39 @@ dependencies = [
"lazy_static",
]
+[[package]]
+name = "tinyvec"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "238ce071d267c5710f9d31451efec16c5ee22de34df17cc05e56cbc92e967117"
+
+[[package]]
+name = "tokio"
+version = "0.2.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d34ca54d84bf2b5b4d7d31e901a8464f7b60ac145a284fba25ceb801f2ddccd"
+dependencies = [
+ "bytes",
+ "iovec",
+ "lazy_static",
+ "memchr",
+ "mio",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "tokio-rustls"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15cb62a0d2770787abc96e99c1cd98fcf17f94959f3af63ca85bdfb203f051b4"
+dependencies = [
+ "futures-core",
+ "rustls",
+ "tokio",
+ "webpki",
+]
+
[[package]]
name = "toml"
version = "0.5.6"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -977,6 +1321,83 @@ dependencies = [
"serde",
]
+[[package]]
+name = "trust-dns-proto"
+version = "0.19.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdd7061ba6f4d4d9721afedffbfd403f20f39a4301fee1b70d6fcd09cca69f28"
+dependencies = [
+ "async-trait",
+ "backtrace",
+ "enum-as-inner",
+ "futures",
+ "idna",
+ "lazy_static",
+ "log",
+ "rand",
+ "smallvec",
+ "thiserror",
+ "tokio",
+ "url",
+]
+
+[[package]]
+name = "trust-dns-resolver"
+version = "0.19.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f23cdfdc3d8300b3c50c9e84302d3bd6d860fb9529af84ace6cf9665f181b77"
+dependencies = [
+ "backtrace",
+ "cfg-if",
+ "futures",
+ "ipconfig",
+ "lazy_static",
+ "log",
+ "lru-cache",
+ "resolv-conf",
+ "rustls",
+ "smallvec",
+ "thiserror",
+ "tokio",
+ "tokio-rustls",
+ "trust-dns-proto",
+ "trust-dns-rustls",
+ "webpki-roots",
+]
+
+[[package]]
+name = "trust-dns-rustls"
+version = "0.19.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "365f4f7efd5f7ab30c143ad4172534077f32ccb16b1977d13e9259d2457744c2"
+dependencies = [
+ "futures",
+ "log",
+ "rustls",
+ "tokio",
+ "tokio-rustls",
+ "trust-dns-proto",
+ "webpki",
+]
+
+[[package]]
+name = "unicode-bidi"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5"
+dependencies = [
+ "matches",
+]
+
+[[package]]
+name = "unicode-normalization"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6fb19cf769fa8c6a80a162df694621ebeb4dafb606470b2b2fce0be40a98a977"
+dependencies = [
+ "tinyvec",
+]
+
[[package]]
name = "unicode-segmentation"
version = "1.6.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -995,6 +1416,23 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
+[[package]]
+name = "untrusted"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
+
+[[package]]
+name = "url"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "829d4a8476c35c9bf0bbce5a3b23f4106f79728039b726d292bb93bc106787cb"
+dependencies = [
+ "idna",
+ "matches",
+ "percent-encoding",
+]
+
[[package]]
name = "vec-arena"
version = "1.0.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1101,6 +1539,25 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "webpki"
+version = "0.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab146130f5f790d45f82aeeb09e55a256573373ec64409fc19a6fb82fb1032ae"
+dependencies = [
+ "ring",
+ "untrusted",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8eff4b7516a57307f9349c64bf34caa34b940b66fed4b2fb3136cb7386e5739"
+dependencies = [
+ "webpki",
+]
+
[[package]]
name = "wepoll-sys-stjepang"
version = "1.0.6"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1110,6 +1567,18 @@ dependencies = [
"cc",
]
+[[package]]
+name = "widestring"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a763e303c0e0f23b0da40888724762e802a8ffefbc22de4127ef42493c2ea68c"
+
+[[package]]
+name = "winapi"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"
+
[[package]]
name = "winapi"
version = "0.3.9"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1120,6 +1589,12 @@ dependencies = [
"winapi-x86_64-pc-windows-gnu",
]
+[[package]]
+name = "winapi-build"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc"
+
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1132,7 +1607,7 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
dependencies = [
- "winapi",
+ "winapi 0.3.9",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1140,3 +1615,22 @@ name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "winreg"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2986deb581c4fe11b621998a5e53361efe6b48a151178d0cd9eeffa4dc6acc9"
+dependencies = [
+ "winapi 0.3.9",
+]
+
+[[package]]
+name = "ws2_32-sys"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e"
+dependencies = [
+ "winapi 0.2.8",
+ "winapi-build",
+]
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -35,6 +35,7 @@ serde = "1.0.116"
serde_derive = "1.0.116"
cidr-utils = "0.5.0"
itertools = "0.9.0"
+trust-dns-resolver = { version = "0.19.5", features = ["dns-over-rustls"] }
[package.metadata.deb]
depends = "$auto, nmap"
diff --git /dev/null b/fixtures/hosts.txt
new file mode 100644
--- /dev/null
+++ b/fixtures/hosts.txt
@@ -0,0 +1,6 @@
+127.0.0.1
+google.com
+example.com
+66666666666666.666666666666666666.66666666666666666.6666666666
+....
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.radiatorFixtures
\ No newline at end of file
diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -26,8 +26,9 @@ use std::io::prelude::*;
use std::io::BufReader;
use std::net::ToSocketAddrs;
use std::process::Command;
-use std::str::FromStr;
use std::{net::IpAddr, time::Duration};
+use trust_dns_resolver::config::*;
+use trust_dns_resolver::Resolver;
extern crate colorful;
extern crate dirs;
diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -208,9 +209,54 @@ fn build_nmap_arguments<'a>(
arguments
}
+/// Goes through all possible IP inputs (files or via argparsing)
+/// Parses the string(s) into IPs
+fn parse_addresses(opts: &Opts) -> Vec<IpAddr> {
+ let mut ips: Vec<IpAddr> = Vec::new();
+ let resolver = &Resolver::new(ResolverConfig::default(), ResolverOpts::default()).unwrap();
+
+ for ip_or_host in &opts.addresses {
+ match read_ips_from_file(ip_or_host.to_owned(), &resolver) {
+ Ok(x) => ips.extend(x),
+ _ => match parse_to_ip(ip_or_host.to_owned(), &resolver) {
+ Ok(x) => ips.extend(x),
+ _ => {
+ warning!(
+ format!("Host {:?} could not be resolved.", ip_or_host),
+ opts.greppable,
+ opts.accessible
+ );
+ }
+ },
+ }
+ }
+ ips
+}
+
+/// Uses DNS to get the IPS assiocated with host
+fn resolve_ips_from_host(
+ source: &String,
+ resolver: &Resolver,
+) -> Result<Vec<IpAddr>, std::io::Error> {
+ let mut ips: Vec<std::net::IpAddr> = Vec::new();
+
+ match resolver.lookup_ip(&source) {
+ Ok(x) => {
+ for ip in x.iter() {
+ ips.push(ip);
+ }
+ }
+ _ => (),
+ };
+ return Ok(ips);
+}
+
#[cfg(not(tarpaulin_include))]
/// Parses an input file of IPs and uses those
-fn read_ips_from_file(ips: String) -> Result<Vec<std::net::IpAddr>, std::io::Error> {
+fn read_ips_from_file(
+ ips: String,
+ resolver: &Resolver,
+) -> Result<Vec<std::net::IpAddr>, std::io::Error> {
// if we cannot open it as a file, it is not a file so move on
let file = File::open(ips)?;
let reader = BufReader::new(file);
diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -218,37 +264,39 @@ fn read_ips_from_file(ips: String) -> Result<Vec<std::net::IpAddr>, std::io::Err
let mut ips: Vec<std::net::IpAddr> = Vec::new();
for str_ip in reader.lines() {
- match IpAddr::from_str(&str_ip.unwrap()) {
- Ok(x) => ips.push(x),
- Err(y) => panic!("File does not contain valid IP address. Error at {}", y),
+ match str_ip {
+ Ok(x) => match parse_to_ip(x, resolver) {
+ Ok(result) => ips.extend(result),
+ Err(e) => {
+ debug!("{} is not a valid IP or host", e);
+ }
+ },
+ Err(_) => {
+ debug!("Line in file is not valid");
+ }
}
}
Ok(ips)
}
-fn parse_addresses(opts: &Opts) -> Vec<IpAddr> {
+/// Given a string, parse it as an host, IP address, or CIDR.
+/// This allows us to pass files as hosts or cidr or IPs easily
+/// Call this everytime you have a possible IP_or_host
+fn parse_to_ip(address: String, resolver: &Resolver) -> Result<Vec<IpAddr>, std::io::Error> {
let mut ips: Vec<IpAddr> = Vec::new();
- for ip_or_host in &opts.addresses {
- match IpCidr::from_str(ip_or_host) {
- Ok(cidr) => cidr.iter().for_each(|ip| ips.push(ip)),
- _ => match format!("{}:{}", &ip_or_host, 80).to_socket_addrs() {
- Ok(mut iter) => ips.push(iter.nth(0).unwrap().ip()),
- _ => match read_ips_from_file(ip_or_host.to_owned()) {
- Ok(x) => ips.extend(x),
- _ => {
- warning!(
- format!("Host {:?} could not be resolved.", ip_or_host),
- opts.greppable,
- opts.accessible
- );
- }
- },
+ match IpCidr::from_str(&address) {
+ Ok(cidr) => cidr.iter().for_each(|ip| ips.push(ip)),
+ _ => match format!("{}:{}", &address, 80).to_socket_addrs() {
+ Ok(mut iter) => ips.push(iter.nth(0).unwrap().ip()),
+ _ => match resolve_ips_from_host(&address, resolver) {
+ Ok(hosts) => ips.extend(hosts),
+ _ => (),
},
- }
- }
+ },
+ };
- ips
+ Ok(ips)
}
fn adjust_ulimit_size(opts: &Opts) -> rlimit::rlim {
diff --git a/src/rustscan_scripting_engine /dev/null
--- a/src/rustscan_scripting_engine
+++ /dev/null
@@ -1,1 +0,0 @@
-Subproject commit 13c3fabcacee38deeee56a681e0fdf1404eefa4b
|
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -207,6 +247,12 @@ version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e8c087f005730276d1096a652e92a8bacee2e2472bcc9715a74d2bec38b5820"
+[[package]]
+name = "bytes"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e4cec68f03f32e44924783795810fa50a7035d8c8ebe78580ad7e6c703fba38"
+
[[package]]
name = "cache-padded"
version = "1.1.1"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -959,6 +1250,26 @@ dependencies = [
"unicode-width",
]
+[[package]]
+name = "thiserror"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dfdd070ccd8ccb78f4ad66bf1982dc37f620ef696c6b5028fe2ed83dd3d0d08"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd80fc12f73063ac132ac92aceea36734f04a1d93c1240c6944e23a3b8841793"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "thread_local"
version = "1.0.1"
diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -419,4 +467,12 @@ mod tests {
assert_eq!(ips.is_empty(), true);
}
+ #[test]
+ fn parse_hosts_file_and_incorrect_hosts() {
+ // Host file contains IP, Hosts, incorrect IPs, incorrect hosts
+ let mut opts = Opts::default();
+ opts.addresses = vec!["fixtures/hosts.txt".to_owned()];
+ let ips = parse_addresses(&opts);
+ assert_eq!(ips.len(), 3);
+ }
}
|
Use DNS instead of socket connection
Currently RustScan connects to port 80 to resolve the host using sockets, DNS would be much nicer to use.
|
Issue-Label Bot is automatically applying the label `feature_request` to this issue, with a confidence of 0.95. Please mark this comment with :thumbsup: or :thumbsdown: to give our bot feedback!
Links: [app homepage](https://github.com/marketplace/issue-label-bot), [dashboard](https://mlbot.net/data/RustScan/RustScan) and [code](https://github.com/hamelsmu/MLapp) for this bot.
|
2020-09-28T04:49:20Z
|
1.9
|
2020-09-29T10:49:25Z
|
739e9716fc22e62b53c0ed5a5998bd743152978f
|
[
"tests::parse_hosts_file_and_incorrect_hosts"
] |
[
"input::tests::opts_merge_optional_arguments",
"input::tests::opts_merge_required_arguments",
"input::tests::opts_no_merge_when_config_is_ignored",
"port_strategy::tests::serial_strategy_with_ports",
"scanner::socket_iterator::tests::goes_through_every_ip_port_combination",
"port_strategy::tests::random_strategy_with_ports",
"port_strategy::tests::serial_strategy_with_range",
"port_strategy::tests::random_strategy_with_range",
"tests::batch_size_adjusted_2000",
"tests::batch_size_equals_ulimit_lowered",
"tests::batch_size_lowered",
"tests::batch_size_lowered_average_size",
"tests::parse_correct_addresses",
"tests::test_high_ulimit_no_greppable_mode",
"tests::parse_correct_host_addresses",
"tests::test_print_opening_no_panic",
"tests::parse_correct_and_incorrect_addresses",
"port_strategy::range_iterator::tests::range_iterator_iterates_through_the_entire_range",
"scanner::tests::quad_zero_scanner_runs",
"scanner::tests::ipv6_scanner_runs",
"scanner::tests::scanner_runs",
"benchmark::benchmark",
"tests::parse_incorrect_addresses",
"scanner::tests::google_dns_runs",
"scanner::tests::infer_ulimit_lowering_no_panic"
] |
[] |
[] |
RustScan/RustScan
| 660
|
RustScan__RustScan-660
|
[
"651"
] |
c3d24feebef4c605535a6661ddfeaa18b9bde60c
|
diff --git a/src/address.rs b/src/address.rs
--- a/src/address.rs
+++ b/src/address.rs
@@ -1,4 +1,5 @@
//! Provides functions to parse input IP addresses, CIDRs or files.
+use std::collections::BTreeSet;
use std::fs::{self, File};
use std::io::{prelude::*, BufReader};
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
diff --git a/src/address.rs b/src/address.rs
--- a/src/address.rs
+++ b/src/address.rs
@@ -27,6 +28,8 @@ use crate::warning;
///
/// let ips = parse_addresses(&opts);
/// ```
+///
+/// Finally, any duplicates are removed to avoid excessive scans.
pub fn parse_addresses(input: &Opts) -> Vec<IpAddr> {
let mut ips: Vec<IpAddr> = Vec::new();
let mut unresolved_addresses: Vec<&str> = Vec::new();
diff --git a/src/address.rs b/src/address.rs
--- a/src/address.rs
+++ b/src/address.rs
@@ -66,7 +69,10 @@ pub fn parse_addresses(input: &Opts) -> Vec<IpAddr> {
}
}
- ips
+ ips.into_iter()
+ .collect::<BTreeSet<_>>()
+ .into_iter()
+ .collect()
}
/// Given a string, parse it as a host, IP address, or CIDR.
|
diff --git a/src/address.rs b/src/address.rs
--- a/src/address.rs
+++ b/src/address.rs
@@ -256,6 +262,16 @@ mod tests {
assert_eq!(ips.len(), 0);
}
+ #[test]
+ fn parse_duplicate_cidrs() {
+ let mut opts = Opts::default();
+ opts.addresses = vec!["79.98.104.0/21".to_owned(), "79.98.104.0/24".to_owned()];
+
+ let ips = parse_addresses(&opts);
+
+ assert_eq!(ips.len(), 2_048);
+ }
+
#[test]
fn resolver_default_cloudflare() {
let opts = Opts::default();
|
Dublication of ports in output
rustscan.exe -a tmp/asns_prefixes_specific.txt -p 80,443,8443,8080,8006 --scripts none
<img width="365" alt="Screenshot_2" src="https://github.com/user-attachments/assets/ef874b42-60b5-4260-bc67-dd7abe6dbfce">
tmp/asns_prefixes_specific.txt
`185.52.205.0/24
79.98.109.0/24
185.239.124.0/24
185.52.204.0/22
185.228.27.0/24
185.239.127.0/24
79.98.111.0/24
185.52.207.0/24
79.98.110.0/24
79.98.108.0/24
195.189.81.0/24
185.52.206.0/24
194.145.63.0/24
185.228.26.0/24
185.52.204.0/24
185.228.25.0/24
79.98.105.0/24
185.55.228.0/24
79.98.104.0/21
5.182.21.0/24
79.98.107.0/24
185.228.24.0/24
185.55.231.0/24
185.55.228.0/22
195.189.83.0/24
185.55.229.0/24
185.199.38.0/24
185.55.230.0/24
185.199.37.0/24
45.67.19.0/24
185.166.238.0/24
89.187.83.0/24
5.182.20.0/24
79.98.106.0/24
185.228.24.0/22
195.189.80.0/24
185.239.126.0/24
195.189.80.0/22
185.133.72.0/24
195.189.82.0/24
79.98.104.0/24
`
|
I suspect that when we got
79.98.104.0/21
79.98.104.0/24
dublication comes from this
|
2024-09-19T00:46:28Z
|
2.3
|
2024-09-21T18:08:33Z
|
c3d24feebef4c605535a6661ddfeaa18b9bde60c
|
[
"address::tests::parse_duplicate_cidrs"
] |
[
"input::tests::opts_merge_optional_arguments",
"input::tests::opts_merge_required_arguments",
"input::tests::opts_no_merge_when_config_is_ignored",
"address::tests::parse_correct_addresses",
"address::tests::parse_naughty_host_file",
"address::tests::parse_empty_hosts_file",
"input::tests::parse_trailing_command::case_0",
"input::tests::parse_trailing_command::case_1",
"input::tests::parse_trailing_command::case_3",
"input::tests::parse_trailing_command::case_2",
"input::tests::verify_cli",
"port_strategy::tests::serial_strategy_with_ports",
"port_strategy::tests::random_strategy_with_ports",
"port_strategy::tests::serial_strategy_with_range",
"port_strategy::tests::random_strategy_with_range",
"scanner::socket_iterator::tests::goes_through_every_ip_port_combination",
"input::tests::parse_trailing_command::case_4",
"address::tests::parse_correct_host_addresses",
"address::tests::parse_correct_and_incorrect_addresses",
"address::tests::resolver_default_cloudflare",
"address::tests::parse_hosts_file_and_incorrect_hosts",
"address::tests::parse_incorrect_addresses",
"port_strategy::range_iterator::tests::range_iterator_iterates_through_the_entire_range",
"scripts::tests::find_and_parse_scripts",
"scripts::tests::find_invalid_folder - should panic",
"scripts::tests::open_nonexisting_script_file - should panic",
"scripts::tests::open_script_file_invalid_call_format - should panic",
"scripts::tests::open_script_file_invalid_headers - should panic",
"scripts::tests::open_script_file_missing_call_format - should panic",
"scripts::tests::parse_txt_script",
"scripts::tests::run_bash_script",
"scripts::tests::run_perl_script",
"scripts::tests::run_python_script",
"address::tests::resolver_args_google_dns",
"benchmark::benchmark",
"scanner::tests::ipv6_scanner_runs",
"scanner::tests::scanner_runs",
"scanner::tests::quad_zero_scanner_runs",
"scanner::tests::udp_scan_runs",
"scanner::tests::udp_ipv6_runs",
"scanner::tests::udp_quad_zero_scanner_runs",
"scanner::tests::google_dns_runs",
"scanner::tests::udp_google_dns_runs",
"scanner::tests::infer_ulimit_lowering_no_panic",
"tests::batch_size_adjusted_2000",
"tests::batch_size_equals_ulimit_lowered",
"tests::test_high_ulimit_no_greppable_mode",
"tests::batch_size_lowered",
"tests::batch_size_lowered_average_size",
"tests::test_print_opening_no_panic",
"src/scanner/mod.rs - scanner::Scanner::connect (line 206) - compile fail",
"src/scanner/mod.rs - scanner::Scanner::scan_socket (line 133) - compile fail",
"src/scanner/mod.rs - scanner::Scanner::udp_bind (line 229) - compile fail",
"src/scanner/mod.rs - scanner::Scanner::udp_scan (line 252) - compile fail",
"src/benchmark/mod.rs - benchmark (line 5)",
"src/lib.rs - (line 10)"
] |
[] |
[] |
RustScan/RustScan
| 518
|
RustScan__RustScan-518
|
[
"515"
] |
7dd9352baee3b467b4c55c95edf4de8494ca8a40
|
diff --git a/src/port_strategy/mod.rs b/src/port_strategy/mod.rs
--- a/src/port_strategy/mod.rs
+++ b/src/port_strategy/mod.rs
@@ -67,7 +67,7 @@ pub struct SerialRange {
impl RangeOrder for SerialRange {
fn generate(&self) -> Vec<u16> {
- (self.start..self.end).collect()
+ (self.start..=self.end).collect()
}
}
diff --git a/src/port_strategy/range_iterator.rs b/src/port_strategy/range_iterator.rs
--- a/src/port_strategy/range_iterator.rs
+++ b/src/port_strategy/range_iterator.rs
@@ -22,7 +22,7 @@ impl RangeIterator {
/// For example, the range `1000-2500` will be normalized to `0-1500`
/// before going through the algorithm.
pub fn new(start: u32, end: u32) -> Self {
- let normalized_end = end - start;
+ let normalized_end = end - start + 1;
let step = pick_random_coprime(normalized_end);
// Randomly choose a number within the range to be the first
|
diff --git a/src/port_strategy/mod.rs b/src/port_strategy/mod.rs
--- a/src/port_strategy/mod.rs
+++ b/src/port_strategy/mod.rs
@@ -104,7 +104,7 @@ mod tests {
let range = PortRange { start: 1, end: 100 };
let strategy = PortStrategy::pick(&Some(range), None, ScanOrder::Serial);
let result = strategy.order();
- let expected_range = (1..100).into_iter().collect::<Vec<u16>>();
+ let expected_range = (1..=100).into_iter().collect::<Vec<u16>>();
assert_eq!(expected_range, result);
}
#[test]
diff --git a/src/port_strategy/mod.rs b/src/port_strategy/mod.rs
--- a/src/port_strategy/mod.rs
+++ b/src/port_strategy/mod.rs
@@ -112,7 +112,7 @@ mod tests {
let range = PortRange { start: 1, end: 100 };
let strategy = PortStrategy::pick(&Some(range), None, ScanOrder::Random);
let mut result = strategy.order();
- let expected_range = (1..100).into_iter().collect::<Vec<u16>>();
+ let expected_range = (1..=100).into_iter().collect::<Vec<u16>>();
assert_ne!(expected_range, result);
result.sort_unstable();
diff --git a/src/port_strategy/range_iterator.rs b/src/port_strategy/range_iterator.rs
--- a/src/port_strategy/range_iterator.rs
+++ b/src/port_strategy/range_iterator.rs
@@ -103,23 +103,23 @@ mod tests {
#[test]
fn range_iterator_iterates_through_the_entire_range() {
let result = generate_sorted_range(1, 10);
- let expected_range = (1..10).into_iter().collect::<Vec<u16>>();
+ let expected_range = (1..=10).into_iter().collect::<Vec<u16>>();
assert_eq!(expected_range, result);
let result = generate_sorted_range(1, 100);
- let expected_range = (1..100).into_iter().collect::<Vec<u16>>();
+ let expected_range = (1..=100).into_iter().collect::<Vec<u16>>();
assert_eq!(expected_range, result);
let result = generate_sorted_range(1, 1000);
- let expected_range = (1..1000).into_iter().collect::<Vec<u16>>();
+ let expected_range = (1..=1000).into_iter().collect::<Vec<u16>>();
assert_eq!(expected_range, result);
let result = generate_sorted_range(1, 65_535);
- let expected_range = (1..65_535).into_iter().collect::<Vec<u16>>();
+ let expected_range = (1..=65_535).into_iter().collect::<Vec<u16>>();
assert_eq!(expected_range, result);
let result = generate_sorted_range(1000, 2000);
- let expected_range = (1000..2000).into_iter().collect::<Vec<u16>>();
+ let expected_range = (1000..=2000).into_iter().collect::<Vec<u16>>();
assert_eq!(expected_range, result);
}
|
--range <start-end>, only contain start, But not end port
In nmap run:**nmap 192.168.1.2 -p 1-65535** ,nmap scan port range is 1-65535.
But in RustScan run:**rustscan 192.168.1.2 --range 1-65535** (or directly execute **rustscan 192.168.1.2**) by wireshark verification, the scan range is 1-65534, does not contain 65535.
The same in nmap exec: **nmap 192.168.1.2 -p 1-5**, nmap scan range is 1-5.
But in the RustScan exec: **rustscan 192.168.1.2 --range 1-5**, rustscan scan range is 1-4.
Please fix this bug. Services open on 65535 may be missed when execute full port scan.
|
2023-05-26T04:18:08Z
|
2.1
|
2024-04-07T07:10:45Z
|
2ab7191a659e4e431098d530b6376c753b8616dd
|
[
"port_strategy::tests::serial_strategy_with_range",
"port_strategy::tests::random_strategy_with_range",
"port_strategy::range_iterator::tests::range_iterator_iterates_through_the_entire_range"
] |
[
"input::tests::opts_merge_optional_arguments",
"input::tests::opts_no_merge_when_config_is_ignored",
"input::tests::opts_merge_required_arguments",
"port_strategy::tests::serial_strategy_with_ports",
"port_strategy::tests::random_strategy_with_ports",
"scanner::socket_iterator::tests::goes_through_every_ip_port_combination",
"scripts::tests::find_invalid_folder - should panic",
"scripts::tests::open_nonexisting_script_file - should panic",
"scripts::tests::open_script_file_invalid_headers - should panic",
"scripts::tests::open_script_file_missing_call_format - should panic",
"scripts::tests::parse_txt_script",
"scripts::tests::open_script_file_invalid_call_format - should panic",
"scripts::tests::find_and_parse_scripts",
"tests::batch_size_equals_ulimit_lowered",
"tests::batch_size_adjusted_2000",
"tests::batch_size_lowered_average_size",
"tests::batch_size_lowered",
"scripts::tests::run_bash_script",
"scripts::tests::run_perl_script",
"tests::parse_correct_addresses",
"tests::parse_empty_hosts_file",
"tests::parse_correct_host_addresses",
"tests::parse_naughty_host_file",
"tests::test_high_ulimit_no_greppable_mode",
"tests::parse_correct_and_incorrect_addresses",
"tests::test_print_opening_no_panic",
"scripts::tests::run_python_script",
"scanner::tests::ipv6_scanner_runs",
"scanner::tests::quad_zero_scanner_runs",
"scanner::tests::scanner_runs",
"benchmark::benchmark",
"scanner::tests::google_dns_runs",
"scanner::tests::infer_ulimit_lowering_no_panic",
"tests::parse_incorrect_addresses",
"tests::parse_hosts_file_and_incorrect_hosts"
] |
[] |
[] |
|
sqlpage/SQLPage
| 544
|
sqlpage__SQLPage-544
|
[
"529"
] |
471158f8722a01e7ee848d818e357f6b8ff00273
|
diff --git /dev/null b/examples/handle-404/api/404.sql
new file mode 100644
--- /dev/null
+++ b/examples/handle-404/api/404.sql
@@ -0,0 +1,9 @@
+SELECT 'debug' AS component,
+ 'api/404.sql' AS serving_file,
+ sqlpage.path() AS request_path;
+
+SELECT 'button' AS component;
+SELECT
+ 'Back home' AS title,
+ 'home' AS icon,
+ '/' AS link;
diff --git /dev/null b/examples/handle-404/api/index.sql
new file mode 100644
--- /dev/null
+++ b/examples/handle-404/api/index.sql
@@ -0,0 +1,9 @@
+SELECT
+ 'title' AS component,
+ 'Welcome to the API' AS contents;
+
+SELECT 'button' AS component;
+SELECT
+ 'Back home' AS title,
+ 'home' AS icon,
+ '/' AS link;
diff --git /dev/null b/examples/handle-404/index.sql
new file mode 100644
--- /dev/null
+++ b/examples/handle-404/index.sql
@@ -0,0 +1,42 @@
+SELECT 'list' AS component,
+ 'Navigation' AS title;
+
+SELECT
+ column1 AS title, column2 AS link, column3 AS description_md
+FROM (VALUES
+ ('Link to arbitrary path', '/api/does/not/actually/exist', 'Covered by `api/404.sql`'),
+ ('Link to arbitrary file', '/api/nothing.png', 'Covered by `api/404.sql`'),
+ ('Link to non-existing .sql file', '/api/inexistent.sql', 'Covered by `api/404.sql`'),
+ ('Link to 404 handler', '/api/404.sql', 'Actually `api/404.sql`'),
+ ('Link to API landing page', '/api', 'Covered by `api/index.sql`'),
+ ('Link to arbitrary broken path', '/backend/does/not/actually/exist', 'Not covered by anything, will yield a 404 error')
+);
+
+SELECT 'text' AS component,
+ '
+# Overview
+
+This demo shows how a `404.sql` file can serve as a fallback error handler. Whenever a `404 Not
+Found` error would be emitted, instead a dedicated `404.sql` is called (if it exists) to serve the
+request. This is usefull in two scenarios:
+
+1. Providing custom 404 error pages.
+2. To provide content under dynamic paths.
+
+The former use-case is primarily of cosmetic nature, it allows for more informative, customized
+failure modes, enabling better UX. The latter use-case opens the door especially for REST API
+design, where dynamic paths are often used to convey arguments, i.e. `/api/resource/5` where `5` is
+the id of a resource.
+
+
+# Fallback Handler Selection
+
+When a normal request to either a `.sql` or a static file fails with `404`, the `404` error is
+intercepted. The reuquest path''s target directory is scanned for a `404.sql`. If it exists, it is
+called. Otherwise, the parent directory is scanned for `404.sql`, which will be called if it exists.
+This search traverses up until it reaches the `web_root`. If even the webroot does not contain a
+`404.sql`, then the original `404` error is served as response to the HTTP client.
+
+The fallback handler is not recursive; i.e. if anything causes another `404` during the call to a
+`404.sql`, then the request fails (emitting a `404` response to the HTTP client).
+ ' AS contents_md;
diff --git a/src/webserver/http.rs b/src/webserver/http.rs
--- a/src/webserver/http.rs
+++ b/src/webserver/http.rs
@@ -374,9 +374,9 @@ fn path_to_sql_file(path: &str) -> Option<PathBuf> {
}
async fn process_sql_request(
- mut req: ServiceRequest,
+ req: &mut ServiceRequest,
sql_path: PathBuf,
-) -> actix_web::Result<ServiceResponse> {
+) -> actix_web::Result<HttpResponse> {
let app_state: &web::Data<AppState> = req.app_data().expect("app_state");
let sql_file = app_state
.sql_file_cache
diff --git a/src/webserver/http.rs b/src/webserver/http.rs
--- a/src/webserver/http.rs
+++ b/src/webserver/http.rs
@@ -384,8 +384,7 @@ async fn process_sql_request(
.await
.with_context(|| format!("Unable to get SQL file {sql_path:?}"))
.map_err(anyhow_err_to_actix)?;
- let response = render_sql(&mut req, sql_file).await?;
- Ok(req.into_response(response))
+ render_sql(req, sql_file).await
}
fn anyhow_err_to_actix(e: anyhow::Error) -> actix_web::Error {
diff --git a/src/webserver/http.rs b/src/webserver/http.rs
--- a/src/webserver/http.rs
+++ b/src/webserver/http.rs
@@ -434,25 +433,100 @@ async fn serve_file(
})
}
+/// Fallback handler for when a file could not be served
+///
+/// Recursively traverses upwards in the request's path, looking for a `404.sql` to call as the
+/// fallback handler. Fails if none is found, or if there is an issue while running the `404.sql`.
+async fn serve_fallback(
+ service_request: &mut ServiceRequest,
+ original_err: actix_web::Error,
+) -> actix_web::Result<HttpResponse> {
+ let catch_all = "404.sql";
+
+ let req_path = req_path(&service_request);
+ let mut fallback_path_candidate = req_path.clone().into_owned();
+ log::debug!("Trying to find a {catch_all:?} handler for {fallback_path_candidate:?}");
+
+ let app_state: &web::Data<AppState> = service_request.app_data().expect("app_state");
+
+ // Find the indeces of each char which follows a directroy separator (`/`). Also consider the 0
+ // index, as we also have to try to check the empty path, for a root dir `404.sql`.
+ for idx in req_path
+ .rmatch_indices('/')
+ .map(|(idx, _)| idx + 1)
+ .chain(std::iter::once(0))
+ {
+ // Remove the trailing substring behind the current `/`, and append `404.sql`.
+ fallback_path_candidate.truncate(idx);
+ fallback_path_candidate.push_str(&catch_all);
+
+ // Check if `maybe_fallback_path` actually exists, if not, skip to the next round (which
+ // will check `maybe_fallback_path`s parent directory for fallback handler).
+ let mabye_sql_path = PathBuf::from(&fallback_path_candidate);
+ match app_state
+ .sql_file_cache
+ .get_with_privilege(app_state, &mabye_sql_path, false)
+ .await
+ {
+ // `maybe_fallback_path` does seem to exist, lets try to run it!
+ Ok(sql_file) => {
+ log::debug!("Processing SQL request via fallback: {:?}", mabye_sql_path);
+ return render_sql(service_request, sql_file).await;
+ }
+ Err(e) => {
+ let actix_web_err = anyhow_err_to_actix(e);
+
+ // `maybe_fallback_path` does not exist, continue search in parent dir.
+ if actix_web_err.as_response_error().status_code() == StatusCode::NOT_FOUND {
+ log::trace!("The 404 handler {mabye_sql_path:?} does not exist");
+ continue;
+ }
+
+ // Another error occured, bubble it up!
+ return Err(actix_web_err);
+ }
+ }
+ }
+
+ log::debug!("There is no {catch_all:?} handler, this response is terminally failed");
+ Err(original_err)
+}
+
pub async fn main_handler(
mut service_request: ServiceRequest,
) -> actix_web::Result<ServiceResponse> {
let path = req_path(&service_request);
let sql_file_path = path_to_sql_file(&path);
- if let Some(sql_path) = sql_file_path {
+ let maybe_response = if let Some(sql_path) = sql_file_path {
if let Some(redirect) = redirect_missing_trailing_slash(service_request.uri()) {
- return Ok(service_request.into_response(redirect));
+ Ok(redirect)
+ } else {
+ log::debug!("Processing SQL request: {:?}", sql_path);
+ process_sql_request(&mut service_request, sql_path).await
}
- log::debug!("Processing SQL request: {:?}", sql_path);
- process_sql_request(service_request, sql_path).await
} else {
log::debug!("Serving file: {:?}", path);
let app_state = service_request.extract::<web::Data<AppState>>().await?;
let path = req_path(&service_request);
let if_modified_since = IfModifiedSince::parse(&service_request).ok();
- let response = serve_file(&path, &app_state, if_modified_since).await?;
- Ok(service_request.into_response(response))
- }
+
+ serve_file(&path, &app_state, if_modified_since).await
+ };
+
+ // On 404/NOT_FOUND error, fall back to `404.sql` handler if it exists
+ let response = match maybe_response {
+ // File could not be served due to a 404 error. Try to find a user provide 404 handler in
+ // the form of a `404.sql` in the current directory. If there is none, look in the parent
+ // directeory, and its parent directory, ...
+ Err(e) if e.as_response_error().status_code() == StatusCode::NOT_FOUND => {
+ serve_fallback(&mut service_request, e).await?
+ }
+
+ // Either a valid response, or an unrelated error that shall be bubbled up.
+ e => e?,
+ };
+
+ Ok(service_request.into_response(response))
}
/// Extracts the path from a request and percent-decodes it
|
diff --git /dev/null b/tests/404.sql
new file mode 100644
--- /dev/null
+++ b/tests/404.sql
@@ -0,0 +1,3 @@
+SELECT 'alert' AS component,
+ 'We almost got an oopsie' AS title,
+ 'But the `404.sql` file saved the day!' AS description_md;
diff --git a/tests/index.rs b/tests/index.rs
--- a/tests/index.rs
+++ b/tests/index.rs
@@ -51,6 +51,28 @@ async fn test_404() {
}
}
+#[actix_web::test]
+async fn test_404_fallback() {
+ for f in [
+ "/tests/does_not_exist.sql",
+ "/tests/does_not_exist.html",
+ "/tests/does_not_exist/",
+ ] {
+ let resp_result = req_path(f).await;
+ let resp = resp_result.unwrap();
+ assert_eq!(resp.status(), http::StatusCode::OK, "{f} isnt 200");
+
+ let body = test::read_body(resp).await;
+ assert!(body.starts_with(b"<!DOCTYPE html>"));
+ // the body should contain our happy string, but not the string "error"
+ let body = String::from_utf8(body.to_vec()).unwrap();
+ assert!(body.contains("But the "));
+ assert!(body.contains("404.sql"));
+ assert!(body.contains("file saved the day!"));
+ assert!(!body.contains("error"));
+ }
+}
+
#[actix_web::test]
async fn test_concurrent_requests() {
// send 32 requests (less than the default postgres pool size)
|
allow catch all `.sql` files for custom routing
What are you building with SQLPage ?
I'd like to build a [pixiecore api](https://github.com/danderson/netboot/blob/main/pixiecore/README.api.md#api-specification) server based on SQL Page.
What is your problem ? A description of the problem, not the solution you are proposing.
The server has to answer requests to the following path: `<apiserver-prefix>/v1/boot/<mac-addr>`.
The last part of the path is the actual argument to the API call. To the best of my knowledge, there is no way in SQLpage to have a one or multiple arbitrary paths served by a single `.sql` file. There is of course `index.sql`, but that maps one path to one `.sql` file.
What are you currently doing ? Since your solution is not implemented in SQLPage currently, what are you doing instead ?
Introducing a map in the configuration, mapping URL paths to `.sql` files. When the current URL path starts with the key of an entry from that map, use the corresponding value from the map as path to a `.sql` file and execute it. Otherwise, carry on as usual.
**Describe alternatives you've considered**
Having a special name, e.g. if in a directory there is a `_catch_all.sql` then only that is considered for any URL whose path goes into this directory.
|
Hi !
That would indeed be a nice feature, and has been asked before (in various forms).
Until this is implemented, the best way to make this work is to [use a reverse proxy](https://sql.ophir.dev/your-first-sql-website/nginx.sql) like nginx:
```nginx
server {
listen 80;
server_name yourdomain.com;
location /v1/boot/ {
# Extract the MAC address from the URL
rewrite ^/v1/boot/(.*)$ /v1/boot-handler.sql?mac=$1 break;
# Proxy the request to the SQLPage server
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
}
location / {
# Default location for other SQLPage files
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
}
}
```
Hi @lovasoa, thank you for the quick response! Yes, a reverse proxy fixes this. But the sweetness of just `cd my-page-dir && sqlpage` is too good. I'd much prefer not involving a nginx simply to test the setup. Your comment of course still might help others.
Is there any chance that you have a preferred mechanism for this? I might find time to hack together a MVP POC, but I'd much prefer to spent only effort on upstream agreeable approaches.
The way I would have done it is with a `404.sql` file that you can place in a folder.
When SQLPage is about to return a 404, it recursively checks for 404.sql pages in directories and returns the default 404 only if it finds nothing.
A pull request is more than welcome :) Make sure to also update `configuration.md` to document the behavior.
That is a sweet idea, but feels a little like a hack. What I dislike in particular is that this interfers with he namespace of normal URLs. Of course, that is a nitpick.
To brainstorm another idea: what if we detect that a subset (beginning at the start) of the path from the URL matches a file path. So if the URL is:
`http://localhost/path/to/my/api`
And there is a file `path/to/my` then this file is called. We can not have a file and a directory with the same name anyhow. That file then gets called with `$url_full_path` and maybe `$url_trailing_path` already set. We should of course only match when the matching sub path is at a `/` boundary, so
`http://localhost/path/to/my-nice-shoes` must not match.
Would you serve the website's `index.sql` when someone tries to access a non-existing file ? I fear this approach would lead to serving files when a proper 404 would be expected.
I understand your concerns about the 404.sql in the web root... What about a single 404.sql in the sqlpage configuration directory ? Pages always have access to the current page through [`sqlpage.path()`](https://sql.ophir.dev/functions.sql?function=path#function) anyway. This would avoid leaving access to the 404 handler to end users, but would require developer to manually handle the multiple cases if their app needs this kind of routing in multiple places...
> Would you serve the website's index.sql when someone tries to access a non-existing file ? I fear this approach would lead to serving files when a proper 404 would be expected.
Can you describe a particular example? I can not imagine a scenario where there would be a choice to either use index.sql or the path thing
Maybe I misunderstood you, but I thought you were suggesting to interpret `$SQLPAGE_ROOT/path/to/my/index.sql` when the user loads `http://localhost/path/to/my/api`. I think that would be a surprising behavior. Maybe you meant instead `$SQLPAGE_ROOT/path/to/my` and the user would have to create a file without extension, but that actually contains SQL code ? or `$SQLPAGE_ROOT/path/to/my.sql` ?
> Maybe you meant instead $SQLPAGE_ROOT/path/to/my and the user would have to create a file without extension, but that actually contains SQL code ?
This is what I meant. Personally I would likely use that combined with a symlink, but it should work just like you described, no symlinks.
I'm not a fan of that. Having files without extensions would be confusing and would prevent syntax highlighting to work in editors. Creating a symlink every time would be cumbersome and defeat the initial purpose of hiding the handler... I still like my initial idea of a 404.sql in the folder where you want to handle 404s more. It kind of feels natural and easy for beginners.
do I correctly infer the 404 handler needs to be put here: https://github.com/lovasoa/SQLpage/blob/d35c493ddf57a7922a318fda067c16e51d07c6e6/src/webserver/http.rs#L438-L453 ?
yes!
|
2024-08-19T06:28:51Z
|
0.27
|
2024-08-22T19:30:48Z
|
471158f8722a01e7ee848d818e357f6b8ff00273
|
[
"test_404_fallback"
] |
[
"app_config::test::test_encode_uri",
"app_config::test_normalize_site_prefix",
"app_config::test::test_normalize_site_prefix",
"app_config::test::test_default_site_prefix",
"dynamic_component::tests::test_dynamic_properties_to_vec",
"dynamic_component::tests::test_parse_dynamic_array_json_strings",
"dynamic_component::tests::test_dynamic_properties_to_result_vec",
"dynamic_component::tests::test_parse_dynamic_rows",
"template_helpers::test_rfc2822_date",
"webserver::database::error_highlighting::test_quote_source_with_highlight",
"webserver::database::sql::test::is_own_placeholder",
"webserver::database::csv_import::test_make_statement",
"templates::test_split_template",
"webserver::database::sql::test::test_extract_set_variable",
"webserver::database::sql::test::test_mssql_statement_rewrite",
"webserver::database::sql::test::test_set_variable",
"webserver::database::sql::test::test_simple_select_only_extraction",
"webserver::database::sql::test::test_extract_toplevel_delayed_functions",
"webserver::database::sql::test::test_extract_toplevel_delayed_functions_parameter_order",
"webserver::database::sql::test::test_simple_select_with_sqlpage_pseudofunction",
"webserver::database::sqlpage_functions::functions::test_random_string",
"webserver::database::sql::test::test_statement_rewrite_sqlite",
"webserver::database::sql::test::test_static_extract",
"webserver::database::sql::test::test_statement_rewrite",
"webserver::database::sql::test::test_sqlpage_function_with_argument",
"webserver::database::sqlpage_functions::url_parameter_deserializer::test_url_parameters_deserializer",
"webserver::database::sql_to_json::test_row_to_json",
"webserver::database::sql::test::test_static_extract_doesnt_match",
"webserver::database::csv_import::test_end_to_end",
"webserver::http_request_info::test::test_extract_urlencoded_request",
"webserver::http_request_info::test::test_extract_multipart_form_data",
"filesystem::test_sql_file_read_utf8",
"render::tests::test_split_template_render",
"render::tests::test_delayed",
"webserver::http_request_info::test::test_extract_empty_request",
"webserver::database::sqlpage_functions::functions::test_hash_password",
"privileged_paths_are_not_accessible",
"test_access_config_forbidden",
"test_file_upload_too_large",
"test_blank_file_upload_field",
"test_file_upload_through_runsql",
"test_csv_upload",
"test_file_upload_direct",
"test_index_ok",
"test_official_website_basic_auth_example",
"test_static_files",
"test_uploaded_file_name",
"test_overwrite_variable",
"test_upload_file_data_url",
"test_official_website_documentation",
"test_with_site_prefix",
"test_404",
"test_files",
"test_concurrent_requests"
] |
[] |
[] |
sqlpage/SQLPage
| 370
|
sqlpage__SQLPage-370
|
[
"333"
] |
8add49dc524d94c2c72571f7917bcc28a38671ef
|
diff --git a/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql b/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql
--- a/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql
+++ b/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql
@@ -105,6 +105,54 @@ select ''redirect'' as component,
where sqlpage.uploaded_file_mime_type(''myfile'') not in (select mime_type from allowed_mime_types);
```
'
+),
+(
+ 'uploaded_file_name',
+ '0.23.0',
+ 'file-description',
+ 'Returns the `filename` value in the `content-disposition` header.
+
+## Example: saving uploaded file metadata for later download
+
+### Making a form
+
+```sql
+select ''form'' as component, ''handle_file_upload.sql'' as action;
+select ''myfile'' as name, ''file'' as type, ''File'' as label;
+```
+
+### Handling the form response
+
+### Inserting an arbitrary file as a [data URL](https://en.wikipedia.org/wiki/Data_URI_scheme) into the database
+
+In `handle_file_upload.sql`, one can process the form results like this:
+
+```sql
+insert into uploaded_files (fname, content, uploaded) values (
+ sqlpage.uploaded_file_name(''myfile''),
+ sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path(''myfile'')),
+ CURRENT_TIMESTAMP
+);
+```
+
+> *Note*: Data URLs are larger than the original file, so it is not recommended to use them for large files.
+
+### Downloading the uploaded files
+
+The file can be downloaded by clicking a link like this:
+```sql
+select ''button'' as component;
+select name as title, content as link from uploaded_files where name = $file_name limit 1;
+```
+
+> *Note*: because the file is ecoded as a data uri, the file is transferred to the client whether or not the link is clicked
+
+### Large files
+
+See the [`sqlpage.uploaded_file_path`](?function=uploaded_file_path#function) function.
+
+See the [`sqlpage.persist_uploaded_file`](?function=persist_uploaded_file#function) function.
+'
);
INSERT INTO sqlpage_function_parameters (
diff --git a/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql b/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql
--- a/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql
+++ b/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql
@@ -136,5 +184,12 @@ VALUES (
'name',
'Name of the file input field in the form.',
'TEXT'
+),
+(
+ 'uploaded_file_name',
+ 1,
+ 'name',
+ 'Name of the file input field in the form.',
+ 'TEXT'
)
;
diff --git a/src/webserver/database/sqlpage_functions/functions.rs b/src/webserver/database/sqlpage_functions/functions.rs
--- a/src/webserver/database/sqlpage_functions/functions.rs
+++ b/src/webserver/database/sqlpage_functions/functions.rs
@@ -31,6 +31,7 @@ super::function_definition_macro::sqlpage_functions! {
uploaded_file_mime_type((&RequestInfo), upload_name: Cow<str>);
uploaded_file_path((&RequestInfo), upload_name: Cow<str>);
+ uploaded_file_name((&RequestInfo), upload_name: Cow<str>);
url_encode(raw_text: Option<Cow<str>>);
variables((&RequestInfo), get_or_post: Option<Cow<str>>);
diff --git a/src/webserver/database/sqlpage_functions/functions.rs b/src/webserver/database/sqlpage_functions/functions.rs
--- a/src/webserver/database/sqlpage_functions/functions.rs
+++ b/src/webserver/database/sqlpage_functions/functions.rs
@@ -427,6 +428,18 @@ async fn uploaded_file_path<'a>(
Some(uploaded_file.file.path().to_string_lossy())
}
+async fn uploaded_file_name<'a>(
+ request: &'a RequestInfo,
+ upload_name: Cow<'a, str>,
+) -> Option<Cow<'a, str>> {
+ let fname = request
+ .uploaded_files
+ .get(&*upload_name)?
+ .file_name
+ .as_ref()?;
+ Some(Cow::Borrowed(fname.as_str()))
+}
+
/// escapes a string for use in a URL using percent encoding
/// for example, spaces are replaced with %20, '/' with %2F, etc.
/// This is useful for constructing URLs in SQL queries.
|
diff --git a/tests/index.rs b/tests/index.rs
--- a/tests/index.rs
+++ b/tests/index.rs
@@ -284,6 +284,28 @@ async fn test_upload_file_data_url() -> actix_web::Result<()> {
Ok(())
}
+#[actix_web::test]
+async fn test_uploaded_file_name() -> actix_web::Result<()> {
+ let req = get_request_to("/tests/uploaded_file_name_test.sql")
+ .await?
+ .insert_header(("content-type", "multipart/form-data; boundary=1234567890"))
+ .set_payload(
+ "--1234567890\r\n\
+ Content-Disposition: form-data; name=\"my_file\"; filename=\"testfile.txt\"\r\n\
+ Content-Type: text/plain\r\n\
+ \r\n\
+ Some plain text.\r\n\
+ --1234567890--\r\n",
+ )
+ .to_srv_request();
+ let resp = main_handler(req).await?;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = test::read_body(resp).await;
+ let body_str = String::from_utf8(body.to_vec()).unwrap();
+ assert_eq!(body_str, "testfile.txt");
+ Ok(())
+}
+
#[actix_web::test]
async fn test_csv_upload() -> actix_web::Result<()> {
let req = get_request_to("/tests/upload_csv_test.sql")
diff --git /dev/null b/tests/uploaded_file_name_test.sql
new file mode 100644
--- /dev/null
+++ b/tests/uploaded_file_name_test.sql
@@ -0,0 +1,3 @@
+-- display the file name of the uploaded file, unencoded, and nothing else
+select 'shell-empty' as component,
+ sqlpage.uploaded_file_name('my_file') as html;
|
Preserve file name on file upload
**_What are you building with SQLPage ?_**
I have a suite of apps I use to help me transfer data between devices.
* It's not for sharing secrets, it's for convenience only. Not recommended to paste and private info...
ie, I can paste something from the clip board on my PC to the web form, and then scan the QR code on my phone.
OR, on a device without a camera, the codes are 5 base 32 digits (yes, I'm not worried about collisions) so it's easy to remember and type.
Here is the tools:
* https://shandan.one/clip - paste text to share
* https://shandan.one/goto - tiny URL
* https://shandan.one/upload - upload file to share
I formerly used python + bottle and rolled my own UI. This is fine.
I persisted clip/link/file to disk by naming it by it's base32 hash. Lots of small files. This is fine.
On finding out about SQLPage, I'm converting these so my website has a similar look and feel. Also want to get rid of the horrific python code I wrote.
It also make sense to store this stuff in db so it's easier to cleanup old data and apply size limits (had a bash script to do it, but ... yeah not comfortable with it).
**_What is your problem ? A description of the problem, not the solution you are proposing._**
The drawback with the SQLPage version is that I can not preserve the file name on upload.
My old UI, I was preserving the file name supplied by the browser:
```
-----------------------------4053620313313727090337127195
Content-Disposition: form-data; name="action"
Upload
-----------------------------4053620313313727090337127195
Content-Disposition: form-data; name="content"; filename="match.sh"
Content-Type: application/x-shellscript
#!/bin/bash
grep -ni 'import .*gnu' "$@"
-----------------------------4053620313313727090337127195--
```
The `Content-Disposition` header includes the filename (at least on Brave and Firefox).
_**What are you currently doing ? Since your solution is not implemented in SQLPage currently, what are you doing instead ?**_
There doesn't seem to be a way to get the filename out of the form data on SQLPage.
For now, I'm using the base32 code as the file name - at least this is not random and will be consistent on each download and also relates back to the code used to share the file.
_**Describe the solution you'd like**_
I'd like to preserve the file name on upload, so that when users download the file, the don't get a random or meaningless name.
A SQLPage function like [uploaded_file_mime_type](https://sql.ophir.dev/functions.sql?function=uploaded_file_mime_type#function) would be good. Maybe call it `uploaded_file_name`. Can return NULL if user-agent doesn't provide it.
|
Hi !
Indeed, I agree we should have an `uploaded_file_name` function. It shouldn't be hard to add in [`functions.rs`](https://github.com/lovasoa/SQLpage/blob/main/src/webserver/database/sqlpage_functions/functions.rs). Do you want to have a stab at implementing it, and opening a PR ?
The files are stored as [`TempFile`s](https://docs.rs/actix-multipart/latest/actix_multipart/form/tempfile/struct.TempFile.html) in the request object. Tempfile has a file_name attribute.
OK, I'll have a go. I think I should do some basic programs in rust first though - I feel I do everything oddly in rust because I have no idea what is available in terms of libraries etc...
Don't hesitate to open even a awkward pull request, I'll be there to help !
I think you don't need any library to implement this. The other file-related functions in functions.rs should give a good idea of how to do things.
@lovasoa I've started looking at this. I see there is also a file size attribute too which would also be handy to have access to. So I'm wondering if instead we should have a ``uploaded_file_attributes`` returning JSON:
```json
{
"name": "myfile.ext",
"size": 1234,
"content-type": "application/octet-stream",
"path": "/path/to/file"
}
```
If rather have separate functions, for performance and convenience
|
2024-06-03T06:53:51Z
|
0.22
|
2024-06-09T04:45:36Z
|
8add49dc524d94c2c72571f7917bcc28a38671ef
|
[
"test_uploaded_file_name"
] |
[
"app_config::test_normalize_site_prefix",
"dynamic_component::tests::test_dynamic_properties_to_vec",
"dynamic_component::tests::test_parse_dynamic_array_json_strings",
"dynamic_component::tests::test_dynamic_properties_to_result_vec",
"webserver::database::csv_import::test_make_statement",
"dynamic_component::tests::test_parse_dynamic_rows",
"webserver::database::sql::test::is_own_placeholder",
"template_helpers::test_rfc2822_date",
"webserver::database::sql::test::test_simple_select_only_extraction",
"webserver::database::sql::test::test_mssql_statement_rewrite",
"webserver::database::sql::test::test_statement_rewrite_sqlite",
"webserver::database::sql::test::test_sqlpage_function_with_argument",
"webserver::database::sql::test::test_set_variable",
"webserver::database::sql::test::test_simple_select_with_sqlpage_pseudofunction",
"templates::test_split_template",
"webserver::database::sql::test::test_statement_rewrite",
"webserver::database::sql::test::test_static_extract",
"webserver::database::sqlpage_functions::functions::test_random_string",
"webserver::database::sql::test::test_static_extract_doesnt_match",
"webserver::database::sql_to_json::test_row_to_json",
"webserver::database::csv_import::test_end_to_end",
"render::tests::test_delayed",
"webserver::http_request_info::test::test_extract_multipart_form_data",
"filesystem::test_sql_file_read_utf8",
"render::tests::test_split_template_render",
"webserver::http_request_info::test::test_extract_urlencoded_request",
"webserver::http_request_info::test::test_extract_empty_request",
"webserver::database::sqlpage_functions::functions::test_hash_password",
"test_file_upload_too_large",
"test_static_files",
"privileged_paths_are_not_accessible",
"test_access_config_forbidden",
"test_csv_upload",
"test_file_upload_direct",
"test_file_upload_through_runsql",
"test_overwrite_variable",
"test_index_ok",
"test_upload_file_data_url",
"test_with_site_prefix",
"test_404",
"test_files",
"test_concurrent_requests"
] |
[] |
[] |
sqlpage/SQLPage
| 253
|
sqlpage__SQLPage-253
|
[
"251"
] |
9abc9f8db00ee353c5c1310f31d56ba29c11ae4f
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,9 +2,15 @@
## 0.20.0 (unreleased)
+ - **file inclusion**. This is a long awaited feature that allows you to include the contents of one file in another. This is useful to factorize common parts of your website, such as the header, or the authentication logic. There is a new [`sqlpage.run_sql`](https://sql.ophir.dev/functions.sql?function=run_sql#function) function that runs a given SQL file and returns its result as a JSON array. Combined with the existing [`dynamic`](https://sql.ophir.dev/documentation.sql?component=dynamic#component) component, this allows you to include the content of a file in another, like this:
+ ```sql
+ select 'dynamic' as component, sqlpage.run_sql('header.sql') as properties;
+ ```
+ - **more powerful *dynamic* component**: the [`dynamic`](https://sql.ophir.dev/documentation.sql?component=dynamic#component) component can now be used to generate the special *header* components too, such as the `redirect`, `cookie`, `authentication`, `http_header` and `json` components. The *shell* component used to be allowed in dynamic components, but only if they were not nested (a dynamic component inside another one). This limitation is now lifted. This is particularly useful in combination with the new file inclusion feature, to factorize common parts of your website. There used to be a limited to how deeply nested dynamic components could be, but this limitation is now lifted too.
- Add an `id` attribute to form fields in the [form](https://sql.ophir.dev/documentation.sql?component=form#component) component. This allows you to easily reference form fields in custom javascript code.
- New [`rss`](https://sql.ophir.dev/documentation.sql?component=rss#component) component to create RSS feeds, including **podcast feeds**. You can now create and manage your podcast feed entirely in SQL, and distribute it to all podcast directories such as Apple Podcasts, Spotify, and Google Podcasts.
- Better error handling in template rendering. Many template helpers now display a more precise error message when they fail to execute. This makes it easier to debug errors when you [develop your own custom components](https://sql.ophir.dev/custom_components.sql).
+ - better error messages when an error occurs when defining a variable with `SET`. SQLPage now displays the query that caused the error, and the name of the variable that was being defined.
- Updated SQL parser to [v0.44](https://github.com/sqlparser-rs/sqlparser-rs/blob/main/CHANGELOG.md#0440-2024-03-02)
- support [EXECUTE ... USING](https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN) in PostgreSQL
- support `INSERT INTO ... SELECT ... RETURNING`, which allows you to insert data into a table, and easily pass values from the inserted row to a SQLPage component. [postgres docs](https://www.postgresql.org/docs/current/dml-returning.html), [mysql docs](https://mariadb.com/kb/en/insertreturning/), [sqlite docs](https://sqlite.org/lang_returning.html)
diff --git /dev/null b/examples/official-site/sqlpage/migrations/38_run_sql.sql
new file mode 100644
--- /dev/null
+++ b/examples/official-site/sqlpage/migrations/38_run_sql.sql
@@ -0,0 +1,48 @@
+INSERT INTO sqlpage_functions (
+ "name",
+ "introduced_in_version",
+ "icon",
+ "description_md"
+ )
+VALUES (
+ 'run_sql',
+ '0.20.0',
+ 'login',
+ 'Executes another SQL file and returns its result as a JSON array.
+
+### Example
+
+#### Include a common header in all your pages
+
+It is common to want to run the same SQL queries at the beginning of all your pages,
+to check if an user is logged in, render a header, etc.
+You can create a file called `common_header.sql`, and use the `dynamic` component with the `run_sql` function to include it in all your pages.
+
+```sql
+select ''dynamic'' as component, sqlpage.run_sql(''common_header.sql'') as properties;
+```
+
+#### Notes
+
+ - **recursion**: you can use `run_sql` to include a file that itself includes another file, and so on. However, be careful to avoid infinite loops. SQLPage will throw an error if the inclusion depth is superior to 8.
+ - **security**: be careful when using `run_sql` to include files. Never use `run_sql` with a user-provided parameter. Never run a file uploaded by a user, or a file that is not under your control.
+ - **variables**: the included file will have access to the same variables (URL parameters, POST variables, etc.)
+ as the calling file. It will not have access to uploaded files.
+ If the included file changes the value of a variable or creates a new variable, the change will not be visible in the calling file.
+'
+ );
+INSERT INTO sqlpage_function_parameters (
+ "function",
+ "index",
+ "name",
+ "description_md",
+ "type"
+ )
+VALUES (
+ 'run_sql',
+ 1,
+ 'file',
+ 'Path to the SQL file to execute, can be absolute, or relative to the web root (the root folder of your website sql files).
+ In-database files, from the sqlpage_files(path, contents, last_modified) table are supported.',
+ 'TEXT'
+ );
diff --git a/src/file_cache.rs b/src/file_cache.rs
--- a/src/file_cache.rs
+++ b/src/file_cache.rs
@@ -5,7 +5,7 @@ use anyhow::Context;
use async_trait::async_trait;
use chrono::{DateTime, TimeZone, Utc};
use std::collections::HashMap;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::sync::atomic::{
AtomicU64,
Ordering::{Acquire, Release},
diff --git a/src/file_cache.rs b/src/file_cache.rs
--- a/src/file_cache.rs
+++ b/src/file_cache.rs
@@ -97,7 +97,7 @@ impl<T: AsyncFromStrWithState> FileCache<T> {
/// Gets a file from the cache, or loads it from the file system if it's not there
/// This is a privileged operation; it should not be used for user-provided paths
- pub async fn get(&self, app_state: &AppState, path: &PathBuf) -> anyhow::Result<Arc<T>> {
+ pub async fn get(&self, app_state: &AppState, path: &Path) -> anyhow::Result<Arc<T>> {
self.get_with_privilege(app_state, path, true).await
}
diff --git a/src/file_cache.rs b/src/file_cache.rs
--- a/src/file_cache.rs
+++ b/src/file_cache.rs
@@ -107,7 +107,7 @@ impl<T: AsyncFromStrWithState> FileCache<T> {
pub async fn get_with_privilege(
&self,
app_state: &AppState,
- path: &PathBuf,
+ path: &Path,
privileged: bool,
) -> anyhow::Result<Arc<T>> {
log::trace!("Attempting to get from cache {:?}", path);
diff --git a/src/file_cache.rs b/src/file_cache.rs
--- a/src/file_cache.rs
+++ b/src/file_cache.rs
@@ -164,7 +164,7 @@ impl<T: AsyncFromStrWithState> FileCache<T> {
Ok(value) => {
let new_val = Arc::clone(&value.content);
log::trace!("Writing to cache {:?}", path);
- self.cache.write().await.insert(path.clone(), value);
+ self.cache.write().await.insert(PathBuf::from(path), value);
log::trace!("Done writing to cache {:?}", path);
log::trace!("{:?} loaded in cache", path);
Ok(new_val)
diff --git a/src/lib.rs b/src/lib.rs
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -4,6 +4,7 @@
extern crate core;
pub mod app_config;
+pub mod dynamic_component;
pub mod file_cache;
pub mod filesystem;
pub mod render;
diff --git a/src/render.rs b/src/render.rs
--- a/src/render.rs
+++ b/src/render.rs
@@ -274,15 +274,12 @@ pub struct RenderContext<W: std::io::Write> {
pub writer: W,
current_component: Option<SplitTemplateRenderer>,
shell_renderer: SplitTemplateRenderer,
- recursion_depth: usize,
current_statement: usize,
}
const DEFAULT_COMPONENT: &str = "table";
const PAGE_SHELL_COMPONENT: &str = "shell";
const FRAGMENT_SHELL_COMPONENT: &str = "shell-empty";
-const DYNAMIC_COMPONENT: &str = "dynamic";
-const MAX_RECURSION_DEPTH: usize = 256;
impl<W: std::io::Write> RenderContext<W> {
pub async fn new(
diff --git a/src/render.rs b/src/render.rs
--- a/src/render.rs
+++ b/src/render.rs
@@ -293,12 +290,7 @@ impl<W: std::io::Write> RenderContext<W> {
) -> anyhow::Result<RenderContext<W>> {
log::debug!("Creating the shell component for the page");
- let mut initial_rows =
- if get_object_str(&initial_row, "component") == Some(DYNAMIC_COMPONENT) {
- Self::extract_dynamic_properties(&initial_row)?
- } else {
- vec![Cow::Borrowed(&initial_row)]
- };
+ let mut initial_rows = vec![Cow::Borrowed(&initial_row)];
if !initial_rows
.first()
diff --git a/src/render.rs b/src/render.rs
--- a/src/render.rs
+++ b/src/render.rs
@@ -336,7 +328,6 @@ impl<W: std::io::Write> RenderContext<W> {
writer,
current_component: None,
shell_renderer,
- recursion_depth: 0,
current_statement: 1,
};
diff --git a/src/render.rs b/src/render.rs
--- a/src/render.rs
+++ b/src/render.rs
@@ -367,11 +358,6 @@ impl<W: std::io::Write> RenderContext<W> {
let new_component = get_object_str(data, "component");
let current_component = self.current_component().await?.name();
match (current_component, new_component) {
- (_current_component, Some(DYNAMIC_COMPONENT)) => {
- self.render_dynamic(data).await.with_context(|| {
- format!("Unable to render dynamic component with properties {data}")
- })?;
- }
(
_,
Some(
diff --git a/src/render.rs b/src/render.rs
--- a/src/render.rs
+++ b/src/render.rs
@@ -398,41 +384,6 @@ impl<W: std::io::Write> RenderContext<W> {
Ok(())
}
- fn extract_dynamic_properties(data: &Value) -> anyhow::Result<Vec<Cow<'_, JsonValue>>> {
- let properties_key = "properties";
- let properties_obj = data
- .get(properties_key)
- .with_context(|| format!("Missing '{properties_key}' key."))?;
- Ok(match properties_obj {
- Value::String(s) => match serde_json::from_str::<JsonValue>(s)
- .with_context(|| "parsing json properties")?
- {
- Value::Array(values) => values.into_iter().map(Cow::Owned).collect(),
- obj @ Value::Object(_) => vec![Cow::Owned(obj)],
- other => bail!(
- "Expected properties string to parse as array or object, got {other} instead."
- ),
- },
- obj @ Value::Object(_) => vec![Cow::Borrowed(obj)],
- Value::Array(values) => values.iter().map(Cow::Borrowed).collect(),
- other => bail!("Expected properties of type array or object, got {other} instead."),
- })
- }
-
- async fn render_dynamic(&mut self, data: &Value) -> anyhow::Result<()> {
- anyhow::ensure!(
- self.recursion_depth <= MAX_RECURSION_DEPTH,
- "Maximum recursion depth exceeded in the dynamic component."
- );
- for dynamic_row_obj in Self::extract_dynamic_properties(data)? {
- self.recursion_depth += 1;
- let res = self.handle_row(&dynamic_row_obj).await;
- self.recursion_depth -= 1;
- res?;
- }
- Ok(())
- }
-
#[allow(clippy::unused_async)]
pub async fn finish_query(&mut self) -> anyhow::Result<()> {
log::debug!("-> Query {} finished", self.current_statement);
diff --git a/src/webserver/database/execute_queries.rs b/src/webserver/database/execute_queries.rs
--- a/src/webserver/database/execute_queries.rs
+++ b/src/webserver/database/execute_queries.rs
@@ -1,23 +1,24 @@
-use anyhow::anyhow;
+use anyhow::{anyhow, Context};
use futures_util::stream::Stream;
use futures_util::StreamExt;
use std::borrow::Cow;
use std::collections::HashMap;
+use std::pin::Pin;
use super::csv_import::run_csv_import;
use super::sql::{ParsedSqlFile, ParsedStatement, StmtWithParams};
+use crate::dynamic_component::parse_dynamic_rows;
use crate::webserver::database::sql_pseudofunctions::extract_req_param;
use crate::webserver::database::sql_to_json::row_to_string;
use crate::webserver::http::SingleOrVec;
use crate::webserver::http_request_info::RequestInfo;
+use super::sql_pseudofunctions::StmtParam;
+use super::{highlight_sql_error, Database, DbItem};
use sqlx::any::{AnyArguments, AnyQueryResult, AnyRow, AnyStatement, AnyTypeInfo};
use sqlx::pool::PoolConnection;
use sqlx::{Any, AnyConnection, Arguments, Either, Executor, Statement};
-use super::sql_pseudofunctions::StmtParam;
-use super::{highlight_sql_error, Database, DbItem};
-
impl Database {
pub(crate) async fn prepare_with(
&self,
diff --git a/src/webserver/database/execute_queries.rs b/src/webserver/database/execute_queries.rs
--- a/src/webserver/database/execute_queries.rs
+++ b/src/webserver/database/execute_queries.rs
@@ -31,7 +32,6 @@ impl Database {
.map_err(|e| highlight_sql_error("Failed to prepare SQL statement", query, e))
}
}
-
pub fn stream_query_results<'a>(
db: &'a Database,
sql_file: &'a ParsedSqlFile,
diff --git a/src/webserver/database/execute_queries.rs b/src/webserver/database/execute_queries.rs
--- a/src/webserver/database/execute_queries.rs
+++ b/src/webserver/database/execute_queries.rs
@@ -53,28 +53,24 @@ pub fn stream_query_results<'a>(
let mut stream = connection.fetch_many(query);
while let Some(elem) = stream.next().await {
let is_err = elem.is_err();
- yield parse_single_sql_result(&stmt.query, elem);
+ for i in parse_dynamic_rows(parse_single_sql_result(&stmt.query, elem)) {
+ yield i;
+ }
if is_err {
break;
}
}
},
ParsedStatement::SetVariable { variable, value} => {
- let query = bind_parameters(value, request).await?;
- let connection = take_connection(db, &mut connection_opt).await?;
- log::debug!("Executing query to set the {variable:?} variable: {:?}", query.sql);
- let value: Option<String> = connection.fetch_optional(query).await?.as_ref().and_then(row_to_string);
- let (vars, name) = vars_and_name(request, variable)?;
- if let Some(value) = value {
- log::debug!("Setting variable {name} to {value:?}");
- vars.insert(name.clone(), SingleOrVec::Single(value));
- } else {
- log::debug!("Removing variable {name}");
- vars.remove(&name);
- }
+ execute_set_variable_query(db, &mut connection_opt, request, variable, value).await
+ .with_context(||
+ format!("Failed to set the {variable:?} variable to {value:?}")
+ )?;
},
ParsedStatement::StaticSimpleSelect(value) => {
- yield DbItem::Row(value.clone().into())
+ for i in parse_dynamic_rows(DbItem::Row(value.clone().into())) {
+ yield i;
+ }
}
ParsedStatement::Error(e) => yield DbItem::Error(clone_anyhow_err(e)),
}
diff --git a/src/webserver/database/execute_queries.rs b/src/webserver/database/execute_queries.rs
--- a/src/webserver/database/execute_queries.rs
+++ b/src/webserver/database/execute_queries.rs
@@ -83,6 +79,45 @@ pub fn stream_query_results<'a>(
.map(|res| res.unwrap_or_else(DbItem::Error))
}
+/// This function is used to create a pinned boxed stream of query results.
+/// This allows recursive calls.
+pub fn stream_query_results_boxed<'a>(
+ db: &'a Database,
+ sql_file: &'a ParsedSqlFile,
+ request: &'a mut RequestInfo,
+) -> Pin<Box<dyn Stream<Item = DbItem> + 'a>> {
+ Box::pin(stream_query_results(db, sql_file, request))
+}
+
+async fn execute_set_variable_query<'a>(
+ db: &'a Database,
+ connection_opt: &mut Option<PoolConnection<sqlx::Any>>,
+ request: &'a mut RequestInfo,
+ variable: &StmtParam,
+ statement: &StmtWithParams,
+) -> anyhow::Result<()> {
+ let query = bind_parameters(statement, request).await?;
+ let connection = take_connection(db, connection_opt).await?;
+ log::debug!(
+ "Executing query to set the {variable:?} variable: {:?}",
+ query.sql
+ );
+ let value: Option<String> = connection
+ .fetch_optional(query)
+ .await?
+ .as_ref()
+ .and_then(row_to_string);
+ let (vars, name) = vars_and_name(request, variable)?;
+ if let Some(value) = value {
+ log::debug!("Setting variable {name} to {value:?}");
+ vars.insert(name.clone(), SingleOrVec::Single(value));
+ } else {
+ log::debug!("Removing variable {name}");
+ vars.remove(&name);
+ }
+ Ok(())
+}
+
fn vars_and_name<'a>(
request: &'a mut RequestInfo,
variable: &StmtParam,
diff --git a/src/webserver/database/sql.rs b/src/webserver/database/sql.rs
--- a/src/webserver/database/sql.rs
+++ b/src/webserver/database/sql.rs
@@ -72,6 +72,7 @@ fn parse_sql<'a>(
dialect: &'a dyn Dialect,
sql: &'a str,
) -> anyhow::Result<impl Iterator<Item = ParsedStatement> + 'a> {
+ log::trace!("Parsing SQL: {sql}");
let tokens = Tokenizer::new(dialect, sql)
.tokenize_with_location()
.with_context(|| "SQLPage's SQL parser could not tokenize the sql file")?;
diff --git a/src/webserver/database/sql.rs b/src/webserver/database/sql.rs
--- a/src/webserver/database/sql.rs
+++ b/src/webserver/database/sql.rs
@@ -90,6 +91,7 @@ fn parse_single_statement(parser: &mut Parser<'_>, db_kind: AnyKind) -> Option<P
Ok(stmt) => stmt,
Err(err) => return Some(syntax_error(err, parser)),
};
+ log::debug!("Parsed statement: {stmt}");
while parser.consume_token(&SemiColon) {}
if let Some(static_statement) = extract_static_simple_select(&stmt) {
log::debug!("Optimised a static simple select to avoid a trivial database query: {stmt} optimized to {static_statement:?}");
diff --git a/src/webserver/database/sql.rs b/src/webserver/database/sql.rs
--- a/src/webserver/database/sql.rs
+++ b/src/webserver/database/sql.rs
@@ -106,8 +108,10 @@ fn parse_single_statement(parser: &mut Parser<'_>, db_kind: AnyKind) -> Option<P
if let Some(csv_import) = extract_csv_copy_statement(&mut stmt) {
return Some(ParsedStatement::CsvImport(csv_import));
}
+ let query = stmt.to_string();
+ log::debug!("Final transformed statement: {stmt}");
Some(ParsedStatement::StmtWithParams(StmtWithParams {
- query: stmt.to_string(),
+ query,
params,
}))
}
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -5,8 +5,14 @@ use actix_web_httpauth::headers::authorization::Basic;
use base64::Engine;
use mime_guess::{mime::APPLICATION_OCTET_STREAM, Mime};
use sqlparser::ast::FunctionArg;
+use tokio_stream::StreamExt;
-use crate::webserver::{http::SingleOrVec, http_request_info::RequestInfo, ErrorWithStatus};
+use crate::webserver::{
+ database::{execute_queries::stream_query_results_boxed, DbItem},
+ http::SingleOrVec,
+ http_request_info::RequestInfo,
+ ErrorWithStatus,
+};
use super::sql::{
extract_integer, extract_single_quoted_string, extract_single_quoted_string_optional,
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -38,6 +44,7 @@ pub(super) enum StmtParam {
UploadedFileMimeType(String),
ReadFileAsText(Box<StmtParam>),
ReadFileAsDataUrl(Box<StmtParam>),
+ RunSql(Box<StmtParam>),
Path,
Protocol,
}
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -107,6 +114,7 @@ pub(super) fn func_call_to_param(func_name: &str, arguments: &mut [FunctionArg])
"read_file_as_data_url" => StmtParam::ReadFileAsDataUrl(Box::new(
extract_variable_argument("read_file_as_data_url", arguments),
)),
+ "run_sql" => StmtParam::RunSql(Box::new(extract_variable_argument("run_sql", arguments))),
unknown_name => StmtParam::Error(format!(
"Unknown function {unknown_name}({})",
FormatArguments(arguments)
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -126,6 +134,7 @@ pub(super) async fn extract_req_param<'a>(
StmtParam::UrlEncode(inner) => url_encode(inner, request)?,
StmtParam::ReadFileAsText(inner) => read_file_as_text(inner, request).await?,
StmtParam::ReadFileAsDataUrl(inner) => read_file_as_data_url(inner, request).await?,
+ StmtParam::RunSql(inner) => run_sql(inner, request).await?,
_ => extract_req_param_non_nested(param, request)?,
})
}
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -248,6 +257,53 @@ async fn read_file_as_data_url<'a>(
Ok(Some(Cow::Owned(data_url)))
}
+async fn run_sql<'a>(
+ param0: &StmtParam,
+ request: &'a RequestInfo,
+) -> Result<Option<Cow<'a, str>>, anyhow::Error> {
+ use serde::ser::{SerializeSeq, Serializer};
+ let Some(sql_file_path) = extract_req_param_non_nested(param0, request)? else {
+ log::debug!("run_sql: first argument is NULL, returning NULL");
+ return Ok(None);
+ };
+ let sql_file = request
+ .app_state
+ .sql_file_cache
+ .get_with_privilege(
+ &request.app_state,
+ std::path::Path::new(sql_file_path.as_ref()),
+ true,
+ )
+ .await
+ .with_context(|| format!("run_sql: invalid path {sql_file_path:?}"))?;
+ let mut tmp_req = request.clone();
+ if tmp_req.clone_depth > 8 {
+ bail!("Too many nested inclusions. run_sql can include a file that includes another file, but the depth is limited to 8 levels. \n\
+ Executing sqlpage.run_sql('{sql_file_path}') would exceed this limit. \n\
+ This is to prevent infinite loops and stack overflows.\n\
+ Make sure that your SQL file does not try to run itself, directly or through a chain of other files.");
+ }
+ let mut results_stream =
+ stream_query_results_boxed(&request.app_state.db, &sql_file, &mut tmp_req);
+ let mut json_results_bytes = Vec::new();
+ let mut json_encoder = serde_json::Serializer::new(&mut json_results_bytes);
+ let mut seq = json_encoder.serialize_seq(None)?;
+ while let Some(db_item) = results_stream.next().await {
+ match db_item {
+ DbItem::Row(row) => {
+ log::debug!("run_sql: row: {:?}", row);
+ seq.serialize_element(&row)?;
+ }
+ DbItem::FinishedQuery => log::trace!("run_sql: Finished query"),
+ DbItem::Error(err) => {
+ return Err(err.context(format!("run_sql: unable to run {sql_file_path:?}")))
+ }
+ }
+ }
+ seq.end()?;
+ Ok(Some(Cow::Owned(String::from_utf8(json_results_bytes)?)))
+}
+
fn mime_from_upload<'a>(param0: &StmtParam, request: &'a RequestInfo) -> Option<&'a Mime> {
if let StmtParam::UploadedFilePath(name) | StmtParam::UploadedFileMimeType(name) = param0 {
request.uploaded_files.get(name)?.content_type.as_ref()
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -308,8 +364,9 @@ pub(super) fn extract_req_param_non_nested<'a>(
.map(|x| Cow::Borrowed(x.as_ref())),
StmtParam::ReadFileAsText(_) => bail!("Nested read_file_as_text() function not allowed",),
StmtParam::ReadFileAsDataUrl(_) => {
- bail!("Nested read_file_as_data_url() function not allowed",)
+ bail!("Nested read_file_as_data_url() function not allowed")
}
+ StmtParam::RunSql(_) => bail!("Nested run_sql() function not allowed"),
})
}
diff --git a/src/webserver/http.rs b/src/webserver/http.rs
--- a/src/webserver/http.rs
+++ b/src/webserver/http.rs
@@ -271,7 +271,7 @@ fn send_anyhow_error(
body.push_str("Contact the administrator for more information. A detailed error message has been logged.");
} else {
use std::fmt::Write;
- write!(body, "{e:#}").unwrap();
+ write!(body, "{e:?}").unwrap();
}
resp = resp.set_body(BoxBody::new(body));
resp.headers_mut().insert(
diff --git a/src/webserver/http.rs b/src/webserver/http.rs
--- a/src/webserver/http.rs
+++ b/src/webserver/http.rs
@@ -306,7 +306,7 @@ fn send_anyhow_error(
.unwrap_or_else(|_| log::error!("could not send headers"));
}
-#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq)]
+#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq, Clone)]
#[serde(untagged)]
pub enum SingleOrVec {
Single(String),
diff --git a/src/webserver/http_request_info.rs b/src/webserver/http_request_info.rs
--- a/src/webserver/http_request_info.rs
+++ b/src/webserver/http_request_info.rs
@@ -33,6 +33,26 @@ pub struct RequestInfo {
pub cookies: ParamMap,
pub basic_auth: Option<Basic>,
pub app_state: Arc<AppState>,
+ pub clone_depth: u8,
+}
+
+impl Clone for RequestInfo {
+ fn clone(&self) -> Self {
+ Self {
+ path: self.path.clone(),
+ protocol: self.protocol.clone(),
+ get_variables: self.get_variables.clone(),
+ post_variables: self.post_variables.clone(),
+ // uploaded_files is not cloned, as it contains file handles
+ uploaded_files: HashMap::new(),
+ headers: self.headers.clone(),
+ client_ip: self.client_ip,
+ cookies: self.cookies.clone(),
+ basic_auth: self.basic_auth.clone(),
+ app_state: self.app_state.clone(),
+ clone_depth: self.clone_depth + 1,
+ }
+ }
}
pub(crate) async fn extract_request_info(
diff --git a/src/webserver/http_request_info.rs b/src/webserver/http_request_info.rs
--- a/src/webserver/http_request_info.rs
+++ b/src/webserver/http_request_info.rs
@@ -76,6 +96,7 @@ pub(crate) async fn extract_request_info(
basic_auth,
app_state,
protocol,
+ clone_depth: 0,
}
}
|
diff --git /dev/null b/src/dynamic_component.rs
new file mode 100644
--- /dev/null
+++ b/src/dynamic_component.rs
@@ -0,0 +1,166 @@
+use anyhow::{self, Context as _};
+use serde_json::Value as JsonValue;
+
+use crate::webserver::database::DbItem;
+
+pub fn parse_dynamic_rows(row: DbItem) -> impl Iterator<Item = DbItem> {
+ DynamicComponentIterator {
+ stack: vec![],
+ db_item: Some(row),
+ }
+}
+
+struct DynamicComponentIterator {
+ stack: Vec<anyhow::Result<JsonValue>>,
+ db_item: Option<DbItem>,
+}
+
+impl Iterator for DynamicComponentIterator {
+ type Item = DbItem;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if let Some(db_item) = self.db_item.take() {
+ if let DbItem::Row(mut row) = db_item {
+ if let Some(properties) = extract_dynamic_properties(&mut row) {
+ self.stack = dynamic_properties_to_vec(properties);
+ } else {
+ // Most common case: just a regular row. We allocated nothing.
+ return Some(DbItem::Row(row));
+ }
+ } else {
+ return Some(db_item);
+ }
+ }
+ expand_dynamic_stack(&mut self.stack);
+ self.stack.pop().map(|result| match result {
+ Ok(row) => DbItem::Row(row),
+ Err(err) => DbItem::Error(err),
+ })
+ }
+}
+
+fn expand_dynamic_stack(stack: &mut Vec<anyhow::Result<JsonValue>>) {
+ while let Some(Ok(mut next)) = stack.pop() {
+ if let Some(properties) = extract_dynamic_properties(&mut next) {
+ stack.extend(dynamic_properties_to_vec(properties));
+ } else {
+ stack.push(Ok(next));
+ return;
+ }
+ }
+}
+
+/// if row.component == 'dynamic', return Some(row.properties), otherwise return None
+#[inline]
+fn extract_dynamic_properties(data: &mut JsonValue) -> Option<JsonValue> {
+ let component = data.get("component").and_then(|v| v.as_str());
+ if component == Some("dynamic") {
+ let properties = data.get_mut("properties").map(JsonValue::take);
+ Some(properties.unwrap_or_default())
+ } else {
+ None
+ }
+}
+
+/// reverse the order of the vec returned by `dynamic_properties_to_result_vec`,
+/// and wrap each element in a Result
+fn dynamic_properties_to_vec(properties_obj: JsonValue) -> Vec<anyhow::Result<JsonValue>> {
+ dynamic_properties_to_result_vec(properties_obj).map_or_else(
+ |err| vec![Err(err)],
+ |vec| vec.into_iter().rev().map(Ok).collect::<Vec<_>>(),
+ )
+}
+
+/// if properties is a string, parse it as JSON and return a vec with the parsed value
+/// if properties is an array, return it as is
+/// if properties is an object, return it as a single element vec
+/// otherwise, return an error
+fn dynamic_properties_to_result_vec(
+ mut properties_obj: JsonValue,
+) -> anyhow::Result<Vec<JsonValue>> {
+ if let JsonValue::String(s) = properties_obj {
+ properties_obj = serde_json::from_str::<JsonValue>(&s).with_context(|| {
+ format!(
+ "Unable to parse the 'properties' property of the dynamic component as JSON.\n\
+ Invalid json: {s}"
+ )
+ })?;
+ }
+ match properties_obj {
+ obj @ JsonValue::Object(_) => Ok(vec![obj]),
+ JsonValue::Array(values) => Ok(values),
+ other => anyhow::bail!(
+ "Dynamic component expected properties of type array or object, got {other} instead."
+ ),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_dynamic_properties_to_result_vec() {
+ let mut properties = JsonValue::String(r#"{"a": 1}"#.to_string());
+ assert_eq!(
+ dynamic_properties_to_result_vec(properties.clone()).unwrap(),
+ vec![JsonValue::Object(
+ serde_json::from_str(r#"{"a": 1}"#).unwrap()
+ )]
+ );
+
+ properties = JsonValue::Array(vec![JsonValue::String(r#"{"a": 1}"#.to_string())]);
+ assert_eq!(
+ dynamic_properties_to_result_vec(properties.clone()).unwrap(),
+ vec![JsonValue::String(r#"{"a": 1}"#.to_string())]
+ );
+
+ properties = JsonValue::Object(serde_json::from_str(r#"{"a": 1}"#).unwrap());
+ assert_eq!(
+ dynamic_properties_to_result_vec(properties.clone()).unwrap(),
+ vec![JsonValue::Object(
+ serde_json::from_str(r#"{"a": 1}"#).unwrap()
+ )]
+ );
+
+ properties = JsonValue::Null;
+ assert!(dynamic_properties_to_result_vec(properties).is_err());
+ }
+
+ #[test]
+ fn test_dynamic_properties_to_vec() {
+ let properties = JsonValue::String(r#"{"a": 1}"#.to_string());
+ assert_eq!(
+ dynamic_properties_to_vec(properties.clone())
+ .first()
+ .unwrap()
+ .as_ref()
+ .unwrap(),
+ &serde_json::json!({"a": 1})
+ );
+ }
+
+ #[test]
+ fn test_parse_dynamic_rows() {
+ let row = DbItem::Row(serde_json::json!({
+ "component": "dynamic",
+ "properties": [
+ {"a": 1},
+ {"component": "dynamic", "properties": {"nested": 2}},
+ ]
+ }));
+ let iter = parse_dynamic_rows(row)
+ .map(|item| match item {
+ DbItem::Row(row) => row,
+ x => panic!("Expected a row, got {x:?}"),
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(
+ iter,
+ vec![
+ serde_json::json!({"a": 1}),
+ serde_json::json!({"nested": 2}),
+ ]
+ );
+ }
+}
diff --git /dev/null b/tests/sql_test_files/error_too_many_nested_inclusions.sql
new file mode 100644
--- /dev/null
+++ b/tests/sql_test_files/error_too_many_nested_inclusions.sql
@@ -0,0 +1,4 @@
+select 'debug' as component,
+ sqlpage.run_sql(
+ 'tests/sql_test_files/error_too_many_nested_inclusions.sql'
+ ) as contents;
\ No newline at end of file
diff --git /dev/null b/tests/sql_test_files/it_works_deeply_nested_dynamic_components.sql
new file mode 100644
--- /dev/null
+++ b/tests/sql_test_files/it_works_deeply_nested_dynamic_components.sql
@@ -0,0 +1,129 @@
+select 'dynamic' as component,'{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"dynamic","properties":
+{"component":"text", "contents": "It works ! (but it shouldn''t)"}
+}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
+' as properties;
\ No newline at end of file
diff --git /dev/null b/tests/sql_test_files/it_works_dynamic_nested.sql
new file mode 100644
--- /dev/null
+++ b/tests/sql_test_files/it_works_dynamic_nested.sql
@@ -0,0 +1,8 @@
+-- Checks that we can have a page with a single dynamic component containing multiple children
+select 'dynamic' as component,
+ '[
+ {"component":"dynamic", "properties": [
+ {"component":"text"},
+ {"contents":"It works !", "bold":true}
+ ]}
+ ]' as properties;
\ No newline at end of file
diff --git /dev/null b/tests/sql_test_files/it_works_dynamic_run_sql_include.sql
new file mode 100644
--- /dev/null
+++ b/tests/sql_test_files/it_works_dynamic_run_sql_include.sql
@@ -0,0 +1,1 @@
+select 'dynamic' as component, sqlpage.run_sql('tests/sql_test_files/it_works_dynamic_shell.sql') as properties;
diff --git /dev/null b/tests/sql_test_files/it_works_run_sql.sql
new file mode 100644
--- /dev/null
+++ b/tests/sql_test_files/it_works_run_sql.sql
@@ -0,0 +1,1 @@
+select 'dynamic' as component, sqlpage.run_sql('tests/sql_test_files/it_works_simple.sql') as properties;
diff --git /dev/null b/tests/sql_test_files/it_works_simple.sql
new file mode 100644
--- /dev/null
+++ b/tests/sql_test_files/it_works_simple.sql
@@ -0,0 +1,2 @@
+select 'shell' as component, 'Hello world !' AS title;
+select 'text' as component, 'It works !' AS contents;
\ No newline at end of file
|
Probe component
A debug component that displays a value (constant, variable, parameter value, result of an SQL function, e.g.). Usefull to validate data flow or function behaviour. Each value (except NULL value) is surrounded by double quotes and followed by datatype (number, string, boolean, e.g.).
|
Is there something that you don't like in the existing `debug` component?
Not really the same finality. The debug component is practical to display and control parameters passed to a component. The Probe component is more generic and her work is just to display a value with additional informations (name, datatype, string content, NULL value, etc.). It could be used to print a HTTP parameter from request, the content of a variable, the value of an environment variable, the result of a fonction, etc.
I'm not sure I see the difference with just
```sql
select 'debug' as component, my_value
```
where my_value can be an HTTP parameter from request, the contents of a variable, the value of an environment variable, the result of a function, etc.
This dumps the value as json, so you can also see its type (including whether it is null).
Maybe the main issue is in the documentation of the debug component that isn't clear enough and doesn't give enough examples?
|
2024-03-04T23:47:37Z
|
0.20
|
2024-03-12T10:50:43Z
|
651d96b6482a8cfad4b21e7a0a8a60aad7f1ba06
|
[
"test_files"
] |
[
"template_helpers::test_rfc2822_date",
"webserver::database::sql::test::is_own_placeholder",
"webserver::database::csv_import::test_make_statement",
"templates::test_split_template",
"webserver::database::sql::test::test_statement_rewrite_sqlite",
"webserver::database::sql::test::test_static_extract",
"webserver::database::sql::test::test_mssql_statement_rewrite",
"webserver::database::sql::test::test_statement_rewrite",
"webserver::database::sql::test::test_set_variable",
"webserver::database::sql::test::test_sqlpage_function_with_argument",
"webserver::database::sql::test::test_static_extract_doesnt_match",
"webserver::database::sql_to_json::test_row_to_json",
"webserver::database::csv_import::test_end_to_end",
"webserver::http_request_info::test::test_extract_multipart_form_data",
"render::tests::test_split_template_render",
"webserver::http_request_info::test::test_extract_urlencoded_request",
"webserver::http_request_info::test::test_extract_empty_request",
"filesystem::test_sql_file_read_utf8",
"render::tests::test_delayed",
"test_access_config_forbidden",
"test_file_upload",
"test_csv_upload",
"test_index_ok",
"privileged_paths_are_not_accessible",
"test_concurrent_requests",
"test_404"
] |
[] |
[] |
sqlpage/SQLPage
| 139
|
sqlpage__SQLPage-139
|
[
"24"
] |
ad0fc2c981e18686d6a7be10e5e5a1569ef55628
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,28 @@
# CHANGELOG.md
-## 0.16.1
+## unreleased
+
+### Uploads
+
+This release is all about a long awaited feature: file uploads.
+Your SQLPage website can now accept file uploads from users, store them either in a directory or directly in a database table.
+
+#### New functions
+
+##### Handle uploaded files
+
+ - [`sqlpage.uploaded_file_path`](https://sql.ophir.dev/functions.sql?function=uploaded_file_path#function) to get the temprary local path of a file uploaded by the user. This path will be valid until the end of the current request, and will be located in a temporary directory (customizable with `TMPDIR`). You can use [`sqlpage.exec`](https://sql.ophir.dev/functions.sql?function=exec#function) to operate on the file, for instance to move it to a permanent location.
+ - [`sqlpage.uploaded_file_mime_type`](https://sql.ophir.dev/functions.sql?function=uploaded_file_name#function) to get the type of file uploaded by the user. This is the MIME type of the file, such as `image/png` or `text/csv`. You can use this to easily check that the file is of the expected type before storing it.
+
+##### Read files
+
+These new functions are useful to read the content of a file uploaded by the user,
+but can also be used to read any file on the server.
+
+ - [`sqlpage.read_file_as_text`](https://sql.ophir.dev/functions.sql?function=read_file#function) reads the contents of a file on the server and returns a text string.
+ - [`sqlpage.read_file_as_data_url`](https://sql.ophir.dev/functions.sql?function=read_file#function) reads the contents of a file on the server and returns a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs). This is useful to embed images directly in web pages, or make link
+
+## 0.16.1 (2023-11-22)
- fix a bug where setting a variable to a non-string value would always set it to null
- clearer debug logs (https://github.com/wooorm/markdown-rs/pull/92)
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -69,6 +69,44 @@ dependencies = [
"syn 2.0.39",
]
+[[package]]
+name = "actix-multipart"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b960e2aea75f49c8f069108063d12a48d329fc8b60b786dfc7552a9d5918d2d"
+dependencies = [
+ "actix-multipart-derive",
+ "actix-utils",
+ "actix-web",
+ "bytes",
+ "derive_more",
+ "futures-core",
+ "futures-util",
+ "httparse",
+ "local-waker",
+ "log",
+ "memchr",
+ "mime",
+ "serde",
+ "serde_json",
+ "serde_plain",
+ "tempfile",
+ "tokio",
+]
+
+[[package]]
+name = "actix-multipart-derive"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0a0a77f836d869f700e5b47ac7c3c8b9c8bc82e4aec861954c6198abee3ebd4d"
+dependencies = [
+ "darling",
+ "parse-size",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.39",
+]
+
[[package]]
name = "actix-router"
version = "0.5.1"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -694,6 +732,41 @@ dependencies = [
"typenum",
]
+[[package]]
+name = "darling"
+version = "0.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e"
+dependencies = [
+ "darling_core",
+ "darling_macro",
+]
+
+[[package]]
+name = "darling_core"
+version = "0.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621"
+dependencies = [
+ "fnv",
+ "ident_case",
+ "proc-macro2",
+ "quote",
+ "strsim",
+ "syn 2.0.39",
+]
+
+[[package]]
+name = "darling_macro"
+version = "0.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5"
+dependencies = [
+ "darling_core",
+ "quote",
+ "syn 2.0.39",
+]
+
[[package]]
name = "dary_heap"
version = "0.3.6"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -846,6 +919,12 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "fastrand"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5"
+
[[package]]
name = "finl_unicode"
version = "1.2.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1210,6 +1289,12 @@ dependencies = [
"cc",
]
+[[package]]
+name = "ident_case"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
+
[[package]]
name = "idna"
version = "0.4.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1685,6 +1770,12 @@ dependencies = [
"windows-targets",
]
+[[package]]
+name = "parse-size"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "944553dd59c802559559161f9816429058b869003836120e262e8caec061b7ae"
+
[[package]]
name = "password-hash"
version = "0.5.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2143,6 +2234,15 @@ dependencies = [
"serde",
]
+[[package]]
+name = "serde_plain"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2271,6 +2371,7 @@ dependencies = [
name = "sqlpage"
version = "0.16.1"
dependencies = [
+ "actix-multipart",
"actix-rt",
"actix-web",
"actix-web-httpauth",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2280,6 +2381,7 @@ dependencies = [
"async-stream",
"async-trait",
"awc",
+ "base64 0.21.5",
"chrono",
"config",
"dashmap",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2439,6 +2541,12 @@ dependencies = [
"unicode-normalization",
]
+[[package]]
+name = "strsim"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
+
[[package]]
name = "subtle"
version = "2.5.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2467,6 +2575,19 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "tempfile"
+version = "3.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5"
+dependencies = [
+ "cfg-if",
+ "fastrand",
+ "redox_syscall",
+ "rustix",
+ "windows-sys",
+]
+
[[package]]
name = "termcolor"
version = "1.4.0"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -45,6 +45,8 @@ password-hash = "0.5.0"
argon2 = "0.5.0"
actix-web-httpauth = "0.8.0"
rand = "0.8.5"
+actix-multipart = "0.6.1"
+base64 = "0.21.5"
[build-dependencies]
awc = { version = "3", features = ["rustls"] }
diff --git a/configuration.md b/configuration.md
--- a/configuration.md
+++ b/configuration.md
@@ -16,6 +16,7 @@ on a [JSON](https://en.wikipedia.org/wiki/JSON) file placed in `sqlpage/sqlpage.
| `sqlite_extensions` | | An array of SQLite extensions to load, such as `mod_spatialite` |
| `web_root` | `.` | The root directory of the web server, where the `index.sql` file is located. |
| `allow_exec` | false | Allow usage of the `sqlpage.exec` function. Do this only if all users with write access to sqlpage query files and to the optional `sqlpage_files` table on the database are trusted. |
+| `max_uploaded_file_size` | 10485760 | Maximum size of uploaded files in bytes. Defaults to 10 MiB. |
You can find an example configuration file in [`sqlpage/sqlpage.json`](./sqlpage/sqlpage.json).
diff --git /dev/null b/examples/official-site/examples/handle_picture_upload.sql
new file mode 100644
--- /dev/null
+++ b/examples/official-site/examples/handle_picture_upload.sql
@@ -0,0 +1,5 @@
+select 'card' as component;
+select 'Your picture' as title;
+
+select 'debug' as component;
+select :my_file as file;
\ No newline at end of file
diff --git a/examples/official-site/sqlpage/migrations/01_documentation.sql b/examples/official-site/sqlpage/migrations/01_documentation.sql
--- a/examples/official-site/sqlpage/migrations/01_documentation.sql
+++ b/examples/official-site/sqlpage/migrations/01_documentation.sql
@@ -378,6 +378,22 @@ if your website has authenticated users that can perform sensitive actions throu
{"name": "password", "label": "Password", "type": "password", "width": 6},
{"name": "password_confirmation", "label": "Password confirmation", "type": "password", "width": 6},
{"name": "terms", "label": "I accept the terms and conditions", "type": "checkbox", "required": true}
+ ]')),
+ ('form', '
+## File upload
+
+You can use the `file` type to allow the user to upload a file.
+The file will be uploaded to the server, and you will be able to access it using the
+[`sqlpage.uploaded_file_path`](functions.sql?function=uploaded_file_path#function) function.
+
+Here is how you could save the uploaded file to a table in the database:
+
+```sql
+INSERT INTO uploaded_file(name, data) VALUES(:filename, sqlpage.uploaded_file_data_url(:filename))
+```
+',
+ json('[{"component":"form", "title": "Upload a picture", "validate": "Upload", "action": "examples/handle_picture_upload.sql"},
+ {"name": "my_file", "type": "file", "accept": "image/png, image/jpeg", "label": "Picture", "description": "Upload a nice picture", "required": true}
]'))
;
diff --git /dev/null b/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql
new file mode 100644
--- /dev/null
+++ b/examples/official-site/sqlpage/migrations/23_uploaded_file_functions.sql
@@ -0,0 +1,99 @@
+-- Insert the 'variables' function into sqlpage_functions table
+INSERT INTO sqlpage_functions (
+ "name",
+ "introduced_in_version",
+ "icon",
+ "description_md"
+)
+VALUES (
+ 'uploaded_file_path',
+ '0.17.0',
+ 'upload',
+ 'Returns the path to a temporary file containing the contents of an uploaded file.
+
+## Example: handling a picture upload
+
+### Making a form
+
+```sql
+select ''form'' as component, ''handle_picture_upload.sql'' as action;
+select ''myfile'' as name, ''file'' as type, ''Picture'' as label;
+select ''title'' as name, ''text'' as type, ''Title'' as label;
+```
+
+### Handling the form response
+
+In `handle_picture_upload.sql`, one can process the form results like this:
+
+```sql
+insert into pictures (title, path) values (:title, sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path(''myfile'')));
+```
+'
+),
+(
+ 'uploaded_file_mime_type',
+ '0.17.0',
+ 'file-settings',
+ 'Returns the MIME type of an uploaded file.
+
+## Example: handling a picture upload
+
+When letting the user upload a picture, you may want to check that the uploaded file is indeed an image.
+
+```sql
+select ''redirect'' as component,
+ ''invalid_file.sql'' as link
+where sqlpage.uploaded_file_mime_type(''myfile'') not like ''image/%'';
+```
+
+In `invalid_file.sql`, you can display an error message to the user:
+
+```sql
+select ''alert'' as component, ''Error'' as title,
+ ''Invalid file type'' as description,
+ ''alert-circle'' as icon, ''red'' as color;
+```
+
+## Example: white-listing file types
+
+You could have a database table containing the allowed MIME types, and check that the uploaded file is of one of those types:
+
+```sql
+select ''redirect'' as component,
+ ''invalid_file.sql'' as link
+where sqlpage.uploaded_file_mime_type(''myfile'') not in (select mime_type from allowed_mime_types);
+```
+'
+);
+
+INSERT INTO sqlpage_function_parameters (
+ "function",
+ "index",
+ "name",
+ "description_md",
+ "type"
+)
+VALUES (
+ 'uploaded_file_path',
+ 1,
+ 'name',
+ 'Name of the file input field in the form.',
+ 'TEXT'
+),
+(
+ 'uploaded_file_path',
+ 2,
+ 'allowed_mime_type',
+ 'Makes the function return NULL if the uploaded file is not of the specified MIME type.
+ If omitted, any MIME type is allowed.
+ This makes it possible to restrict the function to only accept certain file types.',
+ 'TEXT'
+),
+(
+ 'uploaded_file_mime_type',
+ 1,
+ 'name',
+ 'Name of the file input field in the form.',
+ 'TEXT'
+)
+;
diff --git /dev/null b/examples/official-site/sqlpage/migrations/24_read_file_as_data_url.sql
new file mode 100644
--- /dev/null
+++ b/examples/official-site/sqlpage/migrations/24_read_file_as_data_url.sql
@@ -0,0 +1,41 @@
+-- Insert the 'variables' function into sqlpage_functions table
+INSERT INTO sqlpage_functions (
+ "name",
+ "introduced_in_version",
+ "icon",
+ "description_md"
+)
+VALUES (
+ 'read_file_as_data_url',
+ '0.17.0',
+ 'file-dollar',
+ 'Returns a [data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)
+containing the contents of the given file.
+
+## Example: inlining a picture
+
+```sql
+select ''card'' as component;
+select ''Picture'' as title, sqlpage.read_file_as_data_url(''/path/to/picture.jpg'') as top_image;
+```
+
+> **Note:** Data URLs are larger than the original file they represent, so they should only be used for small files (a few kilobytes).
+> Otherwise, the page will take a long time to load.
+');
+
+-- Insert the parameters for the 'variables' function into sqlpage_function_parameters table
+-- Parameter 1: 'method' parameter
+INSERT INTO sqlpage_function_parameters (
+ "function",
+ "index",
+ "name",
+ "description_md",
+ "type"
+)
+VALUES (
+ 'read_file_as_data_url',
+ 1,
+ 'name',
+ 'Path to the file to read.',
+ 'TEXT'
+);
diff --git /dev/null b/examples/official-site/sqlpage/migrations/25_read_file_as_text.sql
new file mode 100644
--- /dev/null
+++ b/examples/official-site/sqlpage/migrations/25_read_file_as_text.sql
@@ -0,0 +1,40 @@
+-- Insert the 'variables' function into sqlpage_functions table
+INSERT INTO sqlpage_functions (
+ "name",
+ "introduced_in_version",
+ "icon",
+ "description_md"
+)
+VALUES (
+ 'read_file_as_text',
+ '0.17.0',
+ 'file-invoice',
+ 'Returns a string containing the contents of the given file.
+
+The file must be a raw text file using UTF-8 encoding.
+
+## Example
+
+### Rendering a markdown file
+
+```sql
+select ''text'' as component, sqlpage.read_file_as_text(''/path/to/file.md'') as text;
+```
+');
+
+-- Insert the parameters for the 'variables' function into sqlpage_function_parameters table
+-- Parameter 1: 'method' parameter
+INSERT INTO sqlpage_function_parameters (
+ "function",
+ "index",
+ "name",
+ "description_md",
+ "type"
+)
+VALUES (
+ 'read_file_as_text',
+ 1,
+ 'name',
+ 'Path to the file to read.',
+ 'TEXT'
+);
diff --git a/sqlpage/templates/form.handlebars b/sqlpage/templates/form.handlebars
--- a/sqlpage/templates/form.handlebars
+++ b/sqlpage/templates/form.handlebars
@@ -85,6 +85,7 @@
{{~#if formtarget}}formtarget="{{formtarget}}" {{/if~}}
{{~#if list}}list="{{list}}" {{/if~}}
{{~#if multiple}}multiple="{{multiple}}" {{/if~}}
+ {{~#if accept}}accept="{{accept}}" {{/if~}}
{{~#if autofocus}}autofocus {{/if~}}
>
{{/if}}
diff --git a/sqlpage/templates/form.handlebars b/sqlpage/templates/form.handlebars
--- a/sqlpage/templates/form.handlebars
+++ b/sqlpage/templates/form.handlebars
@@ -95,6 +96,10 @@
</label>
{{/if}}
{{/if}}
+ <!-- Change the form encoding type if this is a file input-->
+ {{#if (eq type "file")}}
+ {{#delay}}formenctype="multipart/form-data"{{/delay}}
+ {{/if}}
{{/each_row}}
</div>
{{#if (ne validate '')}}
diff --git a/sqlpage/templates/form.handlebars b/sqlpage/templates/form.handlebars
--- a/sqlpage/templates/form.handlebars
+++ b/sqlpage/templates/form.handlebars
@@ -103,6 +108,7 @@
{{#if validate_shape}} btn-{{validate_shape}} {{/if}}
{{#if validate_outline}} btn-outline-{{validate_outline}} {{/if}}
{{#if validate_size}} btn-{{validate_size}} {{/if}}"
+ {{flush_delayed}}
type="submit"
{{#if validate}}value="{{validate}}"{{/if}}>
{{/if}}
diff --git a/src/app_config.rs b/src/app_config.rs
--- a/src/app_config.rs
+++ b/src/app_config.rs
@@ -44,6 +44,10 @@ pub struct AppConfig {
/// them the ability to execute arbitrary shell commands on the server.
#[serde(default)]
pub allow_exec: bool,
+
+ /// Maximum size of uploaded files in bytes. The default is 10MiB (10 * 1024 * 1024 bytes)
+ #[serde(default = "default_max_file_size")]
+ pub max_uploaded_file_size: usize,
}
pub fn load() -> anyhow::Result<AppConfig> {
diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -15,6 +15,11 @@ async fn main() {
async fn start() -> anyhow::Result<()> {
let app_config = app_config::load()?;
log::debug!("Starting with the following configuration: {app_config:?}");
+ std::env::set_current_dir(&app_config.web_root)?;
+ log::info!(
+ "Set the working directory to {}",
+ app_config.web_root.display()
+ );
let state = AppState::init(&app_config).await?;
webserver::database::migrations::apply(&state.db).await?;
let listen_on = app_config.listen_on;
diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -46,5 +51,8 @@ async fn log_welcome_message(config: &AppConfig) {
}
fn init_logging() {
- env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
+ let env = env_logger::Env::new().default_filter_or("info");
+ let mut logging = env_logger::Builder::from_env(env);
+ logging.format_timestamp_millis();
+ logging.init();
}
diff --git a/src/webserver/database/execute_queries.rs b/src/webserver/database/execute_queries.rs
--- a/src/webserver/database/execute_queries.rs
+++ b/src/webserver/database/execute_queries.rs
@@ -7,7 +7,8 @@ use std::collections::HashMap;
use super::sql::{ParsedSqlFile, ParsedStatement, StmtWithParams};
use crate::webserver::database::sql_pseudofunctions::extract_req_param;
use crate::webserver::database::sql_to_json::row_to_string;
-use crate::webserver::http::{RequestInfo, SingleOrVec};
+use crate::webserver::http::SingleOrVec;
+use crate::webserver::http_request_info::RequestInfo;
use sqlx::any::{AnyArguments, AnyQueryResult, AnyRow, AnyStatement, AnyTypeInfo};
use sqlx::pool::PoolConnection;
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -2,12 +2,11 @@ use std::{borrow::Cow, collections::HashMap};
use actix_web::http::StatusCode;
use actix_web_httpauth::headers::authorization::Basic;
+use base64::Engine;
+use mime_guess::{mime::APPLICATION_OCTET_STREAM, Mime};
use sqlparser::ast::FunctionArg;
-use crate::webserver::{
- http::{RequestInfo, SingleOrVec},
- ErrorWithStatus,
-};
+use crate::webserver::{http::SingleOrVec, http_request_info::RequestInfo, ErrorWithStatus};
use super::sql::{
extract_integer, extract_single_quoted_string, extract_single_quoted_string_optional,
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -35,6 +34,9 @@ pub(super) enum StmtParam {
EnvironmentVariable(String),
SqlPageVersion,
Literal(String),
+ UploadedFilePath(String),
+ ReadFileAsText(Box<StmtParam>),
+ ReadFileAsDataUrl(Box<StmtParam>),
Path,
}
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -89,6 +91,15 @@ pub(super) fn func_call_to_param(func_name: &str, arguments: &mut [FunctionArg])
"version" => StmtParam::SqlPageVersion,
"variables" => parse_get_or_post(extract_single_quoted_string_optional(arguments)),
"path" => StmtParam::Path,
+ "uploaded_file_path" => extract_single_quoted_string("uploaded_file_path", arguments)
+ .map_or_else(StmtParam::Error, StmtParam::UploadedFilePath),
+ "read_file_as_text" => StmtParam::ReadFileAsText(Box::new(extract_variable_argument(
+ "read_file_as_text",
+ arguments,
+ ))),
+ "read_file_as_data_url" => StmtParam::ReadFileAsDataUrl(Box::new(
+ extract_variable_argument("read_file_as_data_url", arguments),
+ )),
unknown_name => StmtParam::Error(format!(
"Unknown function {unknown_name}({})",
FormatArguments(arguments)
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -106,6 +117,8 @@ pub(super) async fn extract_req_param<'a>(
StmtParam::HashPassword(inner) => has_password_param(inner, request).await?,
StmtParam::Exec(args_params) => exec_external_command(args_params, request).await?,
StmtParam::UrlEncode(inner) => url_encode(inner, request)?,
+ StmtParam::ReadFileAsText(inner) => read_file_as_text(inner, request).await?,
+ StmtParam::ReadFileAsDataUrl(inner) => read_file_as_data_url(inner, request).await?,
_ => extract_req_param_non_nested(param, request)?,
})
}
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -176,6 +189,55 @@ async fn exec_external_command<'a>(
)))
}
+async fn read_file_as_text<'a>(
+ param0: &StmtParam,
+ request: &'a RequestInfo,
+) -> Result<Option<Cow<'a, str>>, anyhow::Error> {
+ let Some(evaluated_param) = extract_req_param_non_nested(param0, request)? else {
+ log::debug!("read_file: first argument is NULL, returning NULL");
+ return Ok(None);
+ };
+ let bytes = tokio::fs::read(evaluated_param.as_ref())
+ .await
+ .with_context(|| format!("Unable to read file {evaluated_param}"))?;
+ let as_str = String::from_utf8(bytes)
+ .with_context(|| format!("read_file_as_text: {param0:?} does not contain raw UTF8 text"))?;
+ Ok(Some(Cow::Owned(as_str)))
+}
+
+async fn read_file_as_data_url<'a>(
+ param0: &StmtParam,
+ request: &'a RequestInfo,
+) -> Result<Option<Cow<'a, str>>, anyhow::Error> {
+ let Some(evaluated_param) = extract_req_param_non_nested(param0, request)? else {
+ log::debug!("read_file: first argument is NULL, returning NULL");
+ return Ok(None);
+ };
+ let bytes = tokio::fs::read(evaluated_param.as_ref())
+ .await
+ .with_context(|| format!("Unable to read file {evaluated_param}"))?;
+ let mime = mime_from_upload(param0, request).map_or_else(
+ || Cow::Owned(mime_guess_from_filename(&evaluated_param)),
+ Cow::Borrowed,
+ );
+ let mut data_url = format!("data:{}/{};base64,", mime.type_(), mime.subtype());
+ base64::engine::general_purpose::URL_SAFE.encode_string(bytes, &mut data_url);
+ Ok(Some(Cow::Owned(data_url)))
+}
+
+fn mime_from_upload<'a>(param0: &StmtParam, request: &'a RequestInfo) -> Option<&'a Mime> {
+ if let StmtParam::UploadedFilePath(name) = param0 {
+ request.uploaded_files.get(name)?.content_type.as_ref()
+ } else {
+ None
+ }
+}
+
+fn mime_guess_from_filename(filename: &str) -> Mime {
+ let maybe_mime = mime_guess::from_path(filename).first();
+ maybe_mime.unwrap_or(APPLICATION_OCTET_STREAM)
+}
+
pub(super) fn extract_req_param_non_nested<'a>(
param: &StmtParam,
request: &'a RequestInfo,
diff --git a/src/webserver/database/sql_pseudofunctions.rs b/src/webserver/database/sql_pseudofunctions.rs
--- a/src/webserver/database/sql_pseudofunctions.rs
+++ b/src/webserver/database/sql_pseudofunctions.rs
@@ -210,6 +272,15 @@ pub(super) fn extract_req_param_non_nested<'a>(
StmtParam::Literal(x) => Some(Cow::Owned(x.to_string())),
StmtParam::AllVariables(get_or_post) => extract_get_or_post(*get_or_post, request),
StmtParam::Path => Some(Cow::Borrowed(&request.path)),
+ StmtParam::UploadedFilePath(x) => request
+ .uploaded_files
+ .get(x)
+ .and_then(|x| x.file.path().to_str())
+ .map(Cow::Borrowed),
+ StmtParam::ReadFileAsText(_) => bail!("Nested read_file_as_text() function not allowed",),
+ StmtParam::ReadFileAsDataUrl(_) => {
+ bail!("Nested read_file_as_data_url() function not allowed",)
+ }
})
}
diff --git a/src/webserver/database/sql_to_json.rs b/src/webserver/database/sql_to_json.rs
--- a/src/webserver/database/sql_to_json.rs
+++ b/src/webserver/database/sql_to_json.rs
@@ -1,4 +1,3 @@
-pub use crate::file_cache::FileCache;
use crate::utils::add_value_to_map;
use serde_json::{self, Map, Value};
use sqlx::any::AnyRow;
diff --git a/src/webserver/http.rs b/src/webserver/http.rs
--- a/src/webserver/http.rs
+++ b/src/webserver/http.rs
@@ -1,37 +1,32 @@
use crate::render::{HeaderContext, PageContext, RenderContext};
use crate::webserver::database::{execute_queries::stream_query_results, DbItem};
+use crate::webserver::http_request_info::extract_request_info;
use crate::webserver::ErrorWithStatus;
use crate::{AppState, Config, ParsedSqlFile};
use actix_web::dev::{fn_service, ServiceFactory, ServiceRequest};
use actix_web::error::ErrorInternalServerError;
use actix_web::http::header::{ContentType, Header, HttpDate, IfModifiedSince, LastModified};
use actix_web::http::{header, StatusCode, Uri};
-use actix_web::web::Form;
use actix_web::{
- dev::ServiceResponse, middleware, middleware::Logger, web, web::Bytes, App, FromRequest,
- HttpResponse, HttpServer,
+ dev::ServiceResponse, middleware, middleware::Logger, web, web::Bytes, App, HttpResponse,
+ HttpServer,
};
+use super::static_content;
use actix_web::body::{BoxBody, MessageBody};
-use actix_web_httpauth::headers::authorization::{Authorization, Basic};
use anyhow::Context;
use chrono::{DateTime, Utc};
use futures_util::stream::Stream;
use futures_util::StreamExt;
use std::borrow::Cow;
-use std::collections::hash_map::Entry;
-use std::collections::HashMap;
use std::io::Write;
use std::mem;
-use std::net::IpAddr;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::time::SystemTime;
use tokio::sync::mpsc;
-use super::static_content;
-
/// If the sending queue exceeds this number of outgoing messages, an error will be thrown
/// This prevents a single request from using up all available memory
const MAX_PENDING_MESSAGES: usize = 128;
diff --git a/src/webserver/http.rs b/src/webserver/http.rs
--- a/src/webserver/http.rs
+++ b/src/webserver/http.rs
@@ -286,9 +281,7 @@ fn send_anyhow_error(e: &anyhow::Error, resp_send: tokio::sync::oneshot::Sender<
.unwrap_or_else(|_| log::error!("could not send headers"));
}
-type ParamMap = HashMap<String, SingleOrVec>;
-
-#[derive(Debug, serde::Serialize, serde::Deserialize)]
+#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(untagged)]
pub enum SingleOrVec {
Single(String),
diff --git a/src/webserver/http.rs b/src/webserver/http.rs
--- a/src/webserver/http.rs
+++ b/src/webserver/http.rs
@@ -296,7 +289,7 @@ pub enum SingleOrVec {
}
impl SingleOrVec {
- fn merge(&mut self, other: Self) {
+ pub(crate) fn merge(&mut self, other: Self) {
match (self, other) {
(Self::Single(old), Self::Single(new)) => *old = new,
(old, mut new) => {
diff --git a/src/webserver/http.rs b/src/webserver/http.rs
--- a/src/webserver/http.rs
+++ b/src/webserver/http.rs
@@ -322,80 +315,6 @@ impl SingleOrVec {
}
}
-#[derive(Debug)]
-pub struct RequestInfo {
- pub path: String,
- pub get_variables: ParamMap,
- pub post_variables: ParamMap,
- pub headers: ParamMap,
- pub client_ip: Option<IpAddr>,
- pub cookies: ParamMap,
- pub basic_auth: Option<Basic>,
- pub app_state: Arc<AppState>,
-}
-
-fn param_map<PAIRS: IntoIterator<Item = (String, String)>>(values: PAIRS) -> ParamMap {
- values
- .into_iter()
- .fold(HashMap::new(), |mut map, (mut k, v)| {
- let entry = if k.ends_with("[]") {
- k.replace_range(k.len() - 2.., "");
- SingleOrVec::Vec(vec![v])
- } else {
- SingleOrVec::Single(v)
- };
- match map.entry(k) {
- Entry::Occupied(mut s) => {
- SingleOrVec::merge(s.get_mut(), entry);
- }
- Entry::Vacant(v) => {
- v.insert(entry);
- }
- }
- map
- })
-}
-
-async fn extract_request_info(req: &mut ServiceRequest, app_state: Arc<AppState>) -> RequestInfo {
- let (http_req, payload) = req.parts_mut();
- let post_variables = Form::<Vec<(String, String)>>::from_request(http_req, payload)
- .await
- .map(Form::into_inner)
- .unwrap_or_default();
-
- let headers = req.headers().iter().map(|(name, value)| {
- (
- name.to_string(),
- String::from_utf8_lossy(value.as_bytes()).to_string(),
- )
- });
- let get_variables = web::Query::<Vec<(String, String)>>::from_query(req.query_string())
- .map(web::Query::into_inner)
- .unwrap_or_default();
- let client_ip = req.peer_addr().map(|addr| addr.ip());
-
- let raw_cookies = req.cookies();
- let cookies = raw_cookies
- .iter()
- .flat_map(|c| c.iter())
- .map(|cookie| (cookie.name().to_string(), cookie.value().to_string()));
-
- let basic_auth = Authorization::<Basic>::parse(req)
- .ok()
- .map(Authorization::into_scheme);
-
- RequestInfo {
- path: req.path().to_string(),
- headers: param_map(headers),
- get_variables: param_map(get_variables),
- post_variables: param_map(post_variables),
- client_ip,
- cookies: param_map(cookies),
- basic_auth,
- app_state,
- }
-}
-
/// Resolves the path in a query to the path to a local SQL file if there is one that matches
fn path_to_sql_file(path: &str) -> Option<PathBuf> {
let mut path = PathBuf::from(path.strip_prefix('/').unwrap_or(path));
diff --git a/src/webserver/mod.rs b/src/webserver/mod.rs
--- a/src/webserver/mod.rs
+++ b/src/webserver/mod.rs
@@ -1,6 +1,7 @@
pub mod database;
pub mod error_with_status;
pub mod http;
+pub mod http_request_info;
pub use database::Database;
pub use error_with_status::ErrorWithStatus;
|
diff --git a/configuration.md b/configuration.md
--- a/configuration.md
+++ b/configuration.md
@@ -28,6 +29,9 @@ but in uppercase.
The environment variable name can optionally be prefixed with `SQLPAGE_`.
+Additionnally, when troubleshooting, you can set the [`RUST_LOG`](https://docs.rs/env_logger/latest/env_logger/#enabling-logging)
+environment variable to `sqlpage=debug` to get more detailed logs and see exactly what SQLPage is doing.
+
### Example
```bash
diff --git a/src/app_config.rs b/src/app_config.rs
--- a/src/app_config.rs
+++ b/src/app_config.rs
@@ -130,6 +134,10 @@ fn default_web_root() -> PathBuf {
})
}
+fn default_max_file_size() -> usize {
+ 10 * 1024 * 1024
+}
+
#[cfg(test)]
pub mod tests {
use super::AppConfig;
diff --git a/src/filesystem.rs b/src/filesystem.rs
--- a/src/filesystem.rs
+++ b/src/filesystem.rs
@@ -207,14 +207,14 @@ async fn test_sql_file_read_utf8() -> anyhow::Result<()> {
.db
.connection
.execute(
- r#"
+ r"
CREATE TABLE sqlpage_files(
path VARCHAR(255) NOT NULL PRIMARY KEY,
contents BLOB,
last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO sqlpage_files(path, contents) VALUES ('unit test file.txt', 'Héllö world! 😀');
- "#,
+ ",
)
.await?;
let fs = FileSystem::init("/", &state.db).await;
diff --git /dev/null b/src/webserver/http_request_info.rs
new file mode 100644
--- /dev/null
+++ b/src/webserver/http_request_info.rs
@@ -0,0 +1,303 @@
+use super::http::SingleOrVec;
+use crate::AppState;
+use actix_multipart::form::bytes::Bytes;
+use actix_multipart::form::tempfile::TempFile;
+use actix_multipart::form::FieldReader;
+use actix_multipart::form::Limits;
+use actix_multipart::Multipart;
+use actix_web::dev::ServiceRequest;
+use actix_web::http::header::Header;
+use actix_web::http::header::CONTENT_TYPE;
+use actix_web::web;
+use actix_web::web::Form;
+use actix_web::FromRequest;
+use actix_web::HttpRequest;
+use actix_web_httpauth::headers::authorization::Authorization;
+use actix_web_httpauth::headers::authorization::Basic;
+use anyhow::anyhow;
+use std::collections::hash_map::Entry;
+use std::collections::HashMap;
+use std::net::IpAddr;
+use std::sync::Arc;
+use tokio_stream::StreamExt;
+
+#[derive(Debug)]
+pub struct RequestInfo {
+ pub path: String,
+ pub get_variables: ParamMap,
+ pub post_variables: ParamMap,
+ pub uploaded_files: HashMap<String, TempFile>,
+ pub headers: ParamMap,
+ pub client_ip: Option<IpAddr>,
+ pub cookies: ParamMap,
+ pub basic_auth: Option<Basic>,
+ pub app_state: Arc<AppState>,
+}
+
+pub(crate) async fn extract_request_info(
+ req: &mut ServiceRequest,
+ app_state: Arc<AppState>,
+) -> RequestInfo {
+ let (http_req, payload) = req.parts_mut();
+ let config = &app_state.config;
+ let (post_variables, uploaded_files) = extract_post_data(http_req, payload, config).await;
+
+ let headers = req.headers().iter().map(|(name, value)| {
+ (
+ name.to_string(),
+ String::from_utf8_lossy(value.as_bytes()).to_string(),
+ )
+ });
+ let get_variables = web::Query::<Vec<(String, String)>>::from_query(req.query_string())
+ .map(web::Query::into_inner)
+ .unwrap_or_default();
+ let client_ip = req.peer_addr().map(|addr| addr.ip());
+
+ let raw_cookies = req.cookies();
+ let cookies = raw_cookies
+ .iter()
+ .flat_map(|c| c.iter())
+ .map(|cookie| (cookie.name().to_string(), cookie.value().to_string()));
+
+ let basic_auth = Authorization::<Basic>::parse(req)
+ .ok()
+ .map(Authorization::into_scheme);
+
+ RequestInfo {
+ path: req.path().to_string(),
+ headers: param_map(headers),
+ get_variables: param_map(get_variables),
+ post_variables: param_map(post_variables),
+ uploaded_files: HashMap::from_iter(uploaded_files),
+ client_ip,
+ cookies: param_map(cookies),
+ basic_auth,
+ app_state,
+ }
+}
+
+async fn extract_post_data(
+ http_req: &mut actix_web::HttpRequest,
+ payload: &mut actix_web::dev::Payload,
+ config: &crate::app_config::AppConfig,
+) -> (Vec<(String, String)>, Vec<(String, TempFile)>) {
+ let content_type = http_req
+ .headers()
+ .get(&CONTENT_TYPE)
+ .map(AsRef::as_ref)
+ .unwrap_or_default();
+ if content_type.starts_with(b"application/x-www-form-urlencoded") {
+ match extract_urlencoded_post_variables(http_req, payload).await {
+ Ok(post_variables) => (post_variables, Vec::new()),
+ Err(e) => {
+ log::error!("Could not read urlencoded POST request data: {}", e);
+ (Vec::new(), Vec::new())
+ }
+ }
+ } else if content_type.starts_with(b"multipart/form-data") {
+ extract_multipart_post_data(http_req, payload, config)
+ .await
+ .unwrap_or_else(|e| {
+ log::error!("Could not read request data: {}", e);
+ (Vec::new(), Vec::new())
+ })
+ } else {
+ let ct_str = String::from_utf8_lossy(content_type);
+ log::debug!("Not parsing POST data from request without known content type {ct_str}");
+ (Vec::new(), Vec::new())
+ }
+}
+
+async fn extract_urlencoded_post_variables(
+ http_req: &mut actix_web::HttpRequest,
+ payload: &mut actix_web::dev::Payload,
+) -> actix_web::Result<Vec<(String, String)>> {
+ Form::<Vec<(String, String)>>::from_request(http_req, payload)
+ .await
+ .map(Form::into_inner)
+}
+
+async fn extract_multipart_post_data(
+ http_req: &mut actix_web::HttpRequest,
+ payload: &mut actix_web::dev::Payload,
+ config: &crate::app_config::AppConfig,
+) -> anyhow::Result<(Vec<(String, String)>, Vec<(String, TempFile)>)> {
+ let mut post_variables = Vec::new();
+ let mut uploaded_files = Vec::new();
+
+ let mut multipart = Multipart::from_request(http_req, payload)
+ .await
+ .map_err(|e| anyhow!("could not parse request as multipart form data: {e}"))?;
+
+ let mut limits = Limits::new(config.max_uploaded_file_size, config.max_uploaded_file_size);
+ log::trace!(
+ "Parsing multipart form data with a {:?} KiB limit",
+ limits.total_limit_remaining / 1024
+ );
+
+ while let Some(part) = multipart.next().await {
+ let field = part.map_err(|e| anyhow!("unable to read form field: {e}"))?;
+ // test if field is a file
+ let filename = field.content_disposition().get_filename();
+ let field_name = field
+ .content_disposition()
+ .get_name()
+ .unwrap_or_default()
+ .to_string();
+ log::trace!("Parsing multipart field: {}", field_name);
+ if let Some(filename) = filename {
+ log::debug!("Extracting file: {field_name} ({filename})");
+ let extracted = extract_file(http_req, field, &mut limits).await?;
+ log::trace!("Extracted file {field_name} to {:?}", extracted.file.path());
+ uploaded_files.push((field_name, extracted));
+ } else {
+ let text_contents = extract_text(http_req, field, &mut limits).await?;
+ log::trace!("Extracted field as text: {field_name} = {text_contents:?}");
+ post_variables.push((field_name, text_contents));
+ }
+ }
+ Ok((post_variables, uploaded_files))
+}
+
+async fn extract_text(
+ req: &HttpRequest,
+ field: actix_multipart::Field,
+ limits: &mut Limits,
+) -> anyhow::Result<String> {
+ // field is an async stream of Result<Bytes> objects, we collect them into a Vec<u8>
+ let data = Bytes::read_field(req, field, limits)
+ .await
+ .map(|bytes| bytes.data)
+ .map_err(|e| anyhow!("failed to read form field data: {e}"))?;
+ Ok(String::from_utf8(data.to_vec())?)
+}
+
+async fn extract_file(
+ req: &HttpRequest,
+ field: actix_multipart::Field,
+ limits: &mut Limits,
+) -> anyhow::Result<TempFile> {
+ // extract a tempfile from the field
+ let file = TempFile::read_field(req, field, limits)
+ .await
+ .map_err(|e| anyhow!("Failed to save uploaded file: {e}"))?;
+ Ok(file)
+}
+
+pub type ParamMap = HashMap<String, SingleOrVec>;
+
+fn param_map<PAIRS: IntoIterator<Item = (String, String)>>(values: PAIRS) -> ParamMap {
+ values
+ .into_iter()
+ .fold(HashMap::new(), |mut map, (mut k, v)| {
+ let entry = if k.ends_with("[]") {
+ k.replace_range(k.len() - 2.., "");
+ SingleOrVec::Vec(vec![v])
+ } else {
+ SingleOrVec::Single(v)
+ };
+ match map.entry(k) {
+ Entry::Occupied(mut s) => {
+ SingleOrVec::merge(s.get_mut(), entry);
+ }
+ Entry::Vacant(v) => {
+ v.insert(entry);
+ }
+ }
+ map
+ })
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+ use crate::app_config::AppConfig;
+ use actix_web::{http::header::ContentType, test::TestRequest};
+
+ #[actix_web::test]
+ async fn test_extract_empty_request() {
+ let config =
+ serde_json::from_str::<AppConfig>(r#"{"listen_on": "localhost:1234"}"#).unwrap();
+ let mut service_request = TestRequest::default().to_srv_request();
+ let app_data = Arc::new(AppState::init(&config).await.unwrap());
+ let request_info = extract_request_info(&mut service_request, app_data).await;
+ assert_eq!(request_info.post_variables.len(), 0);
+ assert_eq!(request_info.uploaded_files.len(), 0);
+ assert_eq!(request_info.get_variables.len(), 0);
+ }
+
+ #[actix_web::test]
+ async fn test_extract_urlencoded_request() {
+ let config =
+ serde_json::from_str::<AppConfig>(r#"{"listen_on": "localhost:1234"}"#).unwrap();
+ let mut service_request = TestRequest::get()
+ .uri("/?my_array[]=5")
+ .insert_header(ContentType::form_url_encoded())
+ .set_payload("my_array[]=3&my_array[]=Hello%20World&repeated=1&repeated=2")
+ .to_srv_request();
+ let app_data = Arc::new(AppState::init(&config).await.unwrap());
+ let request_info = extract_request_info(&mut service_request, app_data).await;
+ assert_eq!(
+ request_info.post_variables,
+ vec![
+ (
+ "my_array".to_string(),
+ SingleOrVec::Vec(vec!["3".to_string(), "Hello World".to_string()])
+ ),
+ ("repeated".to_string(), SingleOrVec::Single("2".to_string())), // without brackets, only the last value is kept
+ ]
+ .into_iter()
+ .collect::<ParamMap>()
+ );
+ assert_eq!(request_info.uploaded_files.len(), 0);
+ assert_eq!(
+ request_info.get_variables,
+ vec![(
+ "my_array".to_string(),
+ SingleOrVec::Vec(vec!["5".to_string()])
+ )] // with brackets, even if there is only one value, it is kept as a vector
+ .into_iter()
+ .collect::<ParamMap>()
+ );
+ }
+
+ #[actix_web::test]
+ async fn test_extract_multipart_form_data() {
+ env_logger::init();
+ let config =
+ serde_json::from_str::<AppConfig>(r#"{"listen_on": "localhost:1234"}"#).unwrap();
+ let mut service_request = TestRequest::get()
+ .insert_header(("content-type", "multipart/form-data;boundary=xxx"))
+ .set_payload(
+ "--xxx\r\n\
+ Content-Disposition: form-data; name=\"my_array[]\"\r\n\
+ Content-Type: text/plain\r\n\
+ \r\n\
+ 3\r\n\
+ --xxx\r\n\
+ Content-Disposition: form-data; name=\"my_uploaded_file\"; filename=\"test.txt\"\r\n\
+ Content-Type: text/plain\r\n\
+ \r\n\
+ Hello World\r\n\
+ --xxx--\r\n"
+ )
+ .to_srv_request();
+ let app_data = Arc::new(AppState::init(&config).await.unwrap());
+ let request_info = extract_request_info(&mut service_request, app_data).await;
+ assert_eq!(
+ request_info.post_variables,
+ vec![(
+ "my_array".to_string(),
+ SingleOrVec::Vec(vec!["3".to_string()])
+ ),]
+ .into_iter()
+ .collect::<ParamMap>()
+ );
+ assert_eq!(request_info.uploaded_files.len(), 1);
+ let my_upload = &request_info.uploaded_files["my_uploaded_file"];
+ assert_eq!(my_upload.file_name.as_ref().unwrap(), "test.txt");
+ assert_eq!(request_info.get_variables.len(), 0);
+ assert_eq!(std::fs::read(&my_upload.file).unwrap(), b"Hello World");
+ assert_eq!(request_info.get_variables.len(), 0);
+ }
+}
diff --git a/tests/index.rs b/tests/index.rs
--- a/tests/index.rs
+++ b/tests/index.rs
@@ -1,7 +1,7 @@
use actix_web::{
body::MessageBody,
- http::{self, header::ContentType},
- test,
+ http::{self, header::ContentType, StatusCode},
+ test::{self, TestRequest},
};
use sqlpage::{app_config::AppConfig, webserver::http::main_handler, AppState};
diff --git a/tests/index.rs b/tests/index.rs
--- a/tests/index.rs
+++ b/tests/index.rs
@@ -86,14 +86,43 @@ async fn test_files() {
}
}
-async fn req_path(path: &str) -> Result<actix_web::dev::ServiceResponse, actix_web::Error> {
+#[actix_web::test]
+async fn test_file_upload() -> actix_web::Result<()> {
+ let req = get_request_to("/tests/upload_file_test.sql")
+ .await?
+ .insert_header(("content-type", "multipart/form-data; boundary=1234567890"))
+ .set_payload(
+ "--1234567890\r\n\
+ Content-Disposition: form-data; name=\"my_file\"; filename=\"testfile.txt\"\r\n\
+ Content-Type: text/plain\r\n\
+ \r\n\
+ Hello, world!\r\n\
+ --1234567890--\r\n",
+ )
+ .to_srv_request();
+ let resp = main_handler(req).await?;
+
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = test::read_body(resp).await;
+ let body_str = String::from_utf8(body.to_vec()).unwrap();
+ assert!(
+ body_str.contains("Hello, world!"),
+ "{body_str}\nexpected to contain: Hello, world!"
+ );
+ Ok(())
+}
+
+async fn get_request_to(path: &str) -> actix_web::Result<TestRequest> {
init_log();
let config = test_config();
let state = AppState::init(&config).await.unwrap();
let data = actix_web::web::Data::new(state);
- let req = test::TestRequest::get()
- .uri(path)
- .app_data(data)
+ Ok(test::TestRequest::get().uri(path).app_data(data))
+}
+
+async fn req_path(path: &str) -> Result<actix_web::dev::ServiceResponse, actix_web::Error> {
+ let req = get_request_to(path)
+ .await?
.insert_header(ContentType::plaintext())
.to_srv_request();
main_handler(req).await
diff --git /dev/null b/tests/it_works.txt
new file mode 100644
--- /dev/null
+++ b/tests/it_works.txt
@@ -0,0 +1,1 @@
+It works !
\ No newline at end of file
diff --git /dev/null b/tests/sql_test_files/it_works_read_file_as_data_url.sql
new file mode 100644
--- /dev/null
+++ b/tests/sql_test_files/it_works_read_file_as_data_url.sql
@@ -0,0 +1,12 @@
+set actual = sqlpage.read_file_as_data_url('tests/it_works.txt')
+set expected = 'data:text/plain;base64,SXQgd29ya3MgIQ==';
+
+select 'text' as component,
+ case $actual
+ when $expected
+ then 'It works !'
+ else
+ 'Failed.
+ Expected: ' || $expected ||
+ 'Got: ' || $actual
+ end as contents;
diff --git /dev/null b/tests/sql_test_files/it_works_read_file_as_text.sql
new file mode 100644
--- /dev/null
+++ b/tests/sql_test_files/it_works_read_file_as_text.sql
@@ -0,0 +1,1 @@
+select 'text' as component, sqlpage.read_file_as_text('tests/it_works.txt') as contents;
diff --git /dev/null b/tests/sql_test_files/it_works_uploaded_file_is_null.sql
new file mode 100644
--- /dev/null
+++ b/tests/sql_test_files/it_works_uploaded_file_is_null.sql
@@ -0,0 +1,7 @@
+-- checks that sqlpage.uploaded_file_path returns null when there is no uploaded_file
+set actual = sqlpage.uploaded_file_path('my_file');
+select 'text' as component,
+ case when $actual is null
+ then 'It works !'
+ else 'Failed. Expected: null. Got: ' || $actual
+ end as contents;
diff --git /dev/null b/tests/upload_file_test.sql
new file mode 100644
--- /dev/null
+++ b/tests/upload_file_test.sql
@@ -0,0 +1,2 @@
+select 'text' as component,
+ sqlpage.read_file_as_text(sqlpage.uploaded_file_path('my_file')) as contents;
\ No newline at end of file
|
file uploads
Hello,
Is it possible to integrate a "files" or "uploads" component that would make it possible to upload a file via the form?
Each file could be stored in a "uploads" folder (by default) and metadata in a table named "uploads" (by default) with the following fields (e.g.) : id, uuid-name, date-created.
|
Hi !
Yes, handling uploads is on the roadmap. But I'm not a huge fan of the `uploads` folder and the `uploads` table.
SQLPage is completely agnostic to your database or folder structure so far, and I'd like it to stay this way. You can use sqlpage with a read-only database, you can use it with a database on which you don't have the permission to create new tables, you can use it on a read-only filesystem, and that's something I'd like to keep.
The way I was thinking about this feature was adding [sqlpage pseudo-functions](https://sql.ophir.dev/functions.sql) :
- `sqlpage.uploaded_file('name')`
- `sqlpage.base64()` to be used with standard `INSERT` statements to make it easy to save files directly in the database and reuse them
- and maybe a component to save data to disk (`SELECT 'save_file' AS component, 'xxx' AS filename, sqlpage.uploaded_file('name') AS contents`)
Why not use sqlpage/sqlpage.json to allow certain parameters, such as the upload folder, to be modified?
If I'm not mistaken: we can integrate a js script into a template to, for example, resize an image before uploading it. Yes ?
It's true that these reflections are very touchy, because the basic idea of simplicity is excellent, and every addition shouldn't call it into question with the risk of creating a bag of knots.
Here is what I think needs to be done:
- Add `enctype=multipart/form-data` to forms in the form component
- Add a dependency to [actix-multipart](https://docs.rs/actix-multipart/0.6.0), with the tempfile optional dependency
- Parse request bodies as multipart in `extract_request_info` in http.rs. Save files as tempfiles.
- Add two new functions
- `sqlpage.uploaded_file_dataurl('name')` which returns an uploaded file as a data url
- `sqlpage.uploaded_file_path('name', 'folder')` which copies the file to the given folder with a secure random name and returns the path
Let me know what you think. If you are interested in implementing it yourself, let me know and I'll guide you through the code and review your pr. If you need that done by me, contact me on [contact at ophir dot dev] and we'll agree on a small dev contract.
|
2023-11-23T07:40:51Z
|
0.16
|
2023-11-24T22:49:57Z
|
42f20563b786b830af039e069094fbd3d08088ea
|
[
"test_file_upload",
"test_files"
] |
[
"webserver::database::sql::test::is_own_placeholder",
"templates::test_split_template",
"webserver::database::sql::test::test_statement_rewrite_sqlite",
"webserver::database::sql::test::test_mssql_statement_rewrite",
"webserver::database::sql::test::test_set_variable",
"webserver::database::sql::test::test_statement_rewrite",
"webserver::database::sql::test::test_static_extract",
"webserver::database::sql::test::test_sqlpage_function_with_argument",
"webserver::database::sql::test::test_static_extract_doesnt_match",
"webserver::database::sql_to_json::test_row_to_json",
"render::tests::test_split_template_render",
"filesystem::test_sql_file_read_utf8",
"render::tests::test_delayed",
"test_access_config_forbidden",
"test_index_ok",
"test_404"
] |
[] |
[] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.