mirror of
https://github.com/storytold/wgpu.git
synced 2026-11-26 01:11:22 +01:00
[wgsl-in] Split into multiple files (#2207)
Make changes suggested in #2075, but put off to a separate PR because they would interfere with reviewing the change: - Split the new WGSL front end into modules in a logical way. - Rename `Parser` to `Frontend`.
This commit is contained in:
1 parent
ae049edc49
commit
67ea8f0c06
28 files changed
+5843
-5772
No files matched your search
@@ -28,7 +28,7 @@ fn gather_inputs(folder: &str, extension: &str) -> Vec<Box<[u8]>> {
|
||||
}
|
||||
|
||||
fn parse_glsl(stage: naga::ShaderStage, inputs: &[Box<[u8]>]) {
|
||||
let mut parser = naga::front::glsl::Parser::default();
|
||||
let mut parser = naga::front::glsl::Frontend::default();
|
||||
let options = naga::front::glsl::Options {
|
||||
stage,
|
||||
defines: Default::default(),
|
||||
@@ -44,12 +44,12 @@ fn frontends(c: &mut Criterion) {
|
||||
#[cfg(all(feature = "wgsl-in", feature = "serialize", feature = "deserialize"))]
|
||||
group.bench_function("bin", |b| {
|
||||
let inputs_wgsl = gather_inputs("tests/in", "wgsl");
|
||||
let mut parser = naga::front::wgsl::Parser::new();
|
||||
let mut frontend = naga::front::wgsl::Frontend::new();
|
||||
let inputs_bin = inputs_wgsl
|
||||
.iter()
|
||||
.map(|input| {
|
||||
let string = std::str::from_utf8(input).unwrap();
|
||||
let module = parser.parse(string).unwrap();
|
||||
let module = frontend.parse(string).unwrap();
|
||||
bincode::serialize(&module).unwrap()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -66,10 +66,10 @@ fn frontends(c: &mut Criterion) {
|
||||
.iter()
|
||||
.map(|input| std::str::from_utf8(input).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
let mut parser = naga::front::wgsl::Parser::new();
|
||||
let mut frontend = naga::front::wgsl::Frontend::new();
|
||||
b.iter(move || {
|
||||
for &input in inputs.iter() {
|
||||
parser.parse(input).unwrap();
|
||||
frontend.parse(input).unwrap();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -81,7 +81,7 @@ fn frontends(c: &mut Criterion) {
|
||||
for input in inputs.iter() {
|
||||
let spv =
|
||||
unsafe { slice::from_raw_parts(input.as_ptr() as *const u32, input.len() / 4) };
|
||||
let parser = naga::front::spv::Parser::new(spv.iter().cloned(), &options);
|
||||
let parser = naga::front::spv::Frontend::new(spv.iter().cloned(), &options);
|
||||
parser.parse().unwrap();
|
||||
}
|
||||
});
|
||||
@@ -101,12 +101,12 @@ fn frontends(c: &mut Criterion) {
|
||||
#[cfg(feature = "wgsl-in")]
|
||||
fn gather_modules() -> Vec<naga::Module> {
|
||||
let inputs = gather_inputs("tests/in", "wgsl");
|
||||
let mut parser = naga::front::wgsl::Parser::new();
|
||||
let mut frontend = naga::front::wgsl::Frontend::new();
|
||||
inputs
|
||||
.iter()
|
||||
.map(|input| {
|
||||
let string = std::str::from_utf8(input).unwrap();
|
||||
parser.parse(string).unwrap()
|
||||
frontend.parse(string).unwrap()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
+1
-1
@@ -289,7 +289,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
ext @ ("vert" | "frag" | "comp") => {
|
||||
let input = String::from_utf8(input)?;
|
||||
let mut parser = naga::front::glsl::Parser::default();
|
||||
let mut parser = naga::front::glsl::Frontend::default();
|
||||
|
||||
(
|
||||
parser
|
||||
|
||||
+26
-20
@@ -4,7 +4,7 @@ use super::{
|
||||
ParameterQualifier,
|
||||
},
|
||||
context::Context,
|
||||
Error, ErrorKind, Parser, Result,
|
||||
Error, ErrorKind, Frontend, Result,
|
||||
};
|
||||
use crate::{
|
||||
BinaryOperator, Block, Constant, DerivativeAxis, Expression, Handle, ImageClass,
|
||||
@@ -1676,7 +1676,7 @@ impl MacroCall {
|
||||
/// finally returns the final expression with the correct result
|
||||
pub fn call(
|
||||
&self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
body: &mut Block,
|
||||
args: &mut [Handle<Expression>],
|
||||
@@ -1688,8 +1688,14 @@ impl MacroCall {
|
||||
args[0]
|
||||
}
|
||||
MacroCall::SamplerShadow => {
|
||||
sampled_to_depth(&mut parser.module, ctx, args[0], meta, &mut parser.errors);
|
||||
parser.invalidate_expression(ctx, args[0], meta)?;
|
||||
sampled_to_depth(
|
||||
&mut frontend.module,
|
||||
ctx,
|
||||
args[0],
|
||||
meta,
|
||||
&mut frontend.errors,
|
||||
);
|
||||
frontend.invalidate_expression(ctx, args[0], meta)?;
|
||||
ctx.samplers.insert(args[0], args[1]);
|
||||
args[0]
|
||||
}
|
||||
@@ -1702,7 +1708,7 @@ impl MacroCall {
|
||||
let mut coords = args[1];
|
||||
|
||||
if proj {
|
||||
let size = match *parser.resolve_type(ctx, coords, meta)? {
|
||||
let size = match *frontend.resolve_type(ctx, coords, meta)? {
|
||||
TypeInner::Vector { size, .. } => size,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
@@ -1748,7 +1754,7 @@ impl MacroCall {
|
||||
|
||||
let extra = args.get(2).copied();
|
||||
let comps =
|
||||
parser.coordinate_components(ctx, args[0], coords, extra, meta, body)?;
|
||||
frontend.coordinate_components(ctx, args[0], coords, extra, meta, body)?;
|
||||
|
||||
let mut num_args = 2;
|
||||
|
||||
@@ -1795,10 +1801,10 @@ impl MacroCall {
|
||||
true => {
|
||||
let offset_arg = args[num_args];
|
||||
num_args += 1;
|
||||
match parser.solve_constant(ctx, offset_arg, meta) {
|
||||
match frontend.solve_constant(ctx, offset_arg, meta) {
|
||||
Ok(v) => Some(v),
|
||||
Err(e) => {
|
||||
parser.errors.push(e);
|
||||
frontend.errors.push(e);
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -1832,7 +1838,7 @@ impl MacroCall {
|
||||
if arrayed {
|
||||
let mut components = Vec::with_capacity(4);
|
||||
|
||||
let size = match *parser.resolve_type(ctx, expr, meta)? {
|
||||
let size = match *frontend.resolve_type(ctx, expr, meta)? {
|
||||
TypeInner::Vector { size: ori_size, .. } => {
|
||||
for index in 0..(ori_size as u32) {
|
||||
components.push(ctx.add_expression(
|
||||
@@ -1862,7 +1868,7 @@ impl MacroCall {
|
||||
body,
|
||||
));
|
||||
|
||||
let ty = parser.module.types.insert(
|
||||
let ty = frontend.module.types.insert(
|
||||
Type {
|
||||
name: None,
|
||||
inner: TypeInner::Vector {
|
||||
@@ -1881,7 +1887,7 @@ impl MacroCall {
|
||||
}
|
||||
MacroCall::ImageLoad { multi } => {
|
||||
let comps =
|
||||
parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?;
|
||||
frontend.coordinate_components(ctx, args[0], args[1], None, meta, body)?;
|
||||
let (sample, level) = match (multi, args.get(2)) {
|
||||
(_, None) => (None, None),
|
||||
(true, Some(&arg)) => (Some(arg), None),
|
||||
@@ -1901,7 +1907,7 @@ impl MacroCall {
|
||||
}
|
||||
MacroCall::ImageStore => {
|
||||
let comps =
|
||||
parser.coordinate_components(ctx, args[0], args[1], None, meta, body)?;
|
||||
frontend.coordinate_components(ctx, args[0], args[1], None, meta, body)?;
|
||||
ctx.emit_restart(body);
|
||||
body.push(
|
||||
crate::Statement::ImageStore {
|
||||
@@ -2037,7 +2043,7 @@ impl MacroCall {
|
||||
body,
|
||||
),
|
||||
MacroCall::Mod(size) => {
|
||||
ctx.implicit_splat(parser, &mut args[1], meta, size)?;
|
||||
ctx.implicit_splat(frontend, &mut args[1], meta, size)?;
|
||||
|
||||
// x - y * floor(x / y)
|
||||
|
||||
@@ -2081,7 +2087,7 @@ impl MacroCall {
|
||||
)
|
||||
}
|
||||
MacroCall::Splatted(fun, size, i) => {
|
||||
ctx.implicit_splat(parser, &mut args[i], meta, size)?;
|
||||
ctx.implicit_splat(frontend, &mut args[i], meta, size)?;
|
||||
|
||||
ctx.add_expression(
|
||||
Expression::Math {
|
||||
@@ -2105,8 +2111,8 @@ impl MacroCall {
|
||||
body,
|
||||
),
|
||||
MacroCall::Clamp(size) => {
|
||||
ctx.implicit_splat(parser, &mut args[1], meta, size)?;
|
||||
ctx.implicit_splat(parser, &mut args[2], meta, size)?;
|
||||
ctx.implicit_splat(frontend, &mut args[1], meta, size)?;
|
||||
ctx.implicit_splat(frontend, &mut args[2], meta, size)?;
|
||||
|
||||
ctx.add_expression(
|
||||
Expression::Math {
|
||||
@@ -2143,8 +2149,8 @@ impl MacroCall {
|
||||
return Ok(None);
|
||||
}
|
||||
MacroCall::SmoothStep { splatted } => {
|
||||
ctx.implicit_splat(parser, &mut args[0], meta, splatted)?;
|
||||
ctx.implicit_splat(parser, &mut args[1], meta, splatted)?;
|
||||
ctx.implicit_splat(frontend, &mut args[0], meta, splatted)?;
|
||||
ctx.implicit_splat(frontend, &mut args[1], meta, splatted)?;
|
||||
|
||||
ctx.add_expression(
|
||||
Expression::Math {
|
||||
@@ -2202,7 +2208,7 @@ fn texture_call(
|
||||
|
||||
/// Helper struct for texture calls with the separate components from the vector argument
|
||||
///
|
||||
/// Obtained by calling [`coordinate_components`](Parser::coordinate_components)
|
||||
/// Obtained by calling [`coordinate_components`](Frontend::coordinate_components)
|
||||
#[derive(Debug)]
|
||||
struct CoordComponents {
|
||||
coordinate: Handle<Expression>,
|
||||
@@ -2211,7 +2217,7 @@ struct CoordComponents {
|
||||
used_extra: bool,
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
impl Frontend {
|
||||
/// Helper function for texture calls, splits the vector argument into it's components
|
||||
fn coordinate_components(
|
||||
&mut self,
|
||||
|
||||
+90
-83
@@ -5,7 +5,7 @@ use super::{
|
||||
},
|
||||
error::{Error, ErrorKind},
|
||||
types::{scalar_components, type_power},
|
||||
Parser, Result,
|
||||
Frontend, Result,
|
||||
};
|
||||
use crate::{
|
||||
front::{Emitter, Typifier},
|
||||
@@ -61,7 +61,7 @@ pub struct Context {
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn new(parser: &Parser, body: &mut Block) -> Self {
|
||||
pub fn new(frontend: &Frontend, body: &mut Block) -> Self {
|
||||
let mut this = Context {
|
||||
expressions: Arena::new(),
|
||||
locals: Arena::new(),
|
||||
@@ -80,8 +80,8 @@ impl Context {
|
||||
|
||||
this.emit_start();
|
||||
|
||||
for &(ref name, lookup) in parser.global_variables.iter() {
|
||||
this.add_global(parser, name, lookup, body)
|
||||
for &(ref name, lookup) in frontend.global_variables.iter() {
|
||||
this.add_global(frontend, name, lookup, body)
|
||||
}
|
||||
|
||||
this
|
||||
@@ -89,7 +89,7 @@ impl Context {
|
||||
|
||||
pub fn add_global(
|
||||
&mut self,
|
||||
parser: &Parser,
|
||||
frontend: &Frontend,
|
||||
name: &str,
|
||||
GlobalLookup {
|
||||
kind,
|
||||
@@ -101,10 +101,10 @@ impl Context {
|
||||
self.emit_end(body);
|
||||
let (expr, load, constant) = match kind {
|
||||
GlobalLookupKind::Variable(v) => {
|
||||
let span = parser.module.global_variables.get_span(v);
|
||||
let span = frontend.module.global_variables.get_span(v);
|
||||
let res = (
|
||||
self.expressions.append(Expression::GlobalVariable(v), span),
|
||||
parser.module.global_variables[v].space != AddressSpace::Handle,
|
||||
frontend.module.global_variables[v].space != AddressSpace::Handle,
|
||||
None,
|
||||
);
|
||||
self.emit_start();
|
||||
@@ -112,7 +112,7 @@ impl Context {
|
||||
res
|
||||
}
|
||||
GlobalLookupKind::BlockSelect(handle, index) => {
|
||||
let span = parser.module.global_variables.get_span(handle);
|
||||
let span = frontend.module.global_variables.get_span(handle);
|
||||
let base = self
|
||||
.expressions
|
||||
.append(Expression::GlobalVariable(handle), span);
|
||||
@@ -124,14 +124,14 @@ impl Context {
|
||||
(
|
||||
expr,
|
||||
{
|
||||
let ty = parser.module.global_variables[handle].ty;
|
||||
let ty = frontend.module.global_variables[handle].ty;
|
||||
|
||||
match parser.module.types[ty].inner {
|
||||
match frontend.module.types[ty].inner {
|
||||
TypeInner::Struct { ref members, .. } => {
|
||||
if let TypeInner::Array {
|
||||
size: crate::ArraySize::Dynamic,
|
||||
..
|
||||
} = parser.module.types[members[index as usize].ty].inner
|
||||
} = frontend.module.types[members[index as usize].ty].inner
|
||||
{
|
||||
false
|
||||
} else {
|
||||
@@ -145,7 +145,7 @@ impl Context {
|
||||
)
|
||||
}
|
||||
GlobalLookupKind::Constant(v, ty) => {
|
||||
let span = parser.module.constants.get_span(v);
|
||||
let span = frontend.module.constants.get_span(v);
|
||||
let res = (
|
||||
self.expressions.append(Expression::Constant(v), span),
|
||||
false,
|
||||
@@ -241,7 +241,7 @@ impl Context {
|
||||
/// Add function argument to current scope
|
||||
pub fn add_function_arg(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
body: &mut Block,
|
||||
name_meta: Option<(String, Span)>,
|
||||
ty: Handle<Type>,
|
||||
@@ -255,14 +255,14 @@ impl Context {
|
||||
};
|
||||
self.parameters.push(ty);
|
||||
|
||||
let opaque = match parser.module.types[ty].inner {
|
||||
let opaque = match frontend.module.types[ty].inner {
|
||||
TypeInner::Image { .. } | TypeInner::Sampler { .. } => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
if qualifier.is_lhs() {
|
||||
let span = parser.module.types.get_span(arg.ty);
|
||||
arg.ty = parser.module.types.insert(
|
||||
let span = frontend.module.types.get_span(arg.ty);
|
||||
arg.ty = frontend.module.types.insert(
|
||||
Type {
|
||||
name: None,
|
||||
inner: TypeInner::Pointer {
|
||||
@@ -345,12 +345,12 @@ impl Context {
|
||||
pub fn lower(
|
||||
&mut self,
|
||||
mut stmt: StmtContext,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
expr: Handle<HirExpr>,
|
||||
pos: ExprPos,
|
||||
body: &mut Block,
|
||||
) -> Result<(Option<Handle<Expression>>, Span)> {
|
||||
let res = self.lower_inner(&stmt, parser, expr, pos, body);
|
||||
let res = self.lower_inner(&stmt, frontend, expr, pos, body);
|
||||
|
||||
stmt.hir_exprs.clear();
|
||||
self.stmt_ctx = Some(stmt);
|
||||
@@ -366,12 +366,12 @@ impl Context {
|
||||
pub fn lower_expect(
|
||||
&mut self,
|
||||
mut stmt: StmtContext,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
expr: Handle<HirExpr>,
|
||||
pos: ExprPos,
|
||||
body: &mut Block,
|
||||
) -> Result<(Handle<Expression>, Span)> {
|
||||
let res = self.lower_expect_inner(&stmt, parser, expr, pos, body);
|
||||
let res = self.lower_expect_inner(&stmt, frontend, expr, pos, body);
|
||||
|
||||
stmt.hir_exprs.clear();
|
||||
self.stmt_ctx = Some(stmt);
|
||||
@@ -382,17 +382,17 @@ impl Context {
|
||||
/// internal implementation of [`lower_expect`](Self::lower_expect)
|
||||
///
|
||||
/// this method is only public because it's used in
|
||||
/// [`function_call`](Parser::function_call), unless you know what
|
||||
/// [`function_call`](Frontend::function_call), unless you know what
|
||||
/// you're doing use [`lower_expect`](Self::lower_expect)
|
||||
pub fn lower_expect_inner(
|
||||
&mut self,
|
||||
stmt: &StmtContext,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
expr: Handle<HirExpr>,
|
||||
pos: ExprPos,
|
||||
body: &mut Block,
|
||||
) -> Result<(Handle<Expression>, Span)> {
|
||||
let (maybe_expr, meta) = self.lower_inner(stmt, parser, expr, pos, body)?;
|
||||
let (maybe_expr, meta) = self.lower_inner(stmt, frontend, expr, pos, body)?;
|
||||
|
||||
let expr = match maybe_expr {
|
||||
Some(e) => e,
|
||||
@@ -472,7 +472,7 @@ impl Context {
|
||||
fn lower_inner(
|
||||
&mut self,
|
||||
stmt: &StmtContext,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
expr: Handle<HirExpr>,
|
||||
pos: ExprPos,
|
||||
body: &mut Block,
|
||||
@@ -484,18 +484,18 @@ impl Context {
|
||||
let handle = match *kind {
|
||||
HirExprKind::Access { base, index } => {
|
||||
let (index, index_meta) =
|
||||
self.lower_expect_inner(stmt, parser, index, ExprPos::Rhs, body)?;
|
||||
self.lower_expect_inner(stmt, frontend, index, ExprPos::Rhs, body)?;
|
||||
let maybe_constant_index = match pos {
|
||||
// Don't try to generate `AccessIndex` if in a LHS position, since it
|
||||
// wouldn't produce a pointer.
|
||||
ExprPos::Lhs => None,
|
||||
_ => parser.solve_constant(self, index, index_meta).ok(),
|
||||
_ => frontend.solve_constant(self, index, index_meta).ok(),
|
||||
};
|
||||
|
||||
let base = self
|
||||
.lower_expect_inner(
|
||||
stmt,
|
||||
parser,
|
||||
frontend,
|
||||
base,
|
||||
pos.maybe_access_base(maybe_constant_index.is_some()),
|
||||
body,
|
||||
@@ -507,7 +507,7 @@ impl Context {
|
||||
Some(self.add_expression(
|
||||
Expression::AccessIndex {
|
||||
base,
|
||||
index: match parser.module.constants[constant].inner {
|
||||
index: match frontend.module.constants[constant].inner {
|
||||
crate::ConstantInner::Scalar {
|
||||
value: ScalarValue::Uint(i),
|
||||
..
|
||||
@@ -528,7 +528,7 @@ impl Context {
|
||||
});
|
||||
|
||||
if ExprPos::Rhs == pos {
|
||||
let resolved = parser.resolve_type(self, pointer, meta)?;
|
||||
let resolved = frontend.resolve_type(self, pointer, meta)?;
|
||||
if resolved.pointer_space().is_some() {
|
||||
return Ok((
|
||||
Some(self.add_expression(Expression::Load { pointer }, meta, body)),
|
||||
@@ -540,32 +540,38 @@ impl Context {
|
||||
pointer
|
||||
}
|
||||
HirExprKind::Select { base, ref field } => {
|
||||
let base = self.lower_expect_inner(stmt, parser, base, pos, body)?.0;
|
||||
let base = self.lower_expect_inner(stmt, frontend, base, pos, body)?.0;
|
||||
|
||||
parser.field_selection(self, pos, body, base, field, meta)?
|
||||
frontend.field_selection(self, pos, body, base, field, meta)?
|
||||
}
|
||||
HirExprKind::Constant(constant) if pos != ExprPos::Lhs => {
|
||||
self.add_expression(Expression::Constant(constant), meta, body)
|
||||
}
|
||||
HirExprKind::Binary { left, op, right } if pos != ExprPos::Lhs => {
|
||||
let (mut left, left_meta) =
|
||||
self.lower_expect_inner(stmt, parser, left, ExprPos::Rhs, body)?;
|
||||
self.lower_expect_inner(stmt, frontend, left, ExprPos::Rhs, body)?;
|
||||
let (mut right, right_meta) =
|
||||
self.lower_expect_inner(stmt, parser, right, ExprPos::Rhs, body)?;
|
||||
self.lower_expect_inner(stmt, frontend, right, ExprPos::Rhs, body)?;
|
||||
|
||||
match op {
|
||||
BinaryOperator::ShiftLeft | BinaryOperator::ShiftRight => self
|
||||
.implicit_conversion(parser, &mut right, right_meta, ScalarKind::Uint, 4)?,
|
||||
.implicit_conversion(
|
||||
frontend,
|
||||
&mut right,
|
||||
right_meta,
|
||||
ScalarKind::Uint,
|
||||
4,
|
||||
)?,
|
||||
_ => self.binary_implicit_conversion(
|
||||
parser, &mut left, left_meta, &mut right, right_meta,
|
||||
frontend, &mut left, left_meta, &mut right, right_meta,
|
||||
)?,
|
||||
}
|
||||
|
||||
parser.typifier_grow(self, left, left_meta)?;
|
||||
parser.typifier_grow(self, right, right_meta)?;
|
||||
frontend.typifier_grow(self, left, left_meta)?;
|
||||
frontend.typifier_grow(self, right, right_meta)?;
|
||||
|
||||
let left_inner = self.typifier.get(left, &parser.module.types);
|
||||
let right_inner = self.typifier.get(right, &parser.module.types);
|
||||
let left_inner = self.typifier.get(left, &frontend.module.types);
|
||||
let right_inner = self.typifier.get(right, &frontend.module.types);
|
||||
|
||||
match (left_inner, right_inner) {
|
||||
(
|
||||
@@ -588,7 +594,7 @@ impl Context {
|
||||
|
||||
// Check that the two arguments have the same dimensions
|
||||
if !dimensions_ok || left_width != right_width {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
format!(
|
||||
"Cannot apply operation to {left_inner:?} and {right_inner:?}"
|
||||
@@ -634,7 +640,7 @@ impl Context {
|
||||
// Rebuild the matrix from the divided vectors
|
||||
self.expressions.append(
|
||||
Expression::Compose {
|
||||
ty: parser.module.types.insert(
|
||||
ty: frontend.module.types.insert(
|
||||
Type {
|
||||
name: None,
|
||||
inner: TypeInner::Matrix {
|
||||
@@ -819,7 +825,7 @@ impl Context {
|
||||
) => {
|
||||
// Check that the two arguments have the same width
|
||||
if left_width != right_width {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
format!(
|
||||
"Cannot apply operation to {left_inner:?} and {right_inner:?}"
|
||||
@@ -874,7 +880,7 @@ impl Context {
|
||||
// Rebuild the matrix from the operation result vectors
|
||||
self.expressions.append(
|
||||
Expression::Compose {
|
||||
ty: parser.module.types.insert(
|
||||
ty: frontend.module.types.insert(
|
||||
Type {
|
||||
name: None,
|
||||
inner: TypeInner::Matrix {
|
||||
@@ -909,7 +915,7 @@ impl Context {
|
||||
) => {
|
||||
// Check that the two arguments have the same width
|
||||
if left_width != right_width {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
format!(
|
||||
"Cannot apply operation to {left_inner:?} and {right_inner:?}"
|
||||
@@ -965,7 +971,7 @@ impl Context {
|
||||
// Rebuild the matrix from the operation result vectors
|
||||
self.expressions.append(
|
||||
Expression::Compose {
|
||||
ty: parser.module.types.insert(
|
||||
ty: frontend.module.types.insert(
|
||||
Type {
|
||||
name: None,
|
||||
inner: TypeInner::Matrix {
|
||||
@@ -993,7 +999,7 @@ impl Context {
|
||||
}
|
||||
HirExprKind::Unary { op, expr } if pos != ExprPos::Lhs => {
|
||||
let expr = self
|
||||
.lower_expect_inner(stmt, parser, expr, ExprPos::Rhs, body)?
|
||||
.lower_expect_inner(stmt, frontend, expr, ExprPos::Rhs, body)?
|
||||
.0;
|
||||
|
||||
self.add_expression(Expression::Unary { op, expr }, meta, body)
|
||||
@@ -1001,7 +1007,7 @@ impl Context {
|
||||
HirExprKind::Variable(ref var) => match pos {
|
||||
ExprPos::Lhs => {
|
||||
if !var.mutable {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
"Variable cannot be used in LHS position".into(),
|
||||
),
|
||||
@@ -1044,7 +1050,7 @@ impl Context {
|
||||
_ => var.expr,
|
||||
},
|
||||
HirExprKind::Call(ref call) if pos != ExprPos::Lhs => {
|
||||
let maybe_expr = parser.function_or_constructor_call(
|
||||
let maybe_expr = frontend.function_or_constructor_call(
|
||||
self,
|
||||
stmt,
|
||||
body,
|
||||
@@ -1080,7 +1086,7 @@ impl Context {
|
||||
|
||||
// Lower the condition first to the current bodyy
|
||||
let condition = self
|
||||
.lower_expect_inner(stmt, parser, condition, ExprPos::Rhs, body)?
|
||||
.lower_expect_inner(stmt, frontend, condition, ExprPos::Rhs, body)?
|
||||
.0;
|
||||
|
||||
// Emit all expressions since we will be adding statements to
|
||||
@@ -1093,7 +1099,7 @@ impl Context {
|
||||
|
||||
// Lower the `true` branch
|
||||
let (mut accept, accept_meta) =
|
||||
self.lower_expect_inner(stmt, parser, accept, pos, &mut accept_body)?;
|
||||
self.lower_expect_inner(stmt, frontend, accept, pos, &mut accept_body)?;
|
||||
|
||||
// Flush the body of the `true` branch, to start emitting on the
|
||||
// `false` branch
|
||||
@@ -1101,7 +1107,7 @@ impl Context {
|
||||
|
||||
// Lower the `false` branch
|
||||
let (mut reject, reject_meta) =
|
||||
self.lower_expect_inner(stmt, parser, reject, pos, &mut reject_body)?;
|
||||
self.lower_expect_inner(stmt, frontend, reject, pos, &mut reject_body)?;
|
||||
|
||||
// Flush the body of the `false` branch
|
||||
self.emit_restart(&mut reject_body);
|
||||
@@ -1113,9 +1119,9 @@ impl Context {
|
||||
Some((reject_power, reject_width, reject_kind)),
|
||||
) = (
|
||||
// Get the components of both branches and calculate the type power
|
||||
self.expr_scalar_components(parser, accept, accept_meta)?
|
||||
self.expr_scalar_components(frontend, accept, accept_meta)?
|
||||
.and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))),
|
||||
self.expr_scalar_components(parser, reject, reject_meta)?
|
||||
self.expr_scalar_components(frontend, reject, reject_meta)?
|
||||
.and_then(|(kind, width)| Some((type_power(kind, width)?, width, kind))),
|
||||
) {
|
||||
match accept_power.cmp(&reject_power) {
|
||||
@@ -1146,7 +1152,7 @@ impl Context {
|
||||
// We need to get the type of the resulting expression to create the local,
|
||||
// this must be done after implicit conversions to ensure both branches have
|
||||
// the same type.
|
||||
let ty = parser.resolve_type_handle(self, accept, accept_meta)?;
|
||||
let ty = frontend.resolve_type_handle(self, accept, accept_meta)?;
|
||||
|
||||
// Add the local that will hold the result of our conditional
|
||||
let local = self.locals.append(
|
||||
@@ -1205,17 +1211,17 @@ impl Context {
|
||||
}
|
||||
HirExprKind::Assign { tgt, value } if ExprPos::Lhs != pos => {
|
||||
let (pointer, ptr_meta) =
|
||||
self.lower_expect_inner(stmt, parser, tgt, ExprPos::Lhs, body)?;
|
||||
self.lower_expect_inner(stmt, frontend, tgt, ExprPos::Lhs, body)?;
|
||||
let (mut value, value_meta) =
|
||||
self.lower_expect_inner(stmt, parser, value, ExprPos::Rhs, body)?;
|
||||
self.lower_expect_inner(stmt, frontend, value, ExprPos::Rhs, body)?;
|
||||
|
||||
let ty = match *parser.resolve_type(self, pointer, ptr_meta)? {
|
||||
TypeInner::Pointer { base, .. } => &parser.module.types[base].inner,
|
||||
let ty = match *frontend.resolve_type(self, pointer, ptr_meta)? {
|
||||
TypeInner::Pointer { base, .. } => &frontend.module.types[base].inner,
|
||||
ref ty => ty,
|
||||
};
|
||||
|
||||
if let Some((kind, width)) = scalar_components(ty) {
|
||||
self.implicit_conversion(parser, &mut value, value_meta, kind, width)?;
|
||||
self.implicit_conversion(frontend, &mut value, value_meta, kind, width)?;
|
||||
}
|
||||
|
||||
self.lower_store(pointer, value, meta, body);
|
||||
@@ -1224,7 +1230,7 @@ impl Context {
|
||||
}
|
||||
HirExprKind::PrePostfix { op, postfix, expr } if ExprPos::Lhs != pos => {
|
||||
let (pointer, _) =
|
||||
self.lower_expect_inner(stmt, parser, expr, ExprPos::Lhs, body)?;
|
||||
self.lower_expect_inner(stmt, frontend, expr, ExprPos::Lhs, body)?;
|
||||
let left = if let Expression::Swizzle { .. } = self.expressions[pointer] {
|
||||
pointer
|
||||
} else {
|
||||
@@ -1241,7 +1247,7 @@ impl Context {
|
||||
|
||||
Some(crate::ConstantInner::Scalar { width, value })
|
||||
};
|
||||
let res = match *parser.resolve_type(self, left, meta)? {
|
||||
let res = match *frontend.resolve_type(self, left, meta)? {
|
||||
TypeInner::Scalar { kind, width } => {
|
||||
let ty = TypeInner::Scalar { kind, width };
|
||||
make_constant_inner(kind, width).map(|i| (ty, i, None, None))
|
||||
@@ -1268,7 +1274,7 @@ impl Context {
|
||||
let (ty_inner, inner, rows, columns) = match res {
|
||||
Some(res) => res,
|
||||
None => {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
"Increment/decrement only works on scalar/vector/matrix".into(),
|
||||
),
|
||||
@@ -1278,7 +1284,7 @@ impl Context {
|
||||
}
|
||||
};
|
||||
|
||||
let constant_1 = parser.module.constants.append(
|
||||
let constant_1 = frontend.module.constants.append(
|
||||
Constant {
|
||||
name: None,
|
||||
specialization: None,
|
||||
@@ -1297,7 +1303,7 @@ impl Context {
|
||||
self.add_expression(Expression::Splat { size, value: right }, meta, body);
|
||||
|
||||
if let Some(cols) = columns {
|
||||
let ty = parser.module.types.insert(
|
||||
let ty = frontend.module.types.insert(
|
||||
Type {
|
||||
name: None,
|
||||
inner: ty_inner,
|
||||
@@ -1333,21 +1339,22 @@ impl Context {
|
||||
} if ExprPos::Lhs != pos => {
|
||||
let args = args
|
||||
.iter()
|
||||
.map(|e| self.lower_expect_inner(stmt, parser, *e, ExprPos::Rhs, body))
|
||||
.map(|e| self.lower_expect_inner(stmt, frontend, *e, ExprPos::Rhs, body))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
match name.as_ref() {
|
||||
"length" => {
|
||||
if !args.is_empty() {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
".length() doesn't take any arguments".into(),
|
||||
),
|
||||
meta,
|
||||
});
|
||||
}
|
||||
let lowered_array =
|
||||
self.lower_expect_inner(stmt, parser, object, pos, body)?.0;
|
||||
let array_type = parser.resolve_type(self, lowered_array, meta)?;
|
||||
let lowered_array = self
|
||||
.lower_expect_inner(stmt, frontend, object, pos, body)?
|
||||
.0;
|
||||
let array_type = frontend.resolve_type(self, lowered_array, meta)?;
|
||||
|
||||
match *array_type {
|
||||
TypeInner::Array {
|
||||
@@ -1357,7 +1364,7 @@ impl Context {
|
||||
let mut array_length =
|
||||
self.add_expression(Expression::Constant(size), meta, body);
|
||||
self.forced_conversion(
|
||||
parser,
|
||||
frontend,
|
||||
&mut array_length,
|
||||
meta,
|
||||
ScalarKind::Sint,
|
||||
@@ -1411,22 +1418,22 @@ impl Context {
|
||||
|
||||
pub fn expr_scalar_components(
|
||||
&mut self,
|
||||
parser: &Parser,
|
||||
frontend: &Frontend,
|
||||
expr: Handle<Expression>,
|
||||
meta: Span,
|
||||
) -> Result<Option<(ScalarKind, crate::Bytes)>> {
|
||||
let ty = parser.resolve_type(self, expr, meta)?;
|
||||
let ty = frontend.resolve_type(self, expr, meta)?;
|
||||
Ok(scalar_components(ty))
|
||||
}
|
||||
|
||||
pub fn expr_power(
|
||||
&mut self,
|
||||
parser: &Parser,
|
||||
frontend: &Frontend,
|
||||
expr: Handle<Expression>,
|
||||
meta: Span,
|
||||
) -> Result<Option<u32>> {
|
||||
Ok(self
|
||||
.expr_scalar_components(parser, expr, meta)?
|
||||
.expr_scalar_components(frontend, expr, meta)?
|
||||
.and_then(|(kind, width)| type_power(kind, width)))
|
||||
}
|
||||
|
||||
@@ -1451,7 +1458,7 @@ impl Context {
|
||||
|
||||
pub fn implicit_conversion(
|
||||
&mut self,
|
||||
parser: &Parser,
|
||||
frontend: &Frontend,
|
||||
expr: &mut Handle<Expression>,
|
||||
meta: Span,
|
||||
kind: ScalarKind,
|
||||
@@ -1459,7 +1466,7 @@ impl Context {
|
||||
) -> Result<()> {
|
||||
if let (Some(tgt_power), Some(expr_power)) = (
|
||||
type_power(kind, width),
|
||||
self.expr_power(parser, *expr, meta)?,
|
||||
self.expr_power(frontend, *expr, meta)?,
|
||||
) {
|
||||
if tgt_power > expr_power {
|
||||
self.conversion(expr, meta, kind, width)?;
|
||||
@@ -1471,14 +1478,14 @@ impl Context {
|
||||
|
||||
pub fn forced_conversion(
|
||||
&mut self,
|
||||
parser: &Parser,
|
||||
frontend: &Frontend,
|
||||
expr: &mut Handle<Expression>,
|
||||
meta: Span,
|
||||
kind: ScalarKind,
|
||||
width: crate::Bytes,
|
||||
) -> Result<()> {
|
||||
if let Some((expr_scalar_kind, expr_width)) =
|
||||
self.expr_scalar_components(parser, *expr, meta)?
|
||||
self.expr_scalar_components(frontend, *expr, meta)?
|
||||
{
|
||||
if expr_scalar_kind != kind || expr_width != width {
|
||||
self.conversion(expr, meta, kind, width)?;
|
||||
@@ -1490,14 +1497,14 @@ impl Context {
|
||||
|
||||
pub fn binary_implicit_conversion(
|
||||
&mut self,
|
||||
parser: &Parser,
|
||||
frontend: &Frontend,
|
||||
left: &mut Handle<Expression>,
|
||||
left_meta: Span,
|
||||
right: &mut Handle<Expression>,
|
||||
right_meta: Span,
|
||||
) -> Result<()> {
|
||||
let left_components = self.expr_scalar_components(parser, *left, left_meta)?;
|
||||
let right_components = self.expr_scalar_components(parser, *right, right_meta)?;
|
||||
let left_components = self.expr_scalar_components(frontend, *left, left_meta)?;
|
||||
let right_components = self.expr_scalar_components(frontend, *right, right_meta)?;
|
||||
|
||||
if let (
|
||||
Some((left_power, left_width, left_kind)),
|
||||
@@ -1523,12 +1530,12 @@ impl Context {
|
||||
|
||||
pub fn implicit_splat(
|
||||
&mut self,
|
||||
parser: &Parser,
|
||||
frontend: &Frontend,
|
||||
expr: &mut Handle<Expression>,
|
||||
meta: Span,
|
||||
vector_size: Option<VectorSize>,
|
||||
) -> Result<()> {
|
||||
let expr_type = parser.resolve_type(self, *expr, meta)?;
|
||||
let expr_type = frontend.resolve_type(self, *expr, meta)?;
|
||||
|
||||
if let (&TypeInner::Scalar { .. }, Some(size)) = (expr_type, vector_size) {
|
||||
*expr = self
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::{
|
||||
context::{Context, ExprPos, StmtContext},
|
||||
error::{Error, ErrorKind},
|
||||
types::scalar_components,
|
||||
Parser, Result,
|
||||
Frontend, Result,
|
||||
};
|
||||
use crate::{
|
||||
front::glsl::types::type_power, proc::ensure_block_returns, AddressSpace, Arena, Block,
|
||||
@@ -14,7 +14,7 @@ use crate::{
|
||||
};
|
||||
use std::iter;
|
||||
|
||||
impl Parser {
|
||||
impl Frontend {
|
||||
fn add_constant_value(
|
||||
&mut self,
|
||||
scalar_kind: ScalarKind,
|
||||
@@ -1032,7 +1032,7 @@ impl Parser {
|
||||
|
||||
let void = result.is_none();
|
||||
|
||||
let &mut Parser {
|
||||
let &mut Frontend {
|
||||
ref mut lookup_function,
|
||||
ref mut module,
|
||||
..
|
||||
@@ -1121,7 +1121,7 @@ impl Parser {
|
||||
) {
|
||||
let void = result.is_none();
|
||||
|
||||
let &mut Parser {
|
||||
let &mut Frontend {
|
||||
ref mut lookup_function,
|
||||
ref mut module,
|
||||
..
|
||||
|
||||
+18
-18
@@ -1,7 +1,7 @@
|
||||
/*!
|
||||
Frontend for [GLSL][glsl] (OpenGL Shading Language).
|
||||
|
||||
To begin, take a look at the documentation for the [`Parser`](Parser).
|
||||
To begin, take a look at the documentation for the [`Frontend`].
|
||||
|
||||
# Supported versions
|
||||
## Vulkan
|
||||
@@ -37,7 +37,7 @@ mod variables;
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Per-shader options passed to [`parse`](Parser::parse).
|
||||
/// Per-shader options passed to [`parse`](Frontend::parse).
|
||||
///
|
||||
/// The [`From`](From) trait is implemented for [`ShaderStage`](ShaderStage) to
|
||||
/// provide a quick way to create a Options instance.
|
||||
@@ -79,7 +79,7 @@ pub struct ShaderMetadata {
|
||||
/// The GLSL profile specified in the shader trough the use of the
|
||||
/// `#version` preprocessor directive.
|
||||
pub profile: Profile,
|
||||
/// The shader stage in the pipeline, passed to the [`parse`](Parser::parse)
|
||||
/// The shader stage in the pipeline, passed to the [`parse`](Frontend::parse)
|
||||
/// method via the [`Options`](Options) struct.
|
||||
pub stage: ShaderStage,
|
||||
|
||||
@@ -124,16 +124,16 @@ impl Default for ShaderMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `Parser` is the central structure of the GLSL frontend.
|
||||
/// The `Frontend` is the central structure of the GLSL frontend.
|
||||
///
|
||||
/// To instantiate a new `Parser` the [`Default`](Default) trait is used, so a
|
||||
/// call to the associated function [`Parser::default`](Parser::default) will
|
||||
/// return a new `Parser` instance.
|
||||
/// To instantiate a new `Frontend` the [`Default`](Default) trait is used, so a
|
||||
/// call to the associated function [`Frontend::default`](Frontend::default) will
|
||||
/// return a new `Frontend` instance.
|
||||
///
|
||||
/// To parse a shader simply call the [`parse`](Parser::parse) method with a
|
||||
/// To parse a shader simply call the [`parse`](Frontend::parse) method with a
|
||||
/// [`Options`](Options) struct and a [`&str`](str) holding the glsl code.
|
||||
///
|
||||
/// The `Parser` also provides the [`metadata`](Parser::metadata) to get some
|
||||
/// The `Frontend` also provides the [`metadata`](Frontend::metadata) to get some
|
||||
/// further information about the previously parsed shader, like version and
|
||||
/// extensions used (see the documentation for
|
||||
/// [`ShaderMetadata`](ShaderMetadata) to see all the returned information)
|
||||
@@ -141,7 +141,7 @@ impl Default for ShaderMetadata {
|
||||
/// # Example usage
|
||||
/// ```rust
|
||||
/// use naga::ShaderStage;
|
||||
/// use naga::front::glsl::{Parser, Options};
|
||||
/// use naga::front::glsl::{Frontend, Options};
|
||||
///
|
||||
/// let glsl = r#"
|
||||
/// #version 450 core
|
||||
@@ -149,20 +149,20 @@ impl Default for ShaderMetadata {
|
||||
/// void main() {}
|
||||
/// "#;
|
||||
///
|
||||
/// let mut parser = Parser::default();
|
||||
/// let mut frontend = Frontend::default();
|
||||
/// let options = Options::from(ShaderStage::Vertex);
|
||||
/// parser.parse(&options, glsl);
|
||||
/// frontend.parse(&options, glsl);
|
||||
/// ```
|
||||
///
|
||||
/// # Reusability
|
||||
///
|
||||
/// If there's a need to parse more than one shader reusing the same `Parser`
|
||||
/// If there's a need to parse more than one shader reusing the same `Frontend`
|
||||
/// instance may be beneficial since internal allocations will be reused.
|
||||
///
|
||||
/// Calling the [`parse`](Parser::parse) method multiple times will reset the
|
||||
/// `Parser` so no extra care is needed when reusing.
|
||||
/// Calling the [`parse`](Frontend::parse) method multiple times will reset the
|
||||
/// `Frontend` so no extra care is needed when reusing.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Parser {
|
||||
pub struct Frontend {
|
||||
meta: ShaderMetadata,
|
||||
|
||||
lookup_function: FastHashMap<String, FunctionDeclaration>,
|
||||
@@ -179,7 +179,7 @@ pub struct Parser {
|
||||
module: Module,
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
impl Frontend {
|
||||
fn reset(&mut self, stage: ShaderStage) {
|
||||
self.meta.reset(stage);
|
||||
|
||||
@@ -197,7 +197,7 @@ impl Parser {
|
||||
/// Parses a shader either outputting a shader [`Module`](Module) or a list
|
||||
/// of [`Error`](Error)s.
|
||||
///
|
||||
/// Multiple calls using the same `Parser` and different shaders are supported.
|
||||
/// Multiple calls using the same `Frontend` and different shaders are supported.
|
||||
pub fn parse(
|
||||
&mut self,
|
||||
options: &Options,
|
||||
|
||||
+36
-36
@@ -7,7 +7,7 @@ use super::{
|
||||
token::{Directive, DirectiveKind},
|
||||
token::{Token, TokenValue},
|
||||
variables::{GlobalOrConstant, VarDeclaration},
|
||||
Parser, Result,
|
||||
Frontend, Result,
|
||||
};
|
||||
use crate::{arena::Handle, Block, Constant, ConstantInner, Expression, ScalarValue, Span, Type};
|
||||
use core::convert::TryFrom;
|
||||
@@ -56,8 +56,8 @@ impl<'source> ParsingContext<'source> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn expect_ident(&mut self, parser: &mut Parser) -> Result<(String, Span)> {
|
||||
let token = self.bump(parser)?;
|
||||
pub fn expect_ident(&mut self, frontend: &mut Frontend) -> Result<(String, Span)> {
|
||||
let token = self.bump(frontend)?;
|
||||
|
||||
match token.value {
|
||||
TokenValue::Identifier(name) => Ok((name, token.meta)),
|
||||
@@ -68,8 +68,8 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expect(&mut self, parser: &mut Parser, value: TokenValue) -> Result<Token> {
|
||||
let token = self.bump(parser)?;
|
||||
pub fn expect(&mut self, frontend: &mut Frontend, value: TokenValue) -> Result<Token> {
|
||||
let token = self.bump(frontend)?;
|
||||
|
||||
if token.value != value {
|
||||
Err(Error {
|
||||
@@ -81,7 +81,7 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next(&mut self, parser: &mut Parser) -> Option<Token> {
|
||||
pub fn next(&mut self, frontend: &mut Frontend) -> Option<Token> {
|
||||
loop {
|
||||
if let Some(token) = self.backtracked_token.take() {
|
||||
self.last_meta = token.meta;
|
||||
@@ -96,9 +96,9 @@ impl<'source> ParsingContext<'source> {
|
||||
break Some(token);
|
||||
}
|
||||
LexerResultKind::Directive(directive) => {
|
||||
parser.handle_directive(directive, res.meta)
|
||||
frontend.handle_directive(directive, res.meta)
|
||||
}
|
||||
LexerResultKind::Error(error) => parser.errors.push(Error {
|
||||
LexerResultKind::Error(error) => frontend.errors.push(Error {
|
||||
kind: ErrorKind::PreprocessorError(error),
|
||||
meta: res.meta,
|
||||
}),
|
||||
@@ -106,23 +106,23 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bump(&mut self, parser: &mut Parser) -> Result<Token> {
|
||||
self.next(parser).ok_or(Error {
|
||||
pub fn bump(&mut self, frontend: &mut Frontend) -> Result<Token> {
|
||||
self.next(frontend).ok_or(Error {
|
||||
kind: ErrorKind::EndOfFile,
|
||||
meta: self.last_meta,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns None on the end of the file rather than an error like other methods
|
||||
pub fn bump_if(&mut self, parser: &mut Parser, value: TokenValue) -> Option<Token> {
|
||||
if self.peek(parser).filter(|t| t.value == value).is_some() {
|
||||
self.bump(parser).ok()
|
||||
pub fn bump_if(&mut self, frontend: &mut Frontend, value: TokenValue) -> Option<Token> {
|
||||
if self.peek(frontend).filter(|t| t.value == value).is_some() {
|
||||
self.bump(frontend).ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn peek(&mut self, parser: &mut Parser) -> Option<&Token> {
|
||||
pub fn peek(&mut self, frontend: &mut Frontend) -> Option<&Token> {
|
||||
loop {
|
||||
if let Some(ref token) = self.backtracked_token {
|
||||
break Some(token);
|
||||
@@ -142,9 +142,9 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
match res.kind {
|
||||
LexerResultKind::Directive(directive) => {
|
||||
parser.handle_directive(directive, res.meta)
|
||||
frontend.handle_directive(directive, res.meta)
|
||||
}
|
||||
LexerResultKind::Error(error) => parser.errors.push(Error {
|
||||
LexerResultKind::Error(error) => frontend.errors.push(Error {
|
||||
kind: ErrorKind::PreprocessorError(error),
|
||||
meta: res.meta,
|
||||
}),
|
||||
@@ -155,30 +155,30 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expect_peek(&mut self, parser: &mut Parser) -> Result<&Token> {
|
||||
pub fn expect_peek(&mut self, frontend: &mut Frontend) -> Result<&Token> {
|
||||
let meta = self.last_meta;
|
||||
self.peek(parser).ok_or(Error {
|
||||
self.peek(frontend).ok_or(Error {
|
||||
kind: ErrorKind::EndOfFile,
|
||||
meta,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse(&mut self, parser: &mut Parser) -> Result<()> {
|
||||
pub fn parse(&mut self, frontend: &mut Frontend) -> Result<()> {
|
||||
// Body and expression arena for global initialization
|
||||
let mut body = Block::new();
|
||||
let mut ctx = Context::new(parser, &mut body);
|
||||
let mut ctx = Context::new(frontend, &mut body);
|
||||
|
||||
while self.peek(parser).is_some() {
|
||||
self.parse_external_declaration(parser, &mut ctx, &mut body)?;
|
||||
while self.peek(frontend).is_some() {
|
||||
self.parse_external_declaration(frontend, &mut ctx, &mut body)?;
|
||||
}
|
||||
|
||||
// Add an `EntryPoint` to `parser.module` for `main`, if a
|
||||
// suitable overload exists. Error out if we can't find one.
|
||||
if let Some(declaration) = parser.lookup_function.get("main") {
|
||||
if let Some(declaration) = frontend.lookup_function.get("main") {
|
||||
for decl in declaration.overloads.iter() {
|
||||
if let FunctionKind::Call(handle) = decl.kind {
|
||||
if decl.defined && decl.parameters.is_empty() {
|
||||
parser.add_entry_point(handle, body, ctx.expressions);
|
||||
frontend.add_entry_point(handle, body, ctx.expressions);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
@@ -191,10 +191,10 @@ impl<'source> ParsingContext<'source> {
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_uint_constant(&mut self, parser: &mut Parser) -> Result<(u32, Span)> {
|
||||
let (value, meta) = self.parse_constant_expression(parser)?;
|
||||
fn parse_uint_constant(&mut self, frontend: &mut Frontend) -> Result<(u32, Span)> {
|
||||
let (value, meta) = self.parse_constant_expression(frontend)?;
|
||||
|
||||
let int = match parser.module.constants[value].inner {
|
||||
let int = match frontend.module.constants[value].inner {
|
||||
ConstantInner::Scalar {
|
||||
value: ScalarValue::Uint(int),
|
||||
..
|
||||
@@ -222,21 +222,21 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
fn parse_constant_expression(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
) -> Result<(Handle<Constant>, Span)> {
|
||||
let mut block = Block::new();
|
||||
|
||||
let mut ctx = Context::new(parser, &mut block);
|
||||
let mut ctx = Context::new(frontend, &mut block);
|
||||
|
||||
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, ExprPos::Rhs, &mut block)?;
|
||||
let expr = self.parse_conditional(frontend, &mut ctx, &mut stmt_ctx, &mut block, None)?;
|
||||
let (root, meta) = ctx.lower_expect(stmt_ctx, frontend, expr, ExprPos::Rhs, &mut block)?;
|
||||
|
||||
Ok((parser.solve_constant(&ctx, root, meta)?, meta))
|
||||
Ok((frontend.solve_constant(&ctx, root, meta)?, meta))
|
||||
}
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
impl Frontend {
|
||||
fn handle_directive(&mut self, directive: Directive, meta: Span) {
|
||||
let mut tokens = directive.tokens.into_iter();
|
||||
|
||||
@@ -409,7 +409,7 @@ pub struct DeclarationContext<'ctx, 'qualifiers> {
|
||||
impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> {
|
||||
fn add_var(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ty: Handle<Type>,
|
||||
name: String,
|
||||
init: Option<Handle<Constant>>,
|
||||
@@ -425,14 +425,14 @@ impl<'ctx, 'qualifiers> DeclarationContext<'ctx, 'qualifiers> {
|
||||
|
||||
match self.external {
|
||||
true => {
|
||||
let global = parser.add_global_var(self.ctx, self.body, decl)?;
|
||||
let global = frontend.add_global_var(self.ctx, self.body, decl)?;
|
||||
let expr = match global {
|
||||
GlobalOrConstant::Global(handle) => Expression::GlobalVariable(handle),
|
||||
GlobalOrConstant::Constant(handle) => Expression::Constant(handle),
|
||||
};
|
||||
Ok(self.ctx.add_expression(expr, meta, self.body))
|
||||
}
|
||||
false => parser.add_local_var(self.ctx, self.body, decl),
|
||||
false => frontend.add_local_var(self.ctx, self.body, decl),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::{
|
||||
token::{Token, TokenValue},
|
||||
types::scalar_components,
|
||||
variables::{GlobalOrConstant, VarDeclaration},
|
||||
Error, ErrorKind, Parser, Span,
|
||||
Error, ErrorKind, Frontend, Span,
|
||||
},
|
||||
proc::Alignment,
|
||||
AddressSpace, Block, Expression, FunctionResult, Handle, ScalarKind, Statement, StructMember,
|
||||
@@ -71,19 +71,19 @@ fn element_or_member_type(
|
||||
impl<'source> ParsingContext<'source> {
|
||||
pub fn parse_external_declaration(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
global_ctx: &mut Context,
|
||||
global_body: &mut Block,
|
||||
) -> Result<()> {
|
||||
if self
|
||||
.parse_declaration(parser, global_ctx, global_body, true)?
|
||||
.parse_declaration(frontend, global_ctx, global_body, true)?
|
||||
.is_none()
|
||||
{
|
||||
let token = self.bump(parser)?;
|
||||
let token = self.bump(frontend)?;
|
||||
match token.value {
|
||||
TokenValue::Semicolon if parser.meta.version == 460 => Ok(()),
|
||||
TokenValue::Semicolon if frontend.meta.version == 460 => Ok(()),
|
||||
_ => {
|
||||
let expected = match parser.meta.version {
|
||||
let expected = match frontend.meta.version {
|
||||
460 => vec![TokenValue::Semicolon.into(), ExpectedToken::Eof],
|
||||
_ => vec![ExpectedToken::Eof],
|
||||
};
|
||||
@@ -100,7 +100,7 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
pub fn parse_initializer(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ty: Handle<Type>,
|
||||
ctx: &mut Context,
|
||||
body: &mut Block,
|
||||
@@ -113,20 +113,21 @@ impl<'source> ParsingContext<'source> {
|
||||
// initializer_list:
|
||||
// initializer
|
||||
// initializer_list COMMA initializer
|
||||
if let Some(Token { mut meta, .. }) = self.bump_if(parser, TokenValue::LeftBrace) {
|
||||
if let Some(Token { mut meta, .. }) = self.bump_if(frontend, TokenValue::LeftBrace) {
|
||||
// initializer_list
|
||||
let mut components = Vec::new();
|
||||
loop {
|
||||
// The type expected to be parsed inside the initializer list
|
||||
let new_ty = element_or_member_type(ty, components.len(), &mut parser.module.types);
|
||||
let new_ty =
|
||||
element_or_member_type(ty, components.len(), &mut frontend.module.types);
|
||||
|
||||
components.push(self.parse_initializer(parser, new_ty, ctx, body)?.0);
|
||||
components.push(self.parse_initializer(frontend, new_ty, ctx, body)?.0);
|
||||
|
||||
let token = self.bump(parser)?;
|
||||
let token = self.bump(frontend)?;
|
||||
match token.value {
|
||||
TokenValue::Comma => {
|
||||
if let Some(Token { meta: end_meta, .. }) =
|
||||
self.bump_if(parser, TokenValue::RightBrace)
|
||||
self.bump_if(frontend, TokenValue::RightBrace)
|
||||
{
|
||||
meta.subsume(end_meta);
|
||||
break;
|
||||
@@ -154,12 +155,13 @@ 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, ExprPos::Rhs, body)?;
|
||||
let expr = self.parse_assignment(frontend, ctx, &mut stmt, body)?;
|
||||
let (mut init, init_meta) =
|
||||
ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?;
|
||||
|
||||
let scalar_components = scalar_components(&parser.module.types[ty].inner);
|
||||
let scalar_components = scalar_components(&frontend.module.types[ty].inner);
|
||||
if let Some((kind, width)) = scalar_components {
|
||||
ctx.implicit_conversion(parser, &mut init, init_meta, kind, width)?;
|
||||
ctx.implicit_conversion(frontend, &mut init, init_meta, kind, width)?;
|
||||
}
|
||||
|
||||
Ok((init, init_meta))
|
||||
@@ -171,7 +173,7 @@ impl<'source> ParsingContext<'source> {
|
||||
// produced Error::InvalidToken if it isn't consumed
|
||||
pub fn parse_init_declarator_list(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
mut ty: Handle<Type>,
|
||||
ctx: &mut DeclarationContext,
|
||||
) -> Result<()> {
|
||||
@@ -191,14 +193,14 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
// Consume any leading comma, e.g. this is valid: `float, a=1;`
|
||||
if self
|
||||
.peek(parser)
|
||||
.peek(frontend)
|
||||
.map_or(false, |t| t.value == TokenValue::Comma)
|
||||
{
|
||||
self.next(parser);
|
||||
self.next(frontend);
|
||||
}
|
||||
|
||||
loop {
|
||||
let token = self.bump(parser)?;
|
||||
let token = self.bump(frontend)?;
|
||||
let name = match token.value {
|
||||
TokenValue::Semicolon => break,
|
||||
TokenValue::Identifier(name) => name,
|
||||
@@ -221,18 +223,18 @@ impl<'source> ParsingContext<'source> {
|
||||
// parse an array specifier if it exists
|
||||
// NOTE: unlike other parse methods this one doesn't expect an array specifier and
|
||||
// returns Ok(None) rather than an error if there is not one
|
||||
self.parse_array_specifier(parser, &mut meta, &mut ty)?;
|
||||
self.parse_array_specifier(frontend, &mut meta, &mut ty)?;
|
||||
|
||||
let init = self
|
||||
.bump_if(parser, TokenValue::Assign)
|
||||
.bump_if(frontend, TokenValue::Assign)
|
||||
.map::<Result<_>, _>(|_| {
|
||||
let (mut expr, init_meta) =
|
||||
self.parse_initializer(parser, ty, ctx.ctx, ctx.body)?;
|
||||
self.parse_initializer(frontend, ty, ctx.ctx, ctx.body)?;
|
||||
|
||||
let scalar_components = scalar_components(&parser.module.types[ty].inner);
|
||||
let scalar_components = scalar_components(&frontend.module.types[ty].inner);
|
||||
if let Some((kind, width)) = scalar_components {
|
||||
ctx.ctx
|
||||
.implicit_conversion(parser, &mut expr, init_meta, kind, width)?;
|
||||
.implicit_conversion(frontend, &mut expr, init_meta, kind, width)?;
|
||||
}
|
||||
|
||||
meta.subsume(init_meta);
|
||||
@@ -244,7 +246,7 @@ impl<'source> ParsingContext<'source> {
|
||||
let is_const = ctx.qualifiers.storage.0 == StorageQualifier::Const;
|
||||
let maybe_constant = if ctx.external {
|
||||
if let Some((root, meta)) = init {
|
||||
match parser.solve_constant(ctx.ctx, root, meta) {
|
||||
match frontend.solve_constant(ctx.ctx, root, meta) {
|
||||
Ok(res) => Some(res),
|
||||
// If the declaration is external (global scope) and is constant qualified
|
||||
// then the initializer must be a constant expression
|
||||
@@ -258,14 +260,14 @@ impl<'source> ParsingContext<'source> {
|
||||
None
|
||||
};
|
||||
|
||||
let pointer = ctx.add_var(parser, ty, name, maybe_constant, meta)?;
|
||||
let pointer = ctx.add_var(frontend, ty, name, maybe_constant, meta)?;
|
||||
|
||||
if let Some((value, _)) = init.filter(|_| maybe_constant.is_none()) {
|
||||
ctx.flush_expressions();
|
||||
ctx.body.push(Statement::Store { pointer, value }, meta);
|
||||
}
|
||||
|
||||
let token = self.bump(parser)?;
|
||||
let token = self.bump(frontend)?;
|
||||
match token.value {
|
||||
TokenValue::Semicolon => break,
|
||||
TokenValue::Comma => {}
|
||||
@@ -287,7 +289,7 @@ impl<'source> ParsingContext<'source> {
|
||||
/// `external` whether or not we are in a global or local context
|
||||
pub fn parse_declaration(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
body: &mut Block,
|
||||
external: bool,
|
||||
@@ -304,36 +306,36 @@ impl<'source> ParsingContext<'source> {
|
||||
// type_qualifier SEMICOLON type_qualifier IDENTIFIER SEMICOLON
|
||||
// type_qualifier IDENTIFIER identifier_list SEMICOLON
|
||||
|
||||
if self.peek_type_qualifier(parser) || self.peek_type_name(parser) {
|
||||
let mut qualifiers = self.parse_type_qualifiers(parser)?;
|
||||
if self.peek_type_qualifier(frontend) || self.peek_type_name(frontend) {
|
||||
let mut qualifiers = self.parse_type_qualifiers(frontend)?;
|
||||
|
||||
if self.peek_type_name(parser) {
|
||||
if self.peek_type_name(frontend) {
|
||||
// This branch handles variables and function prototypes and if
|
||||
// external is true also function definitions
|
||||
let (ty, mut meta) = self.parse_type(parser)?;
|
||||
let (ty, mut meta) = self.parse_type(frontend)?;
|
||||
|
||||
let token = self.bump(parser)?;
|
||||
let token = self.bump(frontend)?;
|
||||
let token_fallthrough = match token.value {
|
||||
TokenValue::Identifier(name) => match self.expect_peek(parser)?.value {
|
||||
TokenValue::Identifier(name) => match self.expect_peek(frontend)?.value {
|
||||
TokenValue::LeftParen => {
|
||||
// This branch handles function definition and prototypes
|
||||
self.bump(parser)?;
|
||||
self.bump(frontend)?;
|
||||
|
||||
let result = ty.map(|ty| FunctionResult { ty, binding: None });
|
||||
let mut body = Block::new();
|
||||
|
||||
let mut context = Context::new(parser, &mut body);
|
||||
let mut context = Context::new(frontend, &mut body);
|
||||
|
||||
self.parse_function_args(parser, &mut context, &mut body)?;
|
||||
self.parse_function_args(frontend, &mut context, &mut body)?;
|
||||
|
||||
let end_meta = self.expect(parser, TokenValue::RightParen)?.meta;
|
||||
let end_meta = self.expect(frontend, TokenValue::RightParen)?.meta;
|
||||
meta.subsume(end_meta);
|
||||
|
||||
let token = self.bump(parser)?;
|
||||
let token = self.bump(frontend)?;
|
||||
return match token.value {
|
||||
TokenValue::Semicolon => {
|
||||
// This branch handles function prototypes
|
||||
parser.add_prototype(context, name, result, meta);
|
||||
frontend.add_prototype(context, name, result, meta);
|
||||
|
||||
Ok(Some(meta))
|
||||
}
|
||||
@@ -345,13 +347,13 @@ impl<'source> ParsingContext<'source> {
|
||||
// parse the body
|
||||
self.parse_compound_statement(
|
||||
token.meta,
|
||||
parser,
|
||||
frontend,
|
||||
&mut context,
|
||||
&mut body,
|
||||
&mut None,
|
||||
)?;
|
||||
|
||||
parser.add_function(context, name, result, body, meta);
|
||||
frontend.add_function(context, name, result, body, meta);
|
||||
|
||||
Ok(Some(meta))
|
||||
}
|
||||
@@ -396,9 +398,9 @@ impl<'source> ParsingContext<'source> {
|
||||
};
|
||||
|
||||
self.backtrack(token_fallthrough)?;
|
||||
self.parse_init_declarator_list(parser, ty, &mut ctx)?;
|
||||
self.parse_init_declarator_list(frontend, ty, &mut ctx)?;
|
||||
} else {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError("Declaration cannot have void type".into()),
|
||||
meta,
|
||||
})
|
||||
@@ -410,12 +412,12 @@ impl<'source> ParsingContext<'source> {
|
||||
// ```glsl
|
||||
// layout(early_fragment_tests);
|
||||
// ```
|
||||
let token = self.bump(parser)?;
|
||||
let token = self.bump(frontend)?;
|
||||
match token.value {
|
||||
TokenValue::Identifier(ty_name) => {
|
||||
if self.bump_if(parser, TokenValue::LeftBrace).is_some() {
|
||||
if self.bump_if(frontend, TokenValue::LeftBrace).is_some() {
|
||||
self.parse_block_declaration(
|
||||
parser,
|
||||
frontend,
|
||||
ctx,
|
||||
body,
|
||||
&mut qualifiers,
|
||||
@@ -425,10 +427,10 @@ impl<'source> ParsingContext<'source> {
|
||||
.map(Some)
|
||||
} else {
|
||||
if qualifiers.invariant.take().is_some() {
|
||||
parser.make_variable_invariant(ctx, body, &ty_name, token.meta);
|
||||
frontend.make_variable_invariant(ctx, body, &ty_name, token.meta);
|
||||
|
||||
qualifiers.unused_errors(&mut parser.errors);
|
||||
self.expect(parser, TokenValue::Semicolon)?;
|
||||
qualifiers.unused_errors(&mut frontend.errors);
|
||||
self.expect(frontend, TokenValue::Semicolon)?;
|
||||
return Ok(Some(qualifiers.span));
|
||||
}
|
||||
|
||||
@@ -443,25 +445,25 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
TokenValue::Semicolon => {
|
||||
if let Some(value) =
|
||||
qualifiers.uint_layout_qualifier("local_size_x", &mut parser.errors)
|
||||
qualifiers.uint_layout_qualifier("local_size_x", &mut frontend.errors)
|
||||
{
|
||||
parser.meta.workgroup_size[0] = value;
|
||||
frontend.meta.workgroup_size[0] = value;
|
||||
}
|
||||
if let Some(value) =
|
||||
qualifiers.uint_layout_qualifier("local_size_y", &mut parser.errors)
|
||||
qualifiers.uint_layout_qualifier("local_size_y", &mut frontend.errors)
|
||||
{
|
||||
parser.meta.workgroup_size[1] = value;
|
||||
frontend.meta.workgroup_size[1] = value;
|
||||
}
|
||||
if let Some(value) =
|
||||
qualifiers.uint_layout_qualifier("local_size_z", &mut parser.errors)
|
||||
qualifiers.uint_layout_qualifier("local_size_z", &mut frontend.errors)
|
||||
{
|
||||
parser.meta.workgroup_size[2] = value;
|
||||
frontend.meta.workgroup_size[2] = value;
|
||||
}
|
||||
|
||||
parser.meta.early_fragment_tests |= qualifiers
|
||||
.none_layout_qualifier("early_fragment_tests", &mut parser.errors);
|
||||
frontend.meta.early_fragment_tests |= qualifiers
|
||||
.none_layout_qualifier("early_fragment_tests", &mut frontend.errors);
|
||||
|
||||
qualifiers.unused_errors(&mut parser.errors);
|
||||
qualifiers.unused_errors(&mut frontend.errors);
|
||||
|
||||
Ok(Some(qualifiers.span))
|
||||
}
|
||||
@@ -475,12 +477,12 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match self.peek(parser).map(|t| &t.value) {
|
||||
match self.peek(frontend).map(|t| &t.value) {
|
||||
Some(&TokenValue::Precision) => {
|
||||
// PRECISION precision_qualifier type_specifier SEMICOLON
|
||||
self.bump(parser)?;
|
||||
self.bump(frontend)?;
|
||||
|
||||
let token = self.bump(parser)?;
|
||||
let token = self.bump(frontend)?;
|
||||
let _ = match token.value {
|
||||
TokenValue::PrecisionQualifier(p) => p,
|
||||
_ => {
|
||||
@@ -498,14 +500,14 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
};
|
||||
|
||||
let (ty, meta) = self.parse_type_non_void(parser)?;
|
||||
let (ty, meta) = self.parse_type_non_void(frontend)?;
|
||||
|
||||
match parser.module.types[ty].inner {
|
||||
match frontend.module.types[ty].inner {
|
||||
TypeInner::Scalar {
|
||||
kind: ScalarKind::Float | ScalarKind::Sint,
|
||||
..
|
||||
} => {}
|
||||
_ => parser.errors.push(Error {
|
||||
_ => frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
"Precision statement can only work on floats and ints".into(),
|
||||
),
|
||||
@@ -513,7 +515,7 @@ impl<'source> ParsingContext<'source> {
|
||||
}),
|
||||
}
|
||||
|
||||
self.expect(parser, TokenValue::Semicolon)?;
|
||||
self.expect(frontend, TokenValue::Semicolon)?;
|
||||
|
||||
Ok(Some(meta))
|
||||
}
|
||||
@@ -524,7 +526,7 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
pub fn parse_block_declaration(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
body: &mut Block,
|
||||
qualifiers: &mut TypeQualifiers,
|
||||
@@ -546,10 +548,10 @@ impl<'source> ParsingContext<'source> {
|
||||
};
|
||||
|
||||
let mut members = Vec::new();
|
||||
let span = self.parse_struct_declaration_list(parser, &mut members, layout)?;
|
||||
self.expect(parser, TokenValue::RightBrace)?;
|
||||
let span = self.parse_struct_declaration_list(frontend, &mut members, layout)?;
|
||||
self.expect(frontend, TokenValue::RightBrace)?;
|
||||
|
||||
let mut ty = parser.module.types.insert(
|
||||
let mut ty = frontend.module.types.insert(
|
||||
Type {
|
||||
name: Some(ty_name),
|
||||
inner: TypeInner::Struct {
|
||||
@@ -560,13 +562,13 @@ impl<'source> ParsingContext<'source> {
|
||||
Default::default(),
|
||||
);
|
||||
|
||||
let token = self.bump(parser)?;
|
||||
let token = self.bump(frontend)?;
|
||||
let name = match token.value {
|
||||
TokenValue::Semicolon => None,
|
||||
TokenValue::Identifier(name) => {
|
||||
self.parse_array_specifier(parser, &mut meta, &mut ty)?;
|
||||
self.parse_array_specifier(frontend, &mut meta, &mut ty)?;
|
||||
|
||||
self.expect(parser, TokenValue::Semicolon)?;
|
||||
self.expect(frontend, TokenValue::Semicolon)?;
|
||||
|
||||
Some(name)
|
||||
}
|
||||
@@ -581,7 +583,7 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
};
|
||||
|
||||
let global = parser.add_global_var(
|
||||
let global = frontend.add_global_var(
|
||||
ctx,
|
||||
body,
|
||||
VarDeclaration {
|
||||
@@ -605,9 +607,9 @@ impl<'source> ParsingContext<'source> {
|
||||
entry_arg: None,
|
||||
mutable: true,
|
||||
};
|
||||
ctx.add_global(parser, &k, lookup, body);
|
||||
ctx.add_global(frontend, &k, lookup, body);
|
||||
|
||||
parser.global_variables.push((k, lookup));
|
||||
frontend.global_variables.push((k, lookup));
|
||||
}
|
||||
|
||||
Ok(meta)
|
||||
@@ -616,7 +618,7 @@ impl<'source> ParsingContext<'source> {
|
||||
// TODO: Accept layout arguments
|
||||
pub fn parse_struct_declaration_list(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
members: &mut Vec<StructMember>,
|
||||
layout: StructLayout,
|
||||
) -> Result<u32> {
|
||||
@@ -626,22 +628,22 @@ impl<'source> ParsingContext<'source> {
|
||||
loop {
|
||||
// TODO: type_qualifier
|
||||
|
||||
let (mut ty, mut meta) = self.parse_type_non_void(parser)?;
|
||||
let (name, end_meta) = self.expect_ident(parser)?;
|
||||
let (mut ty, mut meta) = self.parse_type_non_void(frontend)?;
|
||||
let (name, end_meta) = self.expect_ident(frontend)?;
|
||||
|
||||
meta.subsume(end_meta);
|
||||
|
||||
self.parse_array_specifier(parser, &mut meta, &mut ty)?;
|
||||
self.parse_array_specifier(frontend, &mut meta, &mut ty)?;
|
||||
|
||||
self.expect(parser, TokenValue::Semicolon)?;
|
||||
self.expect(frontend, TokenValue::Semicolon)?;
|
||||
|
||||
let info = offset::calculate_offset(
|
||||
ty,
|
||||
meta,
|
||||
layout,
|
||||
&mut parser.module.types,
|
||||
&parser.module.constants,
|
||||
&mut parser.errors,
|
||||
&mut frontend.module.types,
|
||||
&frontend.module.constants,
|
||||
&mut frontend.errors,
|
||||
);
|
||||
|
||||
let member_alignment = info.align;
|
||||
@@ -657,7 +659,7 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
span += info.span;
|
||||
|
||||
if let TokenValue::RightBrace = self.expect_peek(parser)?.value {
|
||||
if let TokenValue::RightBrace = self.expect_peek(frontend)?.value {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::{
|
||||
error::{ErrorKind, ExpectedToken},
|
||||
parser::ParsingContext,
|
||||
token::{Token, TokenValue},
|
||||
Error, Parser, Result, Span,
|
||||
Error, Frontend, Result, Span,
|
||||
},
|
||||
ArraySize, BinaryOperator, Block, Constant, ConstantInner, Handle, ScalarValue, Type,
|
||||
TypeInner, UnaryOperator,
|
||||
@@ -14,12 +14,12 @@ use crate::{
|
||||
impl<'source> ParsingContext<'source> {
|
||||
pub fn parse_primary(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
stmt: &mut StmtContext,
|
||||
body: &mut Block,
|
||||
) -> Result<Handle<HirExpr>> {
|
||||
let mut token = self.bump(parser)?;
|
||||
let mut token = self.bump(frontend)?;
|
||||
|
||||
let (width, value) = match token.value {
|
||||
TokenValue::IntConstant(int) => (
|
||||
@@ -36,8 +36,8 @@ impl<'source> ParsingContext<'source> {
|
||||
),
|
||||
TokenValue::BoolConstant(value) => (1, ScalarValue::Bool(value)),
|
||||
TokenValue::LeftParen => {
|
||||
let expr = self.parse_expression(parser, ctx, stmt, body)?;
|
||||
let meta = self.expect(parser, TokenValue::RightParen)?.meta;
|
||||
let expr = self.parse_expression(frontend, ctx, stmt, body)?;
|
||||
let meta = self.expect(frontend, TokenValue::RightParen)?.meta;
|
||||
|
||||
token.meta.subsume(meta);
|
||||
|
||||
@@ -59,7 +59,7 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
};
|
||||
|
||||
let handle = parser.module.constants.fetch_or_append(
|
||||
let handle = frontend.module.constants.fetch_or_append(
|
||||
Constant {
|
||||
name: None,
|
||||
specialization: None,
|
||||
@@ -79,20 +79,20 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
pub fn parse_function_call_args(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
stmt: &mut StmtContext,
|
||||
body: &mut Block,
|
||||
meta: &mut Span,
|
||||
) -> Result<Vec<Handle<HirExpr>>> {
|
||||
let mut args = Vec::new();
|
||||
if let Some(token) = self.bump_if(parser, TokenValue::RightParen) {
|
||||
if let Some(token) = self.bump_if(frontend, TokenValue::RightParen) {
|
||||
meta.subsume(token.meta);
|
||||
} else {
|
||||
loop {
|
||||
args.push(self.parse_assignment(parser, ctx, stmt, body)?);
|
||||
args.push(self.parse_assignment(frontend, ctx, stmt, body)?);
|
||||
|
||||
let token = self.bump(parser)?;
|
||||
let token = self.bump(frontend)?;
|
||||
match token.value {
|
||||
TokenValue::Comma => {}
|
||||
TokenValue::RightParen => {
|
||||
@@ -117,26 +117,26 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
pub fn parse_postfix(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
stmt: &mut StmtContext,
|
||||
body: &mut Block,
|
||||
) -> Result<Handle<HirExpr>> {
|
||||
let mut base = if self.peek_type_name(parser) {
|
||||
let (mut handle, mut meta) = self.parse_type_non_void(parser)?;
|
||||
let mut base = if self.peek_type_name(frontend) {
|
||||
let (mut handle, mut meta) = self.parse_type_non_void(frontend)?;
|
||||
|
||||
self.expect(parser, TokenValue::LeftParen)?;
|
||||
let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?;
|
||||
self.expect(frontend, TokenValue::LeftParen)?;
|
||||
let args = self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?;
|
||||
|
||||
if let TypeInner::Array {
|
||||
size: ArraySize::Dynamic,
|
||||
stride,
|
||||
base,
|
||||
} = parser.module.types[handle].inner
|
||||
} = frontend.module.types[handle].inner
|
||||
{
|
||||
let span = parser.module.types.get_span(handle);
|
||||
let span = frontend.module.types.get_span(handle);
|
||||
|
||||
let constant = parser.module.constants.fetch_or_append(
|
||||
let constant = frontend.module.constants.fetch_or_append(
|
||||
Constant {
|
||||
name: None,
|
||||
specialization: None,
|
||||
@@ -147,7 +147,7 @@ impl<'source> ParsingContext<'source> {
|
||||
},
|
||||
Span::default(),
|
||||
);
|
||||
handle = parser.module.types.insert(
|
||||
handle = frontend.module.types.insert(
|
||||
Type {
|
||||
name: None,
|
||||
inner: TypeInner::Array {
|
||||
@@ -170,13 +170,13 @@ impl<'source> ParsingContext<'source> {
|
||||
},
|
||||
Default::default(),
|
||||
)
|
||||
} else if let TokenValue::Identifier(_) = self.expect_peek(parser)?.value {
|
||||
let (name, mut meta) = self.expect_ident(parser)?;
|
||||
} else if let TokenValue::Identifier(_) = self.expect_peek(frontend)?.value {
|
||||
let (name, mut meta) = self.expect_ident(frontend)?;
|
||||
|
||||
let expr = if self.bump_if(parser, TokenValue::LeftParen).is_some() {
|
||||
let args = self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?;
|
||||
let expr = if self.bump_if(frontend, TokenValue::LeftParen).is_some() {
|
||||
let args = self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?;
|
||||
|
||||
let kind = match parser.lookup_type.get(&name) {
|
||||
let kind = match frontend.lookup_type.get(&name) {
|
||||
Some(ty) => FunctionCallKind::TypeConstructor(*ty),
|
||||
None => FunctionCallKind::Function(name),
|
||||
};
|
||||
@@ -186,7 +186,7 @@ impl<'source> ParsingContext<'source> {
|
||||
meta,
|
||||
}
|
||||
} else {
|
||||
let var = match parser.lookup_variable(ctx, body, &name, meta) {
|
||||
let var = match frontend.lookup_variable(ctx, body, &name, meta) {
|
||||
Some(var) => var,
|
||||
None => {
|
||||
return Err(Error {
|
||||
@@ -204,20 +204,20 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
stmt.hir_exprs.append(expr, Default::default())
|
||||
} else {
|
||||
self.parse_primary(parser, ctx, stmt, body)?
|
||||
self.parse_primary(frontend, ctx, stmt, body)?
|
||||
};
|
||||
|
||||
while let TokenValue::LeftBracket
|
||||
| TokenValue::Dot
|
||||
| TokenValue::Increment
|
||||
| TokenValue::Decrement = self.expect_peek(parser)?.value
|
||||
| TokenValue::Decrement = self.expect_peek(frontend)?.value
|
||||
{
|
||||
let Token { value, mut meta } = self.bump(parser)?;
|
||||
let Token { value, mut meta } = self.bump(frontend)?;
|
||||
|
||||
match value {
|
||||
TokenValue::LeftBracket => {
|
||||
let index = self.parse_expression(parser, ctx, stmt, body)?;
|
||||
let end_meta = self.expect(parser, TokenValue::RightBracket)?.meta;
|
||||
let index = self.parse_expression(frontend, ctx, stmt, body)?;
|
||||
let end_meta = self.expect(frontend, TokenValue::RightBracket)?.meta;
|
||||
|
||||
meta.subsume(end_meta);
|
||||
base = stmt.hir_exprs.append(
|
||||
@@ -229,11 +229,11 @@ impl<'source> ParsingContext<'source> {
|
||||
)
|
||||
}
|
||||
TokenValue::Dot => {
|
||||
let (field, end_meta) = self.expect_ident(parser)?;
|
||||
let (field, end_meta) = self.expect_ident(frontend)?;
|
||||
|
||||
if self.bump_if(parser, TokenValue::LeftParen).is_some() {
|
||||
if self.bump_if(frontend, TokenValue::LeftParen).is_some() {
|
||||
let args =
|
||||
self.parse_function_call_args(parser, ctx, stmt, body, &mut meta)?;
|
||||
self.parse_function_call_args(frontend, ctx, stmt, body, &mut meta)?;
|
||||
|
||||
base = stmt.hir_exprs.append(
|
||||
HirExpr {
|
||||
@@ -283,16 +283,16 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
pub fn parse_unary(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
stmt: &mut StmtContext,
|
||||
body: &mut Block,
|
||||
) -> Result<Handle<HirExpr>> {
|
||||
Ok(match self.expect_peek(parser)?.value {
|
||||
Ok(match self.expect_peek(frontend)?.value {
|
||||
TokenValue::Plus | TokenValue::Dash | TokenValue::Bang | TokenValue::Tilde => {
|
||||
let Token { value, mut meta } = self.bump(parser)?;
|
||||
let Token { value, mut meta } = self.bump(frontend)?;
|
||||
|
||||
let expr = self.parse_unary(parser, ctx, stmt, body)?;
|
||||
let expr = self.parse_unary(frontend, ctx, stmt, body)?;
|
||||
let end_meta = stmt.hir_exprs[expr].meta;
|
||||
|
||||
let kind = match value {
|
||||
@@ -312,9 +312,9 @@ impl<'source> ParsingContext<'source> {
|
||||
.append(HirExpr { kind, meta }, Default::default())
|
||||
}
|
||||
TokenValue::Increment | TokenValue::Decrement => {
|
||||
let Token { value, meta } = self.bump(parser)?;
|
||||
let Token { value, meta } = self.bump(frontend)?;
|
||||
|
||||
let expr = self.parse_unary(parser, ctx, stmt, body)?;
|
||||
let expr = self.parse_unary(frontend, ctx, stmt, body)?;
|
||||
|
||||
stmt.hir_exprs.append(
|
||||
HirExpr {
|
||||
@@ -331,32 +331,32 @@ impl<'source> ParsingContext<'source> {
|
||||
Default::default(),
|
||||
)
|
||||
}
|
||||
_ => self.parse_postfix(parser, ctx, stmt, body)?,
|
||||
_ => self.parse_postfix(frontend, ctx, stmt, body)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_binary(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
stmt: &mut StmtContext,
|
||||
body: &mut Block,
|
||||
passtrough: Option<Handle<HirExpr>>,
|
||||
passthrough: Option<Handle<HirExpr>>,
|
||||
min_bp: u8,
|
||||
) -> Result<Handle<HirExpr>> {
|
||||
let mut left = passtrough
|
||||
let mut left = passthrough
|
||||
.ok_or(ErrorKind::EndOfFile /* Dummy error */)
|
||||
.or_else(|_| self.parse_unary(parser, ctx, stmt, body))?;
|
||||
.or_else(|_| self.parse_unary(frontend, ctx, stmt, body))?;
|
||||
let mut meta = stmt.hir_exprs[left].meta;
|
||||
|
||||
while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek(parser)?.value) {
|
||||
while let Some((l_bp, r_bp)) = binding_power(&self.expect_peek(frontend)?.value) {
|
||||
if l_bp < min_bp {
|
||||
break;
|
||||
}
|
||||
|
||||
let Token { value, .. } = self.bump(parser)?;
|
||||
let Token { value, .. } = self.bump(frontend)?;
|
||||
|
||||
let right = self.parse_binary(parser, ctx, stmt, body, None, r_bp)?;
|
||||
let right = self.parse_binary(frontend, ctx, stmt, body, None, r_bp)?;
|
||||
let end_meta = stmt.hir_exprs[right].meta;
|
||||
|
||||
meta.subsume(end_meta);
|
||||
@@ -399,19 +399,19 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
pub fn parse_conditional(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
stmt: &mut StmtContext,
|
||||
body: &mut Block,
|
||||
passtrough: Option<Handle<HirExpr>>,
|
||||
passthrough: Option<Handle<HirExpr>>,
|
||||
) -> Result<Handle<HirExpr>> {
|
||||
let mut condition = self.parse_binary(parser, ctx, stmt, body, passtrough, 0)?;
|
||||
let mut condition = self.parse_binary(frontend, ctx, stmt, body, passthrough, 0)?;
|
||||
let mut meta = stmt.hir_exprs[condition].meta;
|
||||
|
||||
if self.bump_if(parser, TokenValue::Question).is_some() {
|
||||
let accept = self.parse_expression(parser, ctx, stmt, body)?;
|
||||
self.expect(parser, TokenValue::Colon)?;
|
||||
let reject = self.parse_assignment(parser, ctx, stmt, body)?;
|
||||
if self.bump_if(frontend, TokenValue::Question).is_some() {
|
||||
let accept = self.parse_expression(frontend, ctx, stmt, body)?;
|
||||
self.expect(frontend, TokenValue::Colon)?;
|
||||
let reject = self.parse_assignment(frontend, ctx, stmt, body)?;
|
||||
let end_meta = stmt.hir_exprs[reject].meta;
|
||||
|
||||
meta.subsume(end_meta);
|
||||
@@ -433,18 +433,18 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
pub fn parse_assignment(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
stmt: &mut StmtContext,
|
||||
body: &mut Block,
|
||||
) -> Result<Handle<HirExpr>> {
|
||||
let tgt = self.parse_unary(parser, ctx, stmt, body)?;
|
||||
let tgt = self.parse_unary(frontend, ctx, stmt, body)?;
|
||||
let mut meta = stmt.hir_exprs[tgt].meta;
|
||||
|
||||
Ok(match self.expect_peek(parser)?.value {
|
||||
Ok(match self.expect_peek(frontend)?.value {
|
||||
TokenValue::Assign => {
|
||||
self.bump(parser)?;
|
||||
let value = self.parse_assignment(parser, ctx, stmt, body)?;
|
||||
self.bump(frontend)?;
|
||||
let value = self.parse_assignment(frontend, ctx, stmt, body)?;
|
||||
let end_meta = stmt.hir_exprs[value].meta;
|
||||
|
||||
meta.subsume(end_meta);
|
||||
@@ -466,8 +466,8 @@ impl<'source> ParsingContext<'source> {
|
||||
| TokenValue::LeftShiftAssign
|
||||
| TokenValue::RightShiftAssign
|
||||
| TokenValue::XorAssign => {
|
||||
let token = self.bump(parser)?;
|
||||
let right = self.parse_assignment(parser, ctx, stmt, body)?;
|
||||
let token = self.bump(frontend)?;
|
||||
let right = self.parse_assignment(frontend, ctx, stmt, body)?;
|
||||
let end_meta = stmt.hir_exprs[right].meta;
|
||||
|
||||
meta.subsume(end_meta);
|
||||
@@ -503,22 +503,22 @@ impl<'source> ParsingContext<'source> {
|
||||
Default::default(),
|
||||
)
|
||||
}
|
||||
_ => self.parse_conditional(parser, ctx, stmt, body, Some(tgt))?,
|
||||
_ => self.parse_conditional(frontend, ctx, stmt, body, Some(tgt))?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_expression(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
stmt: &mut StmtContext,
|
||||
body: &mut Block,
|
||||
) -> Result<Handle<HirExpr>> {
|
||||
let mut expr = self.parse_assignment(parser, ctx, stmt, body)?;
|
||||
let mut expr = self.parse_assignment(frontend, ctx, stmt, body)?;
|
||||
|
||||
while let TokenValue::Comma = self.expect_peek(parser)?.value {
|
||||
self.bump(parser)?;
|
||||
expr = self.parse_assignment(parser, ctx, stmt, body)?;
|
||||
while let TokenValue::Comma = self.expect_peek(frontend)?.value {
|
||||
self.bump(frontend)?;
|
||||
expr = self.parse_assignment(frontend, ctx, stmt, body)?;
|
||||
}
|
||||
|
||||
Ok(expr)
|
||||
|
||||
+140
-131
@@ -7,23 +7,23 @@ use crate::{
|
||||
parser::ParsingContext,
|
||||
token::{Token, TokenValue},
|
||||
variables::VarDeclaration,
|
||||
Error, ErrorKind, Parser, Result,
|
||||
Error, ErrorKind, Frontend, Result,
|
||||
},
|
||||
Block, ConstantInner, Expression, ScalarValue, Statement, SwitchCase, UnaryOperator,
|
||||
};
|
||||
|
||||
impl<'source> ParsingContext<'source> {
|
||||
pub fn peek_parameter_qualifier(&mut self, parser: &mut Parser) -> bool {
|
||||
self.peek(parser).map_or(false, |t| match t.value {
|
||||
pub fn peek_parameter_qualifier(&mut self, frontend: &mut Frontend) -> bool {
|
||||
self.peek(frontend).map_or(false, |t| match t.value {
|
||||
TokenValue::In | TokenValue::Out | TokenValue::InOut | TokenValue::Const => true,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the parsed `ParameterQualifier` or `ParameterQualifier::In`
|
||||
pub fn parse_parameter_qualifier(&mut self, parser: &mut Parser) -> ParameterQualifier {
|
||||
if self.peek_parameter_qualifier(parser) {
|
||||
match self.bump(parser).unwrap().value {
|
||||
pub fn parse_parameter_qualifier(&mut self, frontend: &mut Frontend) -> ParameterQualifier {
|
||||
if self.peek_parameter_qualifier(frontend) {
|
||||
match self.bump(frontend).unwrap().value {
|
||||
TokenValue::In => ParameterQualifier::In,
|
||||
TokenValue::Out => ParameterQualifier::Out,
|
||||
TokenValue::InOut => ParameterQualifier::InOut,
|
||||
@@ -37,30 +37,30 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
pub fn parse_statement(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
body: &mut Block,
|
||||
terminator: &mut Option<usize>,
|
||||
) -> Result<Option<Span>> {
|
||||
// Type qualifiers always identify a declaration statement
|
||||
if self.peek_type_qualifier(parser) {
|
||||
return self.parse_declaration(parser, ctx, body, false);
|
||||
if self.peek_type_qualifier(frontend) {
|
||||
return self.parse_declaration(frontend, ctx, body, false);
|
||||
}
|
||||
|
||||
// Type names can identify either declaration statements or type constructors
|
||||
// depending on wether the token following the type name is a `(` (LeftParen)
|
||||
if self.peek_type_name(parser) {
|
||||
if self.peek_type_name(frontend) {
|
||||
// Start by consuming the type name so that we can peek the token after it
|
||||
let token = self.bump(parser)?;
|
||||
let token = self.bump(frontend)?;
|
||||
// Peek the next token and check if it's a `(` (LeftParen) if so the statement
|
||||
// is a constructor, otherwise it's a declaration. We need to do the check
|
||||
// beforehand and not in the if since we will backtrack before the if
|
||||
let declaration = TokenValue::LeftParen != self.expect_peek(parser)?.value;
|
||||
let declaration = TokenValue::LeftParen != self.expect_peek(frontend)?.value;
|
||||
|
||||
self.backtrack(token)?;
|
||||
|
||||
if declaration {
|
||||
return self.parse_declaration(parser, ctx, body, false);
|
||||
return self.parse_declaration(frontend, ctx, body, false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,32 +73,32 @@ impl<'source> ParsingContext<'source> {
|
||||
let &Token {
|
||||
ref value,
|
||||
mut meta,
|
||||
} = self.expect_peek(parser)?;
|
||||
} = self.expect_peek(frontend)?;
|
||||
|
||||
let meta_rest = match *value {
|
||||
TokenValue::Continue => {
|
||||
let meta = self.bump(parser)?.meta;
|
||||
let meta = self.bump(frontend)?.meta;
|
||||
body.push(Statement::Continue, meta);
|
||||
terminator.get_or_insert(body.len());
|
||||
self.expect(parser, TokenValue::Semicolon)?.meta
|
||||
self.expect(frontend, TokenValue::Semicolon)?.meta
|
||||
}
|
||||
TokenValue::Break => {
|
||||
let meta = self.bump(parser)?.meta;
|
||||
let meta = self.bump(frontend)?.meta;
|
||||
body.push(Statement::Break, meta);
|
||||
terminator.get_or_insert(body.len());
|
||||
self.expect(parser, TokenValue::Semicolon)?.meta
|
||||
self.expect(frontend, TokenValue::Semicolon)?.meta
|
||||
}
|
||||
TokenValue::Return => {
|
||||
self.bump(parser)?;
|
||||
let (value, meta) = match self.expect_peek(parser)?.value {
|
||||
TokenValue::Semicolon => (None, self.bump(parser)?.meta),
|
||||
self.bump(frontend)?;
|
||||
let (value, meta) = match self.expect_peek(frontend)?.value {
|
||||
TokenValue::Semicolon => (None, self.bump(frontend)?.meta),
|
||||
_ => {
|
||||
// TODO: Implicit conversions
|
||||
let mut stmt = ctx.stmt_ctx();
|
||||
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
|
||||
self.expect(parser, TokenValue::Semicolon)?;
|
||||
let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?;
|
||||
self.expect(frontend, TokenValue::Semicolon)?;
|
||||
let (handle, meta) =
|
||||
ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?;
|
||||
ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?;
|
||||
(Some(handle), meta)
|
||||
}
|
||||
};
|
||||
@@ -111,39 +111,39 @@ impl<'source> ParsingContext<'source> {
|
||||
meta
|
||||
}
|
||||
TokenValue::Discard => {
|
||||
let meta = self.bump(parser)?.meta;
|
||||
let meta = self.bump(frontend)?.meta;
|
||||
body.push(Statement::Kill, meta);
|
||||
terminator.get_or_insert(body.len());
|
||||
|
||||
self.expect(parser, TokenValue::Semicolon)?.meta
|
||||
self.expect(frontend, TokenValue::Semicolon)?.meta
|
||||
}
|
||||
TokenValue::If => {
|
||||
let mut meta = self.bump(parser)?.meta;
|
||||
let mut meta = self.bump(frontend)?.meta;
|
||||
|
||||
self.expect(parser, TokenValue::LeftParen)?;
|
||||
self.expect(frontend, TokenValue::LeftParen)?;
|
||||
let condition = {
|
||||
let mut stmt = ctx.stmt_ctx();
|
||||
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
|
||||
let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?;
|
||||
let (handle, more_meta) =
|
||||
ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?;
|
||||
ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?;
|
||||
meta.subsume(more_meta);
|
||||
handle
|
||||
};
|
||||
self.expect(parser, TokenValue::RightParen)?;
|
||||
self.expect(frontend, TokenValue::RightParen)?;
|
||||
|
||||
ctx.emit_restart(body);
|
||||
|
||||
let mut accept = Block::new();
|
||||
if let Some(more_meta) =
|
||||
self.parse_statement(parser, ctx, &mut accept, &mut None)?
|
||||
self.parse_statement(frontend, ctx, &mut accept, &mut None)?
|
||||
{
|
||||
meta.subsume(more_meta)
|
||||
}
|
||||
|
||||
let mut reject = Block::new();
|
||||
if self.bump_if(parser, TokenValue::Else).is_some() {
|
||||
if self.bump_if(frontend, TokenValue::Else).is_some() {
|
||||
if let Some(more_meta) =
|
||||
self.parse_statement(parser, ctx, &mut reject, &mut None)?
|
||||
self.parse_statement(frontend, ctx, &mut reject, &mut None)?
|
||||
{
|
||||
meta.subsume(more_meta);
|
||||
}
|
||||
@@ -161,18 +161,19 @@ impl<'source> ParsingContext<'source> {
|
||||
meta
|
||||
}
|
||||
TokenValue::Switch => {
|
||||
let mut meta = self.bump(parser)?.meta;
|
||||
let mut meta = self.bump(frontend)?.meta;
|
||||
let end_meta;
|
||||
|
||||
self.expect(parser, TokenValue::LeftParen)?;
|
||||
self.expect(frontend, TokenValue::LeftParen)?;
|
||||
|
||||
let selector = {
|
||||
let mut stmt = ctx.stmt_ctx();
|
||||
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
|
||||
ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?.0
|
||||
let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?;
|
||||
ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?
|
||||
.0
|
||||
};
|
||||
|
||||
self.expect(parser, TokenValue::RightParen)?;
|
||||
self.expect(frontend, TokenValue::RightParen)?;
|
||||
|
||||
ctx.emit_restart(body);
|
||||
|
||||
@@ -180,19 +181,19 @@ impl<'source> ParsingContext<'source> {
|
||||
// Track if any default case is present in the switch statement.
|
||||
let mut default_present = false;
|
||||
|
||||
self.expect(parser, TokenValue::LeftBrace)?;
|
||||
self.expect(frontend, TokenValue::LeftBrace)?;
|
||||
loop {
|
||||
let value = match self.expect_peek(parser)?.value {
|
||||
let value = match self.expect_peek(frontend)?.value {
|
||||
TokenValue::Case => {
|
||||
self.bump(parser)?;
|
||||
self.bump(frontend)?;
|
||||
let value = {
|
||||
let mut stmt = ctx.stmt_ctx();
|
||||
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
|
||||
let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?;
|
||||
let (root, meta) =
|
||||
ctx.lower_expect(stmt, parser, expr, ExprPos::Rhs, body)?;
|
||||
let constant = parser.solve_constant(ctx, root, meta)?;
|
||||
ctx.lower_expect(stmt, frontend, expr, ExprPos::Rhs, body)?;
|
||||
let constant = frontend.solve_constant(ctx, root, meta)?;
|
||||
|
||||
match parser.module.constants[constant].inner {
|
||||
match frontend.module.constants[constant].inner {
|
||||
ConstantInner::Scalar {
|
||||
value: ScalarValue::Sint(int),
|
||||
..
|
||||
@@ -202,7 +203,7 @@ impl<'source> ParsingContext<'source> {
|
||||
..
|
||||
} => int as i32,
|
||||
_ => {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
"Case values can only be integers".into(),
|
||||
),
|
||||
@@ -216,16 +217,16 @@ impl<'source> ParsingContext<'source> {
|
||||
crate::SwitchValue::Integer(value)
|
||||
}
|
||||
TokenValue::Default => {
|
||||
self.bump(parser)?;
|
||||
self.bump(frontend)?;
|
||||
default_present = true;
|
||||
crate::SwitchValue::Default
|
||||
}
|
||||
TokenValue::RightBrace => {
|
||||
end_meta = self.bump(parser)?.meta;
|
||||
end_meta = self.bump(frontend)?.meta;
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
let Token { value, meta } = self.bump(parser)?;
|
||||
let Token { value, meta } = self.bump(frontend)?;
|
||||
return Err(Error {
|
||||
kind: ErrorKind::InvalidToken(
|
||||
value,
|
||||
@@ -240,18 +241,23 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
};
|
||||
|
||||
self.expect(parser, TokenValue::Colon)?;
|
||||
self.expect(frontend, TokenValue::Colon)?;
|
||||
|
||||
let mut body = Block::new();
|
||||
|
||||
let mut case_terminator = None;
|
||||
loop {
|
||||
match self.expect_peek(parser)?.value {
|
||||
match self.expect_peek(frontend)?.value {
|
||||
TokenValue::Case | TokenValue::Default | TokenValue::RightBrace => {
|
||||
break
|
||||
}
|
||||
_ => {
|
||||
self.parse_statement(parser, ctx, &mut body, &mut case_terminator)?;
|
||||
self.parse_statement(
|
||||
frontend,
|
||||
ctx,
|
||||
&mut body,
|
||||
&mut case_terminator,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -284,7 +290,7 @@ impl<'source> ParsingContext<'source> {
|
||||
// also be checked because `break`s count as statements but
|
||||
// they aren't added to the body)
|
||||
if case.body.is_empty() && case.fall_through {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
"last case/default label must be followed by statements".into(),
|
||||
),
|
||||
@@ -315,17 +321,17 @@ impl<'source> ParsingContext<'source> {
|
||||
meta
|
||||
}
|
||||
TokenValue::While => {
|
||||
let mut meta = self.bump(parser)?.meta;
|
||||
let mut meta = self.bump(frontend)?.meta;
|
||||
|
||||
let mut loop_body = Block::new();
|
||||
|
||||
let mut stmt = ctx.stmt_ctx();
|
||||
self.expect(parser, TokenValue::LeftParen)?;
|
||||
let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?;
|
||||
meta.subsume(self.expect(parser, TokenValue::RightParen)?.meta);
|
||||
self.expect(frontend, TokenValue::LeftParen)?;
|
||||
let root = self.parse_expression(frontend, ctx, &mut stmt, &mut loop_body)?;
|
||||
meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta);
|
||||
|
||||
let (expr, expr_meta) =
|
||||
ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?;
|
||||
ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut loop_body)?;
|
||||
let condition = ctx.add_expression(
|
||||
Expression::Unary {
|
||||
op: UnaryOperator::Not,
|
||||
@@ -349,7 +355,7 @@ impl<'source> ParsingContext<'source> {
|
||||
meta.subsume(expr_meta);
|
||||
|
||||
if let Some(body_meta) =
|
||||
self.parse_statement(parser, ctx, &mut loop_body, &mut None)?
|
||||
self.parse_statement(frontend, ctx, &mut loop_body, &mut None)?
|
||||
{
|
||||
meta.subsume(body_meta);
|
||||
}
|
||||
@@ -366,24 +372,24 @@ impl<'source> ParsingContext<'source> {
|
||||
meta
|
||||
}
|
||||
TokenValue::Do => {
|
||||
let mut meta = self.bump(parser)?.meta;
|
||||
let mut meta = self.bump(frontend)?.meta;
|
||||
|
||||
let mut loop_body = Block::new();
|
||||
|
||||
let mut terminator = None;
|
||||
self.parse_statement(parser, ctx, &mut loop_body, &mut terminator)?;
|
||||
self.parse_statement(frontend, ctx, &mut loop_body, &mut terminator)?;
|
||||
|
||||
let mut stmt = ctx.stmt_ctx();
|
||||
|
||||
self.expect(parser, TokenValue::While)?;
|
||||
self.expect(parser, TokenValue::LeftParen)?;
|
||||
let root = self.parse_expression(parser, ctx, &mut stmt, &mut loop_body)?;
|
||||
let end_meta = self.expect(parser, TokenValue::RightParen)?.meta;
|
||||
self.expect(frontend, TokenValue::While)?;
|
||||
self.expect(frontend, TokenValue::LeftParen)?;
|
||||
let root = self.parse_expression(frontend, ctx, &mut stmt, &mut loop_body)?;
|
||||
let end_meta = self.expect(frontend, TokenValue::RightParen)?.meta;
|
||||
|
||||
meta.subsume(end_meta);
|
||||
|
||||
let (expr, expr_meta) =
|
||||
ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut loop_body)?;
|
||||
ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut loop_body)?;
|
||||
let condition = ctx.add_expression(
|
||||
Expression::Unary {
|
||||
op: UnaryOperator::Not,
|
||||
@@ -420,58 +426,59 @@ impl<'source> ParsingContext<'source> {
|
||||
meta
|
||||
}
|
||||
TokenValue::For => {
|
||||
let mut meta = self.bump(parser)?.meta;
|
||||
let mut meta = self.bump(frontend)?.meta;
|
||||
|
||||
ctx.symbol_table.push_scope();
|
||||
self.expect(parser, TokenValue::LeftParen)?;
|
||||
self.expect(frontend, TokenValue::LeftParen)?;
|
||||
|
||||
if self.bump_if(parser, TokenValue::Semicolon).is_none() {
|
||||
if self.peek_type_name(parser) || self.peek_type_qualifier(parser) {
|
||||
self.parse_declaration(parser, ctx, body, false)?;
|
||||
if self.bump_if(frontend, TokenValue::Semicolon).is_none() {
|
||||
if self.peek_type_name(frontend) || self.peek_type_qualifier(frontend) {
|
||||
self.parse_declaration(frontend, ctx, body, false)?;
|
||||
} else {
|
||||
let mut stmt = ctx.stmt_ctx();
|
||||
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
|
||||
ctx.lower(stmt, parser, expr, ExprPos::Rhs, body)?;
|
||||
self.expect(parser, TokenValue::Semicolon)?;
|
||||
let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?;
|
||||
ctx.lower(stmt, frontend, expr, ExprPos::Rhs, body)?;
|
||||
self.expect(frontend, TokenValue::Semicolon)?;
|
||||
}
|
||||
}
|
||||
|
||||
let (mut block, mut continuing) = (Block::new(), Block::new());
|
||||
|
||||
if self.bump_if(parser, TokenValue::Semicolon).is_none() {
|
||||
let (expr, expr_meta) =
|
||||
if self.peek_type_name(parser) || self.peek_type_qualifier(parser) {
|
||||
let mut qualifiers = self.parse_type_qualifiers(parser)?;
|
||||
let (ty, mut meta) = self.parse_type_non_void(parser)?;
|
||||
let name = self.expect_ident(parser)?.0;
|
||||
if self.bump_if(frontend, TokenValue::Semicolon).is_none() {
|
||||
let (expr, expr_meta) = if self.peek_type_name(frontend)
|
||||
|| self.peek_type_qualifier(frontend)
|
||||
{
|
||||
let mut qualifiers = self.parse_type_qualifiers(frontend)?;
|
||||
let (ty, mut meta) = self.parse_type_non_void(frontend)?;
|
||||
let name = self.expect_ident(frontend)?.0;
|
||||
|
||||
self.expect(parser, TokenValue::Assign)?;
|
||||
self.expect(frontend, TokenValue::Assign)?;
|
||||
|
||||
let (value, end_meta) =
|
||||
self.parse_initializer(parser, ty, ctx, &mut block)?;
|
||||
meta.subsume(end_meta);
|
||||
let (value, end_meta) =
|
||||
self.parse_initializer(frontend, ty, ctx, &mut block)?;
|
||||
meta.subsume(end_meta);
|
||||
|
||||
let decl = VarDeclaration {
|
||||
qualifiers: &mut qualifiers,
|
||||
ty,
|
||||
name: Some(name),
|
||||
init: None,
|
||||
meta,
|
||||
};
|
||||
|
||||
let pointer = parser.add_local_var(ctx, &mut block, decl)?;
|
||||
|
||||
ctx.emit_restart(&mut block);
|
||||
|
||||
block.push(Statement::Store { pointer, value }, meta);
|
||||
|
||||
(value, end_meta)
|
||||
} else {
|
||||
let mut stmt = ctx.stmt_ctx();
|
||||
let root = self.parse_expression(parser, ctx, &mut stmt, &mut block)?;
|
||||
ctx.lower_expect(stmt, parser, root, ExprPos::Rhs, &mut block)?
|
||||
let decl = VarDeclaration {
|
||||
qualifiers: &mut qualifiers,
|
||||
ty,
|
||||
name: Some(name),
|
||||
init: None,
|
||||
meta,
|
||||
};
|
||||
|
||||
let pointer = frontend.add_local_var(ctx, &mut block, decl)?;
|
||||
|
||||
ctx.emit_restart(&mut block);
|
||||
|
||||
block.push(Statement::Store { pointer, value }, meta);
|
||||
|
||||
(value, end_meta)
|
||||
} else {
|
||||
let mut stmt = ctx.stmt_ctx();
|
||||
let root = self.parse_expression(frontend, ctx, &mut stmt, &mut block)?;
|
||||
ctx.lower_expect(stmt, frontend, root, ExprPos::Rhs, &mut block)?
|
||||
};
|
||||
|
||||
let condition = ctx.add_expression(
|
||||
Expression::Unary {
|
||||
op: UnaryOperator::Not,
|
||||
@@ -492,22 +499,24 @@ impl<'source> ParsingContext<'source> {
|
||||
crate::Span::default(),
|
||||
);
|
||||
|
||||
self.expect(parser, TokenValue::Semicolon)?;
|
||||
self.expect(frontend, TokenValue::Semicolon)?;
|
||||
}
|
||||
|
||||
match self.expect_peek(parser)?.value {
|
||||
match self.expect_peek(frontend)?.value {
|
||||
TokenValue::RightParen => {}
|
||||
_ => {
|
||||
let mut stmt = ctx.stmt_ctx();
|
||||
let rest =
|
||||
self.parse_expression(parser, ctx, &mut stmt, &mut continuing)?;
|
||||
ctx.lower(stmt, parser, rest, ExprPos::Rhs, &mut continuing)?;
|
||||
self.parse_expression(frontend, ctx, &mut stmt, &mut continuing)?;
|
||||
ctx.lower(stmt, frontend, rest, ExprPos::Rhs, &mut continuing)?;
|
||||
}
|
||||
}
|
||||
|
||||
meta.subsume(self.expect(parser, TokenValue::RightParen)?.meta);
|
||||
meta.subsume(self.expect(frontend, TokenValue::RightParen)?.meta);
|
||||
|
||||
if let Some(stmt_meta) = self.parse_statement(parser, ctx, &mut block, &mut None)? {
|
||||
if let Some(stmt_meta) =
|
||||
self.parse_statement(frontend, ctx, &mut block, &mut None)?
|
||||
{
|
||||
meta.subsume(stmt_meta);
|
||||
}
|
||||
|
||||
@@ -525,14 +534,14 @@ impl<'source> ParsingContext<'source> {
|
||||
meta
|
||||
}
|
||||
TokenValue::LeftBrace => {
|
||||
let meta = self.bump(parser)?.meta;
|
||||
let meta = self.bump(frontend)?.meta;
|
||||
|
||||
let mut block = Block::new();
|
||||
|
||||
let mut block_terminator = None;
|
||||
let meta = self.parse_compound_statement(
|
||||
meta,
|
||||
parser,
|
||||
frontend,
|
||||
ctx,
|
||||
&mut block,
|
||||
&mut block_terminator,
|
||||
@@ -545,15 +554,15 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
meta
|
||||
}
|
||||
TokenValue::Semicolon => self.bump(parser)?.meta,
|
||||
TokenValue::Semicolon => self.bump(frontend)?.meta,
|
||||
_ => {
|
||||
// Attempt to force expression parsing for remainder of the
|
||||
// tokens. Unknown or invalid tokens will be caught there and
|
||||
// turned into an error.
|
||||
let mut stmt = ctx.stmt_ctx();
|
||||
let expr = self.parse_expression(parser, ctx, &mut stmt, body)?;
|
||||
ctx.lower(stmt, parser, expr, ExprPos::Rhs, body)?;
|
||||
self.expect(parser, TokenValue::Semicolon)?.meta
|
||||
let expr = self.parse_expression(frontend, ctx, &mut stmt, body)?;
|
||||
ctx.lower(stmt, frontend, expr, ExprPos::Rhs, body)?;
|
||||
self.expect(frontend, TokenValue::Semicolon)?.meta
|
||||
}
|
||||
};
|
||||
|
||||
@@ -564,7 +573,7 @@ impl<'source> ParsingContext<'source> {
|
||||
pub fn parse_compound_statement(
|
||||
&mut self,
|
||||
mut meta: Span,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
ctx: &mut Context,
|
||||
body: &mut Block,
|
||||
terminator: &mut Option<usize>,
|
||||
@@ -574,13 +583,13 @@ impl<'source> ParsingContext<'source> {
|
||||
loop {
|
||||
if let Some(Token {
|
||||
meta: brace_meta, ..
|
||||
}) = self.bump_if(parser, TokenValue::RightBrace)
|
||||
}) = self.bump_if(frontend, TokenValue::RightBrace)
|
||||
{
|
||||
meta.subsume(brace_meta);
|
||||
break;
|
||||
}
|
||||
|
||||
let stmt = self.parse_statement(parser, ctx, body, terminator)?;
|
||||
let stmt = self.parse_statement(frontend, ctx, body, terminator)?;
|
||||
|
||||
if let Some(stmt_meta) = stmt {
|
||||
meta.subsume(stmt_meta);
|
||||
@@ -598,32 +607,32 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
pub fn parse_function_args(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
context: &mut Context,
|
||||
body: &mut Block,
|
||||
) -> Result<()> {
|
||||
if self.bump_if(parser, TokenValue::Void).is_some() {
|
||||
if self.bump_if(frontend, TokenValue::Void).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
loop {
|
||||
if self.peek_type_name(parser) || self.peek_parameter_qualifier(parser) {
|
||||
let qualifier = self.parse_parameter_qualifier(parser);
|
||||
let mut ty = self.parse_type_non_void(parser)?.0;
|
||||
if self.peek_type_name(frontend) || self.peek_parameter_qualifier(frontend) {
|
||||
let qualifier = self.parse_parameter_qualifier(frontend);
|
||||
let mut ty = self.parse_type_non_void(frontend)?.0;
|
||||
|
||||
match self.expect_peek(parser)?.value {
|
||||
match self.expect_peek(frontend)?.value {
|
||||
TokenValue::Comma => {
|
||||
self.bump(parser)?;
|
||||
context.add_function_arg(parser, body, None, ty, qualifier);
|
||||
self.bump(frontend)?;
|
||||
context.add_function_arg(frontend, body, None, ty, qualifier);
|
||||
continue;
|
||||
}
|
||||
TokenValue::Identifier(_) => {
|
||||
let mut name = self.expect_ident(parser)?;
|
||||
self.parse_array_specifier(parser, &mut name.1, &mut ty)?;
|
||||
let mut name = self.expect_ident(frontend)?;
|
||||
self.parse_array_specifier(frontend, &mut name.1, &mut ty)?;
|
||||
|
||||
context.add_function_arg(parser, body, Some(name), ty, qualifier);
|
||||
context.add_function_arg(frontend, body, Some(name), ty, qualifier);
|
||||
|
||||
if self.bump_if(parser, TokenValue::Comma).is_some() {
|
||||
if self.bump_if(frontend, TokenValue::Comma).is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::{
|
||||
error::ExpectedToken,
|
||||
parser::ParsingContext,
|
||||
token::{Token, TokenValue},
|
||||
Error, ErrorKind, Parser, Result,
|
||||
Error, ErrorKind, Frontend, Result,
|
||||
},
|
||||
AddressSpace, ArraySize, Handle, Span, Type, TypeInner,
|
||||
};
|
||||
@@ -14,50 +14,51 @@ impl<'source> ParsingContext<'source> {
|
||||
/// and modifying the type handle if it exists
|
||||
pub fn parse_array_specifier(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
span: &mut Span,
|
||||
ty: &mut Handle<Type>,
|
||||
) -> Result<()> {
|
||||
while self.parse_array_specifier_single(parser, span, ty)? {}
|
||||
while self.parse_array_specifier_single(frontend, span, ty)? {}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Implementation of [`Self::parse_array_specifier`] for a single array_specifier
|
||||
fn parse_array_specifier_single(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
span: &mut Span,
|
||||
ty: &mut Handle<Type>,
|
||||
) -> Result<bool> {
|
||||
if self.bump_if(parser, TokenValue::LeftBracket).is_some() {
|
||||
let size =
|
||||
if let Some(Token { meta, .. }) = self.bump_if(parser, TokenValue::RightBracket) {
|
||||
span.subsume(meta);
|
||||
ArraySize::Dynamic
|
||||
} else {
|
||||
let (value, constant_span) = self.parse_uint_constant(parser)?;
|
||||
let constant = parser.module.constants.fetch_or_append(
|
||||
crate::Constant {
|
||||
name: None,
|
||||
specialization: None,
|
||||
inner: crate::ConstantInner::Scalar {
|
||||
width: 4,
|
||||
value: crate::ScalarValue::Uint(value as u64),
|
||||
},
|
||||
if self.bump_if(frontend, TokenValue::LeftBracket).is_some() {
|
||||
let size = if let Some(Token { meta, .. }) =
|
||||
self.bump_if(frontend, TokenValue::RightBracket)
|
||||
{
|
||||
span.subsume(meta);
|
||||
ArraySize::Dynamic
|
||||
} else {
|
||||
let (value, constant_span) = self.parse_uint_constant(frontend)?;
|
||||
let constant = frontend.module.constants.fetch_or_append(
|
||||
crate::Constant {
|
||||
name: None,
|
||||
specialization: None,
|
||||
inner: crate::ConstantInner::Scalar {
|
||||
width: 4,
|
||||
value: crate::ScalarValue::Uint(value as u64),
|
||||
},
|
||||
constant_span,
|
||||
);
|
||||
let end_span = self.expect(parser, TokenValue::RightBracket)?.meta;
|
||||
span.subsume(end_span);
|
||||
ArraySize::Constant(constant)
|
||||
};
|
||||
},
|
||||
constant_span,
|
||||
);
|
||||
let end_span = self.expect(frontend, TokenValue::RightBracket)?.meta;
|
||||
span.subsume(end_span);
|
||||
ArraySize::Constant(constant)
|
||||
};
|
||||
|
||||
parser
|
||||
frontend
|
||||
.layouter
|
||||
.update(&parser.module.types, &parser.module.constants)
|
||||
.update(&frontend.module.types, &frontend.module.constants)
|
||||
.unwrap();
|
||||
let stride = parser.layouter[*ty].to_stride();
|
||||
*ty = parser.module.types.insert(
|
||||
let stride = frontend.layouter[*ty].to_stride();
|
||||
*ty = frontend.module.types.insert(
|
||||
Type {
|
||||
name: None,
|
||||
inner: TypeInner::Array {
|
||||
@@ -75,31 +76,34 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_type(&mut self, parser: &mut Parser) -> Result<(Option<Handle<Type>>, Span)> {
|
||||
let token = self.bump(parser)?;
|
||||
pub fn parse_type(&mut self, frontend: &mut Frontend) -> Result<(Option<Handle<Type>>, Span)> {
|
||||
let token = self.bump(frontend)?;
|
||||
let mut handle = match token.value {
|
||||
TokenValue::Void => return Ok((None, token.meta)),
|
||||
TokenValue::TypeName(ty) => parser.module.types.insert(ty, token.meta),
|
||||
TokenValue::TypeName(ty) => frontend.module.types.insert(ty, token.meta),
|
||||
TokenValue::Struct => {
|
||||
let mut meta = token.meta;
|
||||
let ty_name = self.expect_ident(parser)?.0;
|
||||
self.expect(parser, TokenValue::LeftBrace)?;
|
||||
let ty_name = self.expect_ident(frontend)?.0;
|
||||
self.expect(frontend, TokenValue::LeftBrace)?;
|
||||
let mut members = Vec::new();
|
||||
let span =
|
||||
self.parse_struct_declaration_list(parser, &mut members, StructLayout::Std140)?;
|
||||
let end_meta = self.expect(parser, TokenValue::RightBrace)?.meta;
|
||||
let span = self.parse_struct_declaration_list(
|
||||
frontend,
|
||||
&mut members,
|
||||
StructLayout::Std140,
|
||||
)?;
|
||||
let end_meta = self.expect(frontend, TokenValue::RightBrace)?.meta;
|
||||
meta.subsume(end_meta);
|
||||
let ty = parser.module.types.insert(
|
||||
let ty = frontend.module.types.insert(
|
||||
Type {
|
||||
name: Some(ty_name.clone()),
|
||||
inner: TypeInner::Struct { members, span },
|
||||
},
|
||||
meta,
|
||||
);
|
||||
parser.lookup_type.insert(ty_name, ty);
|
||||
frontend.lookup_type.insert(ty_name, ty);
|
||||
ty
|
||||
}
|
||||
TokenValue::Identifier(ident) => match parser.lookup_type.get(&ident) {
|
||||
TokenValue::Identifier(ident) => match frontend.lookup_type.get(&ident) {
|
||||
Some(ty) => *ty,
|
||||
None => {
|
||||
return Err(Error {
|
||||
@@ -124,12 +128,12 @@ impl<'source> ParsingContext<'source> {
|
||||
};
|
||||
|
||||
let mut span = token.meta;
|
||||
self.parse_array_specifier(parser, &mut span, &mut handle)?;
|
||||
self.parse_array_specifier(frontend, &mut span, &mut handle)?;
|
||||
Ok((Some(handle), span))
|
||||
}
|
||||
|
||||
pub fn parse_type_non_void(&mut self, parser: &mut Parser) -> Result<(Handle<Type>, Span)> {
|
||||
let (maybe_ty, meta) = self.parse_type(parser)?;
|
||||
pub fn parse_type_non_void(&mut self, frontend: &mut Frontend) -> Result<(Handle<Type>, Span)> {
|
||||
let (maybe_ty, meta) = self.parse_type(frontend)?;
|
||||
let ty = maybe_ty.ok_or_else(|| Error {
|
||||
kind: ErrorKind::SemanticError("Type can't be void".into()),
|
||||
meta,
|
||||
@@ -138,8 +142,8 @@ impl<'source> ParsingContext<'source> {
|
||||
Ok((ty, meta))
|
||||
}
|
||||
|
||||
pub fn peek_type_qualifier(&mut self, parser: &mut Parser) -> bool {
|
||||
self.peek(parser).map_or(false, |t| match t.value {
|
||||
pub fn peek_type_qualifier(&mut self, frontend: &mut Frontend) -> bool {
|
||||
self.peek(frontend).map_or(false, |t| match t.value {
|
||||
TokenValue::Invariant
|
||||
| TokenValue::Interpolation(_)
|
||||
| TokenValue::Sampling(_)
|
||||
@@ -157,15 +161,18 @@ impl<'source> ParsingContext<'source> {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_type_qualifiers<'a>(&mut self, parser: &mut Parser) -> Result<TypeQualifiers<'a>> {
|
||||
pub fn parse_type_qualifiers<'a>(
|
||||
&mut self,
|
||||
frontend: &mut Frontend,
|
||||
) -> Result<TypeQualifiers<'a>> {
|
||||
let mut qualifiers = TypeQualifiers::default();
|
||||
|
||||
while self.peek_type_qualifier(parser) {
|
||||
let token = self.bump(parser)?;
|
||||
while self.peek_type_qualifier(frontend) {
|
||||
let token = self.bump(frontend)?;
|
||||
|
||||
// Handle layout qualifiers outside the match since this can push multiple values
|
||||
if token.value == TokenValue::Layout {
|
||||
self.parse_layout_qualifier_id_list(parser, &mut qualifiers)?;
|
||||
self.parse_layout_qualifier_id_list(frontend, &mut qualifiers)?;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -174,7 +181,7 @@ impl<'source> ParsingContext<'source> {
|
||||
match token.value {
|
||||
TokenValue::Invariant => {
|
||||
if qualifiers.invariant.is_some() {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
"Cannot use more than one invariant qualifier per declaration"
|
||||
.into(),
|
||||
@@ -187,7 +194,7 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
TokenValue::Interpolation(i) => {
|
||||
if qualifiers.interpolation.is_some() {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
"Cannot use more than one interpolation qualifier per declaration"
|
||||
.into(),
|
||||
@@ -225,7 +232,7 @@ impl<'source> ParsingContext<'source> {
|
||||
if StorageQualifier::AddressSpace(AddressSpace::Function)
|
||||
!= qualifiers.storage.0
|
||||
{
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
"Cannot use more than one storage qualifier per declaration".into(),
|
||||
),
|
||||
@@ -237,7 +244,7 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
TokenValue::Sampling(s) => {
|
||||
if qualifiers.sampling.is_some() {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
"Cannot use more than one sampling qualifier per declaration"
|
||||
.into(),
|
||||
@@ -250,7 +257,7 @@ impl<'source> ParsingContext<'source> {
|
||||
}
|
||||
TokenValue::PrecisionQualifier(p) => {
|
||||
if qualifiers.precision.is_some() {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
"Cannot use more than one precision qualifier per declaration"
|
||||
.into(),
|
||||
@@ -266,7 +273,7 @@ impl<'source> ParsingContext<'source> {
|
||||
.storage_access
|
||||
.get_or_insert((crate::StorageAccess::all(), Span::default()));
|
||||
if !storage_access.0.contains(!access) {
|
||||
parser.errors.push(Error {
|
||||
frontend.errors.push(Error {
|
||||
kind: ErrorKind::SemanticError(
|
||||
"The same memory qualifier can only be used once".into(),
|
||||
),
|
||||
@@ -287,20 +294,20 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
pub fn parse_layout_qualifier_id_list(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
qualifiers: &mut TypeQualifiers,
|
||||
) -> Result<()> {
|
||||
self.expect(parser, TokenValue::LeftParen)?;
|
||||
self.expect(frontend, TokenValue::LeftParen)?;
|
||||
loop {
|
||||
self.parse_layout_qualifier_id(parser, &mut qualifiers.layout_qualifiers)?;
|
||||
self.parse_layout_qualifier_id(frontend, &mut qualifiers.layout_qualifiers)?;
|
||||
|
||||
if self.bump_if(parser, TokenValue::Comma).is_some() {
|
||||
if self.bump_if(frontend, TokenValue::Comma).is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
let token = self.expect(parser, TokenValue::RightParen)?;
|
||||
let token = self.expect(frontend, TokenValue::RightParen)?;
|
||||
qualifiers.span.subsume(token.meta);
|
||||
|
||||
Ok(())
|
||||
@@ -308,14 +315,14 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
pub fn parse_layout_qualifier_id(
|
||||
&mut self,
|
||||
parser: &mut Parser,
|
||||
frontend: &mut Frontend,
|
||||
qualifiers: &mut crate::FastHashMap<QualifierKey, (QualifierValue, Span)>,
|
||||
) -> Result<()> {
|
||||
// layout_qualifier_id:
|
||||
// IDENTIFIER
|
||||
// IDENTIFIER EQUAL constant_expression
|
||||
// SHARED
|
||||
let mut token = self.bump(parser)?;
|
||||
let mut token = self.bump(frontend)?;
|
||||
match token.value {
|
||||
TokenValue::Identifier(name) => {
|
||||
let (key, value) = match name.as_str() {
|
||||
@@ -332,11 +339,11 @@ impl<'source> ParsingContext<'source> {
|
||||
(QualifierKey::Format, QualifierValue::Format(format))
|
||||
} else {
|
||||
let key = QualifierKey::String(name.into());
|
||||
let value = if self.bump_if(parser, TokenValue::Assign).is_some() {
|
||||
let (value, end_meta) = match self.parse_uint_constant(parser) {
|
||||
let value = if self.bump_if(frontend, TokenValue::Assign).is_some() {
|
||||
let (value, end_meta) = match self.parse_uint_constant(frontend) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
parser.errors.push(e);
|
||||
frontend.errors.push(e);
|
||||
(0, Span::default())
|
||||
}
|
||||
};
|
||||
@@ -354,7 +361,7 @@ impl<'source> ParsingContext<'source> {
|
||||
|
||||
qualifiers.insert(key, (value, token.meta));
|
||||
}
|
||||
_ => parser.errors.push(Error {
|
||||
_ => frontend.errors.push(Error {
|
||||
kind: ErrorKind::InvalidToken(token.value, vec![ExpectedToken::Identifier]),
|
||||
meta: token.meta,
|
||||
}),
|
||||
@@ -363,11 +370,11 @@ impl<'source> ParsingContext<'source> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn peek_type_name(&mut self, parser: &mut Parser) -> bool {
|
||||
self.peek(parser).map_or(false, |t| match t.value {
|
||||
pub fn peek_type_name(&mut self, frontend: &mut Frontend) -> bool {
|
||||
self.peek(frontend).map_or(false, |t| match t.value {
|
||||
TokenValue::TypeName(_) | TokenValue::Void => true,
|
||||
TokenValue::Struct => true,
|
||||
TokenValue::Identifier(ref ident) => parser.lookup_type.contains_key(ident),
|
||||
TokenValue::Identifier(ref ident) => frontend.lookup_type.contains_key(ident),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,18 +3,18 @@ use super::{
|
||||
error::ExpectedToken,
|
||||
error::{Error, ErrorKind},
|
||||
token::TokenValue,
|
||||
Options, Parser, Span,
|
||||
Frontend, Options, Span,
|
||||
};
|
||||
use crate::ShaderStage;
|
||||
use pp_rs::token::PreprocessorError;
|
||||
|
||||
#[test]
|
||||
fn version() {
|
||||
let mut parser = Parser::default();
|
||||
let mut frontend = Frontend::default();
|
||||
|
||||
// invalid versions
|
||||
assert_eq!(
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
"#version 99000\n void main(){}",
|
||||
@@ -28,7 +28,7 @@ fn version() {
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
"#version 449\n void main(){}",
|
||||
@@ -42,7 +42,7 @@ fn version() {
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
"#version 450 smart\n void main(){}",
|
||||
@@ -56,7 +56,7 @@ fn version() {
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
"#version 450\nvoid main(){} #version 450",
|
||||
@@ -79,45 +79,45 @@ fn version() {
|
||||
);
|
||||
|
||||
// valid versions
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
" # version 450\nvoid main() {}",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(parser.metadata().version, parser.metadata().profile),
|
||||
(frontend.metadata().version, frontend.metadata().profile),
|
||||
(450, Profile::Core)
|
||||
);
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
"#version 450\nvoid main() {}",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(parser.metadata().version, parser.metadata().profile),
|
||||
(frontend.metadata().version, frontend.metadata().profile),
|
||||
(450, Profile::Core)
|
||||
);
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
"#version 450 core\nvoid main(void) {}",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(parser.metadata().version, parser.metadata().profile),
|
||||
(frontend.metadata().version, frontend.metadata().profile),
|
||||
(450, Profile::Core)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_flow() {
|
||||
let mut parser = Parser::default();
|
||||
let mut frontend = Frontend::default();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -133,7 +133,7 @@ fn control_flow() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -147,7 +147,7 @@ fn control_flow() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -170,7 +170,7 @@ fn control_flow() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -188,7 +188,7 @@ fn control_flow() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -208,9 +208,9 @@ fn control_flow() {
|
||||
|
||||
#[test]
|
||||
fn declarations() {
|
||||
let mut parser = Parser::default();
|
||||
let mut frontend = Frontend::default();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -227,7 +227,7 @@ fn declarations() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -244,7 +244,7 @@ fn declarations() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -261,7 +261,7 @@ fn declarations() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -278,7 +278,7 @@ fn declarations() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -297,7 +297,7 @@ fn declarations() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -309,7 +309,7 @@ fn declarations() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -324,9 +324,9 @@ fn declarations() {
|
||||
|
||||
#[test]
|
||||
fn textures() {
|
||||
let mut parser = Parser::default();
|
||||
let mut frontend = Frontend::default();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -346,9 +346,9 @@ fn textures() {
|
||||
|
||||
#[test]
|
||||
fn functions() {
|
||||
let mut parser = Parser::default();
|
||||
let mut frontend = Frontend::default();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -361,7 +361,7 @@ fn functions() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -375,7 +375,7 @@ fn functions() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -387,7 +387,7 @@ fn functions() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -402,7 +402,7 @@ fn functions() {
|
||||
.unwrap();
|
||||
|
||||
// Function overloading
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -429,7 +429,7 @@ fn functions() {
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -455,7 +455,7 @@ fn functions() {
|
||||
|
||||
println!();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -474,7 +474,7 @@ fn functions() {
|
||||
.unwrap();
|
||||
|
||||
// Nested function call
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -489,7 +489,7 @@ fn functions() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -510,9 +510,9 @@ fn functions() {
|
||||
#[test]
|
||||
fn constants() {
|
||||
use crate::{Constant, ConstantInner, ScalarValue};
|
||||
let mut parser = Parser::default();
|
||||
let mut frontend = Frontend::default();
|
||||
|
||||
let module = parser
|
||||
let module = frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -556,9 +556,9 @@ fn constants() {
|
||||
|
||||
#[test]
|
||||
fn function_overloading() {
|
||||
let mut parser = Parser::default();
|
||||
let mut frontend = Frontend::default();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -582,9 +582,9 @@ fn function_overloading() {
|
||||
|
||||
#[test]
|
||||
fn implicit_conversions() {
|
||||
let mut parser = Parser::default();
|
||||
let mut frontend = Frontend::default();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -599,7 +599,7 @@ fn implicit_conversions() {
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -621,7 +621,7 @@ fn implicit_conversions() {
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -645,9 +645,9 @@ fn implicit_conversions() {
|
||||
|
||||
#[test]
|
||||
fn structs() {
|
||||
let mut parser = Parser::default();
|
||||
let mut frontend = Frontend::default();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -661,7 +661,7 @@ fn structs() {
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -675,7 +675,7 @@ fn structs() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -690,7 +690,7 @@ fn structs() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -706,7 +706,7 @@ fn structs() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -718,7 +718,7 @@ fn structs() {
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -735,9 +735,9 @@ fn structs() {
|
||||
|
||||
#[test]
|
||||
fn swizzles() {
|
||||
let mut parser = Parser::default();
|
||||
let mut frontend = Frontend::default();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -752,7 +752,7 @@ fn swizzles() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -765,7 +765,7 @@ fn swizzles() {
|
||||
)
|
||||
.unwrap_err();
|
||||
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -781,10 +781,10 @@ fn swizzles() {
|
||||
|
||||
#[test]
|
||||
fn expressions() {
|
||||
let mut parser = Parser::default();
|
||||
let mut frontend = Frontend::default();
|
||||
|
||||
// Vector indexing
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -800,7 +800,7 @@ fn expressions() {
|
||||
.unwrap();
|
||||
|
||||
// Prefix increment/decrement
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
@@ -816,7 +816,7 @@ fn expressions() {
|
||||
.unwrap();
|
||||
|
||||
// Dynamic indexing of array
|
||||
parser
|
||||
frontend
|
||||
.parse(
|
||||
&Options::from(ShaderStage::Vertex),
|
||||
r#"
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use super::{constants::ConstantSolver, context::Context, Error, ErrorKind, Parser, Result, Span};
|
||||
use super::{
|
||||
constants::ConstantSolver, context::Context, Error, ErrorKind, Frontend, Result, Span,
|
||||
};
|
||||
use crate::{
|
||||
proc::ResolveContext, Bytes, Constant, Expression, Handle, ImageClass, ImageDimension,
|
||||
ScalarKind, Type, TypeInner, VectorSize,
|
||||
@@ -224,7 +226,7 @@ pub const fn type_power(kind: ScalarKind, width: Bytes) -> Option<u32> {
|
||||
})
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
impl Frontend {
|
||||
/// Resolves the types of the expressions until `expr` (inclusive)
|
||||
///
|
||||
/// This needs to be done before the [`typifier`] can be queried for
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::{
|
||||
ast::*,
|
||||
context::{Context, ExprPos},
|
||||
error::{Error, ErrorKind},
|
||||
Parser, Result, Span,
|
||||
Frontend, Result, Span,
|
||||
};
|
||||
use crate::{
|
||||
AddressSpace, Binding, Block, BuiltIn, Constant, Expression, GlobalVariable, Handle,
|
||||
@@ -18,7 +18,7 @@ pub struct VarDeclaration<'a, 'key> {
|
||||
pub meta: Span,
|
||||
}
|
||||
|
||||
/// Information about a builtin used in [`add_builtin`](Parser::add_builtin).
|
||||
/// Information about a builtin used in [`add_builtin`](Frontend::add_builtin).
|
||||
struct BuiltInData {
|
||||
/// The type of the builtin.
|
||||
inner: TypeInner,
|
||||
@@ -35,7 +35,7 @@ pub enum GlobalOrConstant {
|
||||
Constant(Handle<Constant>),
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
impl Frontend {
|
||||
/// Adds a builtin and returns a variable reference to it
|
||||
fn add_builtin(
|
||||
&mut self,
|
||||
|
||||
@@ -14,7 +14,7 @@ pub struct MergeInstruction {
|
||||
pub continue_block_id: Option<BlockId>,
|
||||
}
|
||||
|
||||
impl<I: Iterator<Item = u32>> super::Parser<I> {
|
||||
impl<I: Iterator<Item = u32>> super::Frontend<I> {
|
||||
// Registers a function call. It will generate a dummy handle to call, which
|
||||
// gets resolved after all the functions are processed.
|
||||
pub(super) fn add_call(
|
||||
|
||||
@@ -218,7 +218,7 @@ pub(super) fn patch_comparison_type(
|
||||
true
|
||||
}
|
||||
|
||||
impl<I: Iterator<Item = u32>> super::Parser<I> {
|
||||
impl<I: Iterator<Item = u32>> super::Frontend<I> {
|
||||
pub(super) fn parse_image_couple(&mut self) -> Result<(), Error> {
|
||||
let _result_type_id = self.next()?;
|
||||
let result_id = self.next()?;
|
||||
|
||||
@@ -514,7 +514,7 @@ enum SignAnchor {
|
||||
Operand,
|
||||
}
|
||||
|
||||
pub struct Parser<I> {
|
||||
pub struct Frontend<I> {
|
||||
data: I,
|
||||
data_offset: usize,
|
||||
state: ModuleState,
|
||||
@@ -565,9 +565,9 @@ pub struct Parser<I> {
|
||||
builtin_usage: FastHashSet<crate::BuiltIn>,
|
||||
}
|
||||
|
||||
impl<I: Iterator<Item = u32>> Parser<I> {
|
||||
impl<I: Iterator<Item = u32>> Frontend<I> {
|
||||
pub fn new(data: I, options: &Options) -> Self {
|
||||
Parser {
|
||||
Frontend {
|
||||
data,
|
||||
data_offset: 0,
|
||||
state: ModuleState::Empty,
|
||||
@@ -5095,7 +5095,7 @@ pub fn parse_u8_slice(data: &[u8], options: &Options) -> Result<crate::Module, E
|
||||
let words = data
|
||||
.chunks(4)
|
||||
.map(|c| u32::from_le_bytes(c.try_into().unwrap()));
|
||||
Parser::new(words, options).parse()
|
||||
Frontend::new(words, options).parse()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,672 @@
|
||||
use crate::front::wgsl::parse::lexer::Token;
|
||||
use crate::proc::{Alignment, ResolveError};
|
||||
use crate::{SourceLocation, Span};
|
||||
use codespan_reporting::diagnostic::{Diagnostic, Label};
|
||||
use codespan_reporting::files::SimpleFile;
|
||||
use codespan_reporting::term;
|
||||
use std::borrow::Cow;
|
||||
use std::ops::Range;
|
||||
use termcolor::{ColorChoice, NoColor, StandardStream};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ParseError {
|
||||
message: String,
|
||||
labels: Vec<(Span, Cow<'static, str>)>,
|
||||
notes: Vec<String>,
|
||||
}
|
||||
|
||||
impl ParseError {
|
||||
pub fn labels(&self) -> impl Iterator<Item = (Span, &str)> + ExactSizeIterator + '_ {
|
||||
self.labels
|
||||
.iter()
|
||||
.map(|&(span, ref msg)| (span, msg.as_ref()))
|
||||
}
|
||||
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
|
||||
fn diagnostic(&self) -> Diagnostic<()> {
|
||||
let diagnostic = Diagnostic::error()
|
||||
.with_message(self.message.to_string())
|
||||
.with_labels(
|
||||
self.labels
|
||||
.iter()
|
||||
.map(|label| {
|
||||
Label::primary((), label.0.to_range().unwrap())
|
||||
.with_message(label.1.to_string())
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
.with_notes(
|
||||
self.notes
|
||||
.iter()
|
||||
.map(|note| format!("note: {note}"))
|
||||
.collect(),
|
||||
);
|
||||
diagnostic
|
||||
}
|
||||
|
||||
/// Emits a summary of the error to standard error stream.
|
||||
pub fn emit_to_stderr(&self, source: &str) {
|
||||
self.emit_to_stderr_with_path(source, "wgsl")
|
||||
}
|
||||
|
||||
/// Emits a summary of the error to standard error stream.
|
||||
pub fn emit_to_stderr_with_path(&self, source: &str, path: &str) {
|
||||
let files = SimpleFile::new(path, source);
|
||||
let config = codespan_reporting::term::Config::default();
|
||||
let writer = StandardStream::stderr(ColorChoice::Auto);
|
||||
term::emit(&mut writer.lock(), &config, &files, &self.diagnostic())
|
||||
.expect("cannot write error");
|
||||
}
|
||||
|
||||
/// Emits a summary of the error to a string.
|
||||
pub fn emit_to_string(&self, source: &str) -> String {
|
||||
self.emit_to_string_with_path(source, "wgsl")
|
||||
}
|
||||
|
||||
/// Emits a summary of the error to a string.
|
||||
pub fn emit_to_string_with_path(&self, source: &str, path: &str) -> String {
|
||||
let files = SimpleFile::new(path, source);
|
||||
let config = codespan_reporting::term::Config::default();
|
||||
let mut writer = NoColor::new(Vec::new());
|
||||
term::emit(&mut writer, &config, &files, &self.diagnostic()).expect("cannot write error");
|
||||
String::from_utf8(writer.into_inner()).unwrap()
|
||||
}
|
||||
|
||||
/// Returns a [`SourceLocation`] for the first label in the error message.
|
||||
pub fn location(&self, source: &str) -> Option<SourceLocation> {
|
||||
self.labels.get(0).map(|label| label.0.location(source))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ParseError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ParseError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub enum ExpectedToken<'a> {
|
||||
Token(Token<'a>),
|
||||
Identifier,
|
||||
Number,
|
||||
Integer,
|
||||
/// A compile-time constant expression.
|
||||
Constant,
|
||||
/// Expected: constant, parenthesized expression, identifier
|
||||
PrimaryExpression,
|
||||
/// Expected: assignment, increment/decrement expression
|
||||
Assignment,
|
||||
/// Expected: 'case', 'default', '}'
|
||||
SwitchItem,
|
||||
/// Expected: ',', ')'
|
||||
WorkgroupSizeSeparator,
|
||||
/// Expected: 'struct', 'let', 'var', 'type', ';', 'fn', eof
|
||||
GlobalItem,
|
||||
/// Expected a type.
|
||||
Type,
|
||||
/// Access of `var`, `let`, `const`.
|
||||
Variable,
|
||||
/// Access of a function
|
||||
Function,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Error, PartialEq)]
|
||||
pub enum NumberError {
|
||||
#[error("invalid numeric literal format")]
|
||||
Invalid,
|
||||
#[error("numeric literal not representable by target type")]
|
||||
NotRepresentable,
|
||||
#[error("unimplemented f16 type")]
|
||||
UnimplementedF16,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub enum InvalidAssignmentType {
|
||||
Other,
|
||||
Swizzle,
|
||||
ImmutableBinding,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Error<'a> {
|
||||
Unexpected(Span, ExpectedToken<'a>),
|
||||
UnexpectedComponents(Span),
|
||||
BadNumber(Span, NumberError),
|
||||
/// A negative signed integer literal where both signed and unsigned,
|
||||
/// but only non-negative literals are allowed.
|
||||
NegativeInt(Span),
|
||||
BadU32Constant(Span),
|
||||
BadMatrixScalarKind(Span, crate::ScalarKind, u8),
|
||||
BadAccessor(Span),
|
||||
BadTexture(Span),
|
||||
BadTypeCast {
|
||||
span: Span,
|
||||
from_type: String,
|
||||
to_type: String,
|
||||
},
|
||||
BadTextureSampleType {
|
||||
span: Span,
|
||||
kind: crate::ScalarKind,
|
||||
width: u8,
|
||||
},
|
||||
BadIncrDecrReferenceType(Span),
|
||||
InvalidResolve(ResolveError),
|
||||
InvalidForInitializer(Span),
|
||||
/// A break if appeared outside of a continuing block
|
||||
InvalidBreakIf(Span),
|
||||
InvalidGatherComponent(Span),
|
||||
InvalidConstructorComponentType(Span, i32),
|
||||
InvalidIdentifierUnderscore(Span),
|
||||
ReservedIdentifierPrefix(Span),
|
||||
UnknownAddressSpace(Span),
|
||||
UnknownAttribute(Span),
|
||||
UnknownBuiltin(Span),
|
||||
UnknownAccess(Span),
|
||||
UnknownIdent(Span, &'a str),
|
||||
UnknownScalarType(Span),
|
||||
UnknownType(Span),
|
||||
UnknownStorageFormat(Span),
|
||||
UnknownConservativeDepth(Span),
|
||||
SizeAttributeTooLow(Span, u32),
|
||||
AlignAttributeTooLow(Span, Alignment),
|
||||
NonPowerOfTwoAlignAttribute(Span),
|
||||
InconsistentBinding(Span),
|
||||
TypeNotConstructible(Span),
|
||||
TypeNotInferrable(Span),
|
||||
InitializationTypeMismatch(Span, String, String),
|
||||
MissingType(Span),
|
||||
MissingAttribute(&'static str, Span),
|
||||
InvalidAtomicPointer(Span),
|
||||
InvalidAtomicOperandType(Span),
|
||||
Pointer(&'static str, Span),
|
||||
NotPointer(Span),
|
||||
NotReference(&'static str, Span),
|
||||
InvalidAssignment {
|
||||
span: Span,
|
||||
ty: InvalidAssignmentType,
|
||||
},
|
||||
ReservedKeyword(Span),
|
||||
/// Redefinition of an identifier (used for both module-scope and local redefinitions).
|
||||
Redefinition {
|
||||
/// Span of the identifier in the previous definition.
|
||||
previous: Span,
|
||||
|
||||
/// Span of the identifier in the new definition.
|
||||
current: Span,
|
||||
},
|
||||
/// A declaration refers to itself directly.
|
||||
RecursiveDeclaration {
|
||||
/// The location of the name of the declaration.
|
||||
ident: Span,
|
||||
|
||||
/// The point at which it is used.
|
||||
usage: Span,
|
||||
},
|
||||
/// A declaration refers to itself indirectly, through one or more other
|
||||
/// definitions.
|
||||
CyclicDeclaration {
|
||||
/// The location of the name of some declaration in the cycle.
|
||||
ident: Span,
|
||||
|
||||
/// The edges of the cycle of references.
|
||||
///
|
||||
/// Each `(decl, reference)` pair indicates that the declaration whose
|
||||
/// name is `decl` has an identifier at `reference` whose definition is
|
||||
/// the next declaration in the cycle. The last pair's `reference` is
|
||||
/// the same identifier as `ident`, above.
|
||||
path: Vec<(Span, Span)>,
|
||||
},
|
||||
ConstExprUnsupported(Span),
|
||||
InvalidSwitchValue {
|
||||
uint: bool,
|
||||
span: Span,
|
||||
},
|
||||
CalledEntryPoint(Span),
|
||||
WrongArgumentCount {
|
||||
span: Span,
|
||||
expected: Range<u32>,
|
||||
found: u32,
|
||||
},
|
||||
FunctionReturnsVoid(Span),
|
||||
Other,
|
||||
}
|
||||
|
||||
impl<'a> Error<'a> {
|
||||
pub(crate) fn as_parse_error(&self, source: &'a str) -> ParseError {
|
||||
match *self {
|
||||
Error::Unexpected(unexpected_span, expected) => {
|
||||
let expected_str = match expected {
|
||||
ExpectedToken::Token(token) => {
|
||||
match token {
|
||||
Token::Separator(c) => format!("'{c}'"),
|
||||
Token::Paren(c) => format!("'{c}'"),
|
||||
Token::Attribute => "@".to_string(),
|
||||
Token::Number(_) => "number".to_string(),
|
||||
Token::Word(s) => s.to_string(),
|
||||
Token::Operation(c) => format!("operation ('{c}')"),
|
||||
Token::LogicalOperation(c) => format!("logical operation ('{c}')"),
|
||||
Token::ShiftOperation(c) => format!("bitshift ('{c}{c}')"),
|
||||
Token::AssignmentOperation(c) if c=='<' || c=='>' => format!("bitshift ('{c}{c}=')"),
|
||||
Token::AssignmentOperation(c) => format!("operation ('{c}=')"),
|
||||
Token::IncrementOperation => "increment operation".to_string(),
|
||||
Token::DecrementOperation => "decrement operation".to_string(),
|
||||
Token::Arrow => "->".to_string(),
|
||||
Token::Unknown(c) => format!("unknown ('{c}')"),
|
||||
Token::Trivia => "trivia".to_string(),
|
||||
Token::End => "end".to_string(),
|
||||
}
|
||||
}
|
||||
ExpectedToken::Identifier => "identifier".to_string(),
|
||||
ExpectedToken::Number => "32-bit signed integer literal".to_string(),
|
||||
ExpectedToken::Integer => "unsigned/signed integer literal".to_string(),
|
||||
ExpectedToken::Constant => "compile-time constant".to_string(),
|
||||
ExpectedToken::PrimaryExpression => "expression".to_string(),
|
||||
ExpectedToken::Assignment => "assignment or increment/decrement".to_string(),
|
||||
ExpectedToken::SwitchItem => "switch item ('case' or 'default') or a closing curly bracket to signify the end of the switch statement ('}')".to_string(),
|
||||
ExpectedToken::WorkgroupSizeSeparator => "workgroup size separator (',') or a closing parenthesis".to_string(),
|
||||
ExpectedToken::GlobalItem => "global item ('struct', 'const', 'var', 'type', ';', 'fn') or the end of the file".to_string(),
|
||||
ExpectedToken::Type => "type".to_string(),
|
||||
ExpectedToken::Variable => "variable access".to_string(),
|
||||
ExpectedToken::Function => "function name".to_string(),
|
||||
};
|
||||
ParseError {
|
||||
message: format!(
|
||||
"expected {}, found '{}'",
|
||||
expected_str, &source[unexpected_span],
|
||||
),
|
||||
labels: vec![(unexpected_span, format!("expected {expected_str}").into())],
|
||||
notes: vec![],
|
||||
}
|
||||
}
|
||||
Error::UnexpectedComponents(bad_span) => ParseError {
|
||||
message: "unexpected components".to_string(),
|
||||
labels: vec![(bad_span, "unexpected components".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::BadNumber(bad_span, ref err) => ParseError {
|
||||
message: format!("{}: `{}`", err, &source[bad_span],),
|
||||
labels: vec![(bad_span, err.to_string().into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::NegativeInt(bad_span) => ParseError {
|
||||
message: format!(
|
||||
"expected non-negative integer literal, found `{}`",
|
||||
&source[bad_span],
|
||||
),
|
||||
labels: vec![(bad_span, "expected non-negative integer".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::BadU32Constant(bad_span) => ParseError {
|
||||
message: format!(
|
||||
"expected unsigned integer constant expression, found `{}`",
|
||||
&source[bad_span],
|
||||
),
|
||||
labels: vec![(bad_span, "expected unsigned integer".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::BadMatrixScalarKind(span, kind, width) => ParseError {
|
||||
message: format!(
|
||||
"matrix scalar type must be floating-point, but found `{}`",
|
||||
kind.to_wgsl(width)
|
||||
),
|
||||
labels: vec![(span, "must be floating-point (e.g. `f32`)".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::BadAccessor(accessor_span) => ParseError {
|
||||
message: format!("invalid field accessor `{}`", &source[accessor_span],),
|
||||
labels: vec![(accessor_span, "invalid accessor".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::UnknownIdent(ident_span, ident) => ParseError {
|
||||
message: format!("no definition in scope for identifier: '{ident}'"),
|
||||
labels: vec![(ident_span, "unknown identifier".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::UnknownScalarType(bad_span) => ParseError {
|
||||
message: format!("unknown scalar type: '{}'", &source[bad_span]),
|
||||
labels: vec![(bad_span, "unknown scalar type".into())],
|
||||
notes: vec!["Valid scalar types are f32, f64, i32, u32, bool".into()],
|
||||
},
|
||||
Error::BadTextureSampleType { span, kind, width } => ParseError {
|
||||
message: format!(
|
||||
"texture sample type must be one of f32, i32 or u32, but found {}",
|
||||
kind.to_wgsl(width)
|
||||
),
|
||||
labels: vec![(span, "must be one of f32, i32 or u32".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::BadIncrDecrReferenceType(span) => ParseError {
|
||||
message:
|
||||
"increment/decrement operation requires reference type to be one of i32 or u32"
|
||||
.to_string(),
|
||||
labels: vec![(span, "must be a reference type of i32 or u32".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::BadTexture(bad_span) => ParseError {
|
||||
message: format!(
|
||||
"expected an image, but found '{}' which is not an image",
|
||||
&source[bad_span]
|
||||
),
|
||||
labels: vec![(bad_span, "not an image".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::BadTypeCast {
|
||||
span,
|
||||
ref from_type,
|
||||
ref to_type,
|
||||
} => {
|
||||
let msg = format!("cannot cast a {from_type} to a {to_type}");
|
||||
ParseError {
|
||||
message: msg.clone(),
|
||||
labels: vec![(span, msg.into())],
|
||||
notes: vec![],
|
||||
}
|
||||
}
|
||||
Error::InvalidResolve(ref resolve_error) => ParseError {
|
||||
message: resolve_error.to_string(),
|
||||
labels: vec![],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::InvalidForInitializer(bad_span) => ParseError {
|
||||
message: format!(
|
||||
"for(;;) initializer is not an assignment or a function call: '{}'",
|
||||
&source[bad_span]
|
||||
),
|
||||
labels: vec![(bad_span, "not an assignment or function call".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::InvalidBreakIf(bad_span) => ParseError {
|
||||
message: "A break if is only allowed in a continuing block".to_string(),
|
||||
labels: vec![(bad_span, "not in a continuing block".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::InvalidGatherComponent(bad_span) => ParseError {
|
||||
message: format!(
|
||||
"textureGather component '{}' doesn't exist, must be 0, 1, 2, or 3",
|
||||
&source[bad_span]
|
||||
),
|
||||
labels: vec![(bad_span, "invalid component".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::InvalidConstructorComponentType(bad_span, component) => ParseError {
|
||||
message: format!("invalid type for constructor component at index [{component}]"),
|
||||
labels: vec![(bad_span, "invalid component type".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::InvalidIdentifierUnderscore(bad_span) => ParseError {
|
||||
message: "Identifier can't be '_'".to_string(),
|
||||
labels: vec![(bad_span, "invalid identifier".into())],
|
||||
notes: vec![
|
||||
"Use phony assignment instead ('_ =' notice the absence of 'let' or 'var')"
|
||||
.to_string(),
|
||||
],
|
||||
},
|
||||
Error::ReservedIdentifierPrefix(bad_span) => ParseError {
|
||||
message: format!(
|
||||
"Identifier starts with a reserved prefix: '{}'",
|
||||
&source[bad_span]
|
||||
),
|
||||
labels: vec![(bad_span, "invalid identifier".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::UnknownAddressSpace(bad_span) => ParseError {
|
||||
message: format!("unknown address space: '{}'", &source[bad_span]),
|
||||
labels: vec![(bad_span, "unknown address space".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::UnknownAttribute(bad_span) => ParseError {
|
||||
message: format!("unknown attribute: '{}'", &source[bad_span]),
|
||||
labels: vec![(bad_span, "unknown attribute".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::UnknownBuiltin(bad_span) => ParseError {
|
||||
message: format!("unknown builtin: '{}'", &source[bad_span]),
|
||||
labels: vec![(bad_span, "unknown builtin".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::UnknownAccess(bad_span) => ParseError {
|
||||
message: format!("unknown access: '{}'", &source[bad_span]),
|
||||
labels: vec![(bad_span, "unknown access".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::UnknownStorageFormat(bad_span) => ParseError {
|
||||
message: format!("unknown storage format: '{}'", &source[bad_span]),
|
||||
labels: vec![(bad_span, "unknown storage format".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::UnknownConservativeDepth(bad_span) => ParseError {
|
||||
message: format!("unknown conservative depth: '{}'", &source[bad_span]),
|
||||
labels: vec![(bad_span, "unknown conservative depth".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::UnknownType(bad_span) => ParseError {
|
||||
message: format!("unknown type: '{}'", &source[bad_span]),
|
||||
labels: vec![(bad_span, "unknown type".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::SizeAttributeTooLow(bad_span, min_size) => ParseError {
|
||||
message: format!("struct member size must be at least {min_size}"),
|
||||
labels: vec![(bad_span, format!("must be at least {min_size}").into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::AlignAttributeTooLow(bad_span, min_align) => ParseError {
|
||||
message: format!("struct member alignment must be at least {min_align}"),
|
||||
labels: vec![(bad_span, format!("must be at least {min_align}").into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::NonPowerOfTwoAlignAttribute(bad_span) => ParseError {
|
||||
message: "struct member alignment must be a power of 2".to_string(),
|
||||
labels: vec![(bad_span, "must be a power of 2".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::InconsistentBinding(span) => ParseError {
|
||||
message: "input/output binding is not consistent".to_string(),
|
||||
labels: vec![(span, "input/output binding is not consistent".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::TypeNotConstructible(span) => ParseError {
|
||||
message: format!("type `{}` is not constructible", &source[span]),
|
||||
labels: vec![(span, "type is not constructible".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::TypeNotInferrable(span) => ParseError {
|
||||
message: "type can't be inferred".to_string(),
|
||||
labels: vec![(span, "type can't be inferred".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::InitializationTypeMismatch(name_span, ref expected_ty, ref got_ty) => {
|
||||
ParseError {
|
||||
message: format!(
|
||||
"the type of `{}` is expected to be `{}`, but got `{}`",
|
||||
&source[name_span], expected_ty, got_ty,
|
||||
),
|
||||
labels: vec![(
|
||||
name_span,
|
||||
format!("definition of `{}`", &source[name_span]).into(),
|
||||
)],
|
||||
notes: vec![],
|
||||
}
|
||||
}
|
||||
Error::MissingType(name_span) => ParseError {
|
||||
message: format!("variable `{}` needs a type", &source[name_span]),
|
||||
labels: vec![(
|
||||
name_span,
|
||||
format!("definition of `{}`", &source[name_span]).into(),
|
||||
)],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::MissingAttribute(name, name_span) => ParseError {
|
||||
message: format!(
|
||||
"variable `{}` needs a '{}' attribute",
|
||||
&source[name_span], name
|
||||
),
|
||||
labels: vec![(
|
||||
name_span,
|
||||
format!("definition of `{}`", &source[name_span]).into(),
|
||||
)],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::InvalidAtomicPointer(span) => ParseError {
|
||||
message: "atomic operation is done on a pointer to a non-atomic".to_string(),
|
||||
labels: vec![(span, "atomic pointer is invalid".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::InvalidAtomicOperandType(span) => ParseError {
|
||||
message: "atomic operand type is inconsistent with the operation".to_string(),
|
||||
labels: vec![(span, "atomic operand type is invalid".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::NotPointer(span) => ParseError {
|
||||
message: "the operand of the `*` operator must be a pointer".to_string(),
|
||||
labels: vec![(span, "expression is not a pointer".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::NotReference(what, span) => ParseError {
|
||||
message: format!("{what} must be a reference"),
|
||||
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::Pointer(what, span) => ParseError {
|
||||
message: format!("{what} must not be a pointer"),
|
||||
labels: vec![(span, "expression is a pointer".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::ReservedKeyword(name_span) => ParseError {
|
||||
message: format!("name `{}` is a reserved keyword", &source[name_span]),
|
||||
labels: vec![(
|
||||
name_span,
|
||||
format!("definition of `{}`", &source[name_span]).into(),
|
||||
)],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::Redefinition { previous, current } => ParseError {
|
||||
message: format!("redefinition of `{}`", &source[current]),
|
||||
labels: vec![
|
||||
(
|
||||
current,
|
||||
format!("redefinition of `{}`", &source[current]).into(),
|
||||
),
|
||||
(
|
||||
previous,
|
||||
format!("previous definition of `{}`", &source[previous]).into(),
|
||||
),
|
||||
],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::RecursiveDeclaration { ident, usage } => ParseError {
|
||||
message: format!("declaration of `{}` is recursive", &source[ident]),
|
||||
labels: vec![(ident, "".into()), (usage, "uses itself here".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::CyclicDeclaration { ident, ref path } => ParseError {
|
||||
message: format!("declaration of `{}` is cyclic", &source[ident]),
|
||||
labels: path
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, &(ident, usage))| {
|
||||
[
|
||||
(ident, "".into()),
|
||||
(
|
||||
usage,
|
||||
if i == path.len() - 1 {
|
||||
"ending the cycle".into()
|
||||
} else {
|
||||
format!("uses `{}`", &source[ident]).into()
|
||||
},
|
||||
),
|
||||
]
|
||||
})
|
||||
.collect(),
|
||||
notes: vec![],
|
||||
},
|
||||
Error::ConstExprUnsupported(span) => ParseError {
|
||||
message: "this constant expression is not supported".to_string(),
|
||||
labels: vec![(span, "expression is not supported".into())],
|
||||
notes: vec![
|
||||
"this should be fixed in a future version of Naga".into(),
|
||||
"https://github.com/gfx-rs/naga/issues/1829".into(),
|
||||
],
|
||||
},
|
||||
Error::InvalidSwitchValue { uint, span } => ParseError {
|
||||
message: "invalid switch value".to_string(),
|
||||
labels: vec![(
|
||||
span,
|
||||
if uint {
|
||||
"expected unsigned integer"
|
||||
} else {
|
||||
"expected signed integer"
|
||||
}
|
||||
.into(),
|
||||
)],
|
||||
notes: vec![if uint {
|
||||
format!("suffix the integer with a `u`: '{}u'", &source[span])
|
||||
} else {
|
||||
let span = span.to_range().unwrap();
|
||||
format!(
|
||||
"remove the `u` suffix: '{}'",
|
||||
&source[span.start..span.end - 1]
|
||||
)
|
||||
}],
|
||||
},
|
||||
Error::CalledEntryPoint(span) => ParseError {
|
||||
message: "entry point cannot be called".to_string(),
|
||||
labels: vec![(span, "entry point cannot be called".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::WrongArgumentCount {
|
||||
span,
|
||||
ref expected,
|
||||
found,
|
||||
} => ParseError {
|
||||
message: format!(
|
||||
"wrong number of arguments: expected {}, found {}",
|
||||
if expected.len() < 2 {
|
||||
format!("{}", expected.start)
|
||||
} else {
|
||||
format!("{}..{}", expected.start, expected.end)
|
||||
},
|
||||
found
|
||||
),
|
||||
labels: vec![(span, "wrong number of arguments".into())],
|
||||
notes: vec![],
|
||||
},
|
||||
Error::FunctionReturnsVoid(span) => ParseError {
|
||||
message: "function does not return any value".to_string(),
|
||||
labels: vec![(span, "".into())],
|
||||
notes: vec![
|
||||
"perhaps you meant to call the function in a separate statement?".into(),
|
||||
],
|
||||
},
|
||||
Error::Other => ParseError {
|
||||
message: "other error".to_string(),
|
||||
labels: vec![],
|
||||
notes: vec![],
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::{ast, Error};
|
||||
use super::Error;
|
||||
use crate::front::wgsl::parse::ast;
|
||||
use crate::{FastHashMap, Handle, Span};
|
||||
|
||||
/// A `GlobalDecl` list in which each definition occurs before all its uses.
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use crate::front::wgsl::parse::ast;
|
||||
use crate::{Handle, Span};
|
||||
|
||||
use super::{ast, Error, ExpressionContext, Lowerer, OutputContext};
|
||||
use crate::front::wgsl::error::Error;
|
||||
use crate::front::wgsl::lower::{ExpressionContext, Lowerer, OutputContext};
|
||||
use crate::proc::TypeResolution;
|
||||
|
||||
enum ConcreteConstructorHandle {
|
||||
@@ -133,7 +135,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
|
||||
///
|
||||
/// [`Construct`]: ast::Expression::Construct
|
||||
/// [`Call`]: ast::Expression::Call
|
||||
pub(super) fn construct(
|
||||
pub fn construct(
|
||||
&mut self,
|
||||
span: Span,
|
||||
constructor: &ast::ConstructorType<'source>,
|
||||
@@ -561,7 +563,7 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
|
||||
/// [`Type`]: crate::Type
|
||||
/// [`Constant`]: crate::Constant
|
||||
/// [`ctx.module`]: OutputContext::module
|
||||
pub(super) fn const_construct(
|
||||
pub fn const_construct(
|
||||
&mut self,
|
||||
span: Span,
|
||||
constructor: &ast::ConstructorType<'source>,
|
||||
File diff suppressed because it is too large.
Load diff
+30
-5139
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,4 @@
|
||||
use super::Number;
|
||||
use crate::front::wgsl::parse::number::Number;
|
||||
use crate::{Arena, FastHashSet, Handle, Span};
|
||||
use std::hash::Hash;
|
||||
|
||||
@@ -106,6 +106,9 @@ pub struct EntryPoint {
|
||||
pub workgroup_size: [u32; 3],
|
||||
}
|
||||
|
||||
#[cfg(doc)]
|
||||
use crate::front::wgsl::lower::{ExpressionContext, StatementContext};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Function<'a> {
|
||||
pub entry_point: Option<EntryPoint>,
|
||||
@@ -135,8 +138,8 @@ pub struct Function<'a> {
|
||||
/// [`LocalDecl`]: StatementKind::LocalDecl
|
||||
/// [`arguments`]: Function::arguments
|
||||
/// [`Ident`]: Expression::Ident
|
||||
/// [`StatementContext::local_table`]: super::StatementContext::local_table
|
||||
/// [`ExpressionContext::local_table`]: super::ExpressionContext::local_table
|
||||
/// [`StatementContext::local_table`]: StatementContext::local_table
|
||||
/// [`ExpressionContext::local_table`]: ExpressionContext::local_table
|
||||
pub locals: Arena<Local>,
|
||||
|
||||
pub body: Block<'a>,
|
||||
@@ -378,6 +381,9 @@ pub enum Literal {
|
||||
Number(Number),
|
||||
}
|
||||
|
||||
#[cfg(doc)]
|
||||
use crate::front::wgsl::lower::Lowerer;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Expression<'a> {
|
||||
Literal(Literal),
|
||||
@@ -423,7 +429,7 @@ pub enum Expression<'a> {
|
||||
/// everything's definition in hand, and can decide whether to emit a Naga
|
||||
/// [`Constant`], [`As`], [`Splat`], or [`Compose`] expression.
|
||||
///
|
||||
/// [`Lowerer::call`]: super::Lowerer::call
|
||||
/// [`Lowerer::call`]: Lowerer::call
|
||||
/// [`Constant`]: crate::Expression::Constant
|
||||
/// [`As`]: crate::Expression::As
|
||||
/// [`Splat`]: crate::Expression::Splat
|
||||
File renamed without changes.
@@ -1,6 +1,29 @@
|
||||
use super::{conv, number::consume_number, Error, ExpectedToken, Token, TokenSpan};
|
||||
use super::{number::consume_number, Error, ExpectedToken};
|
||||
use crate::front::wgsl::error::NumberError;
|
||||
use crate::front::wgsl::parse::{conv, Number};
|
||||
use crate::Span;
|
||||
|
||||
type TokenSpan<'a> = (Token<'a>, Span);
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub enum Token<'a> {
|
||||
Separator(char),
|
||||
Paren(char),
|
||||
Attribute,
|
||||
Number(Result<Number, NumberError>),
|
||||
Word(&'a str),
|
||||
Operation(char),
|
||||
LogicalOperation(char),
|
||||
ShiftOperation(char),
|
||||
AssignmentOperation(char),
|
||||
IncrementOperation,
|
||||
DecrementOperation,
|
||||
Arrow,
|
||||
Unknown(char),
|
||||
Trivia,
|
||||
End,
|
||||
}
|
||||
|
||||
fn consume_any(input: &str, what: impl Fn(char) -> bool) -> (&str, &str) {
|
||||
let pos = input.find(|c| !what(c)).unwrap_or(input.len());
|
||||
input.split_at(pos)
|
||||
@@ -176,15 +199,15 @@ fn is_word_part(c: char) -> bool {
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Lexer<'a> {
|
||||
pub(in crate::front::wgsl) struct Lexer<'a> {
|
||||
input: &'a str,
|
||||
pub(super) source: &'a str,
|
||||
pub(in crate::front::wgsl) source: &'a str,
|
||||
// The byte offset of the end of the last non-trivia token.
|
||||
last_end_offset: usize,
|
||||
}
|
||||
|
||||
impl<'a> Lexer<'a> {
|
||||
pub(super) const fn new(input: &'a str) -> Self {
|
||||
pub(in crate::front::wgsl) const fn new(input: &'a str) -> Self {
|
||||
Lexer {
|
||||
input,
|
||||
source: input,
|
||||
@@ -211,7 +234,7 @@ impl<'a> Lexer<'a> {
|
||||
Ok((res, Span::from(start..end)))
|
||||
}
|
||||
|
||||
pub(super) fn start_byte_offset(&mut self) -> usize {
|
||||
pub(in crate::front::wgsl) 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);
|
||||
@@ -234,7 +257,7 @@ impl<'a> Lexer<'a> {
|
||||
self.source.len() - self.input.len()
|
||||
}
|
||||
|
||||
pub(super) fn span_from(&self, offset: usize) -> Span {
|
||||
pub(in crate::front::wgsl) fn span_from(&self, offset: usize) -> Span {
|
||||
Span::from(offset..self.last_end_offset)
|
||||
}
|
||||
|
||||
@@ -243,7 +266,7 @@ impl<'a> Lexer<'a> {
|
||||
/// Assume we are a parse state where bit shift operators may
|
||||
/// occur, but not angle brackets.
|
||||
#[must_use]
|
||||
pub(super) fn next(&mut self) -> TokenSpan<'a> {
|
||||
pub(in crate::front::wgsl) fn next(&mut self) -> TokenSpan<'a> {
|
||||
self.next_impl(false)
|
||||
}
|
||||
|
||||
@@ -252,7 +275,7 @@ impl<'a> Lexer<'a> {
|
||||
/// Assume we are in a parse state where angle brackets may occur,
|
||||
/// but not bit shift operators.
|
||||
#[must_use]
|
||||
pub(super) fn next_generic(&mut self) -> TokenSpan<'a> {
|
||||
pub(in crate::front::wgsl) fn next_generic(&mut self) -> TokenSpan<'a> {
|
||||
self.next_impl(true)
|
||||
}
|
||||
|
||||
@@ -275,12 +298,15 @@ impl<'a> Lexer<'a> {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(super) fn peek(&mut self) -> TokenSpan<'a> {
|
||||
pub(in crate::front::wgsl) fn peek(&mut self) -> TokenSpan<'a> {
|
||||
let (token, _) = self.peek_token_and_rest();
|
||||
token
|
||||
}
|
||||
|
||||
pub(super) fn expect_span(&mut self, expected: Token<'a>) -> Result<Span, Error<'a>> {
|
||||
pub(in crate::front::wgsl) fn expect_span(
|
||||
&mut self,
|
||||
expected: Token<'a>,
|
||||
) -> Result<Span, Error<'a>> {
|
||||
let next = self.next();
|
||||
if next.0 == expected {
|
||||
Ok(next.1)
|
||||
@@ -289,12 +315,15 @@ impl<'a> Lexer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> {
|
||||
pub(in crate::front::wgsl) fn expect(&mut self, expected: Token<'a>) -> Result<(), Error<'a>> {
|
||||
self.expect_span(expected)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn expect_generic_paren(&mut self, expected: char) -> Result<(), Error<'a>> {
|
||||
pub(in crate::front::wgsl) fn expect_generic_paren(
|
||||
&mut self,
|
||||
expected: char,
|
||||
) -> Result<(), Error<'a>> {
|
||||
let next = self.next_generic();
|
||||
if next.0 == Token::Paren(expected) {
|
||||
Ok(())
|
||||
@@ -307,7 +336,7 @@ impl<'a> Lexer<'a> {
|
||||
}
|
||||
|
||||
/// If the next token matches it is skipped and true is returned
|
||||
pub(super) fn skip(&mut self, what: Token<'_>) -> bool {
|
||||
pub(in crate::front::wgsl) fn skip(&mut self, what: Token<'_>) -> bool {
|
||||
let (peeked_token, rest) = self.peek_token_and_rest();
|
||||
if peeked_token.0 == what {
|
||||
self.input = rest;
|
||||
@@ -317,7 +346,9 @@ impl<'a> Lexer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn next_ident_with_span(&mut self) -> Result<(&'a str, Span), Error<'a>> {
|
||||
pub(in crate::front::wgsl) fn next_ident_with_span(
|
||||
&mut self,
|
||||
) -> Result<(&'a str, Span), Error<'a>> {
|
||||
match self.next() {
|
||||
(Token::Word(word), span) if word == "_" => {
|
||||
Err(Error::InvalidIdentifierUnderscore(span))
|
||||
@@ -330,7 +361,9 @@ impl<'a> Lexer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn next_ident(&mut self) -> Result<super::ast::Ident<'a>, Error<'a>> {
|
||||
pub(in crate::front::wgsl) fn next_ident(
|
||||
&mut self,
|
||||
) -> Result<super::ast::Ident<'a>, Error<'a>> {
|
||||
let ident = self
|
||||
.next_ident_with_span()
|
||||
.map(|(name, span)| super::ast::Ident { name, span })?;
|
||||
@@ -343,7 +376,7 @@ impl<'a> Lexer<'a> {
|
||||
}
|
||||
|
||||
/// Parses a generic scalar type, for example `<f32>`.
|
||||
pub(super) fn next_scalar_generic(
|
||||
pub(in crate::front::wgsl) fn next_scalar_generic(
|
||||
&mut self,
|
||||
) -> Result<(crate::ScalarKind, crate::Bytes), Error<'a>> {
|
||||
self.expect_generic_paren('<')?;
|
||||
@@ -360,7 +393,7 @@ impl<'a> Lexer<'a> {
|
||||
/// Parses a generic scalar type, for example `<f32>`.
|
||||
///
|
||||
/// Returns the span covering the inner type, excluding the brackets.
|
||||
pub(super) fn next_scalar_generic_with_span(
|
||||
pub(in crate::front::wgsl) fn next_scalar_generic_with_span(
|
||||
&mut self,
|
||||
) -> Result<(crate::ScalarKind, crate::Bytes, Span), Error<'a>> {
|
||||
self.expect_generic_paren('<')?;
|
||||
@@ -374,7 +407,9 @@ impl<'a> Lexer<'a> {
|
||||
Ok(pair)
|
||||
}
|
||||
|
||||
pub(super) fn next_storage_access(&mut self) -> Result<crate::StorageAccess, Error<'a>> {
|
||||
pub(in crate::front::wgsl) fn next_storage_access(
|
||||
&mut self,
|
||||
) -> Result<crate::StorageAccess, Error<'a>> {
|
||||
let (ident, span) = self.next_ident_with_span()?;
|
||||
match ident {
|
||||
"read" => Ok(crate::StorageAccess::LOAD),
|
||||
@@ -384,7 +419,7 @@ impl<'a> Lexer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn next_format_generic(
|
||||
pub(in crate::front::wgsl) fn next_format_generic(
|
||||
&mut self,
|
||||
) -> Result<(crate::StorageFormat, crate::StorageAccess), Error<'a>> {
|
||||
self.expect(Token::Paren('<'))?;
|
||||
@@ -396,16 +431,16 @@ impl<'a> Lexer<'a> {
|
||||
Ok((format, access))
|
||||
}
|
||||
|
||||
pub(super) fn open_arguments(&mut self) -> Result<(), Error<'a>> {
|
||||
pub(in crate::front::wgsl) fn open_arguments(&mut self) -> Result<(), Error<'a>> {
|
||||
self.expect(Token::Paren('('))
|
||||
}
|
||||
|
||||
pub(super) fn close_arguments(&mut self) -> Result<(), Error<'a>> {
|
||||
pub(in crate::front::wgsl) fn close_arguments(&mut self) -> Result<(), Error<'a>> {
|
||||
let _ = self.skip(Token::Separator(','));
|
||||
self.expect(Token::Paren(')'))
|
||||
}
|
||||
|
||||
pub(super) fn next_argument(&mut self) -> Result<bool, Error<'a>> {
|
||||
pub(in crate::front::wgsl) fn next_argument(&mut self) -> Result<bool, Error<'a>> {
|
||||
let paren = Token::Paren(')');
|
||||
if self.skip(Token::Separator(',')) {
|
||||
Ok(!self.skip(paren))
|
||||
@@ -415,9 +450,6 @@ impl<'a> Lexer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
use super::{number::Number, NumberError};
|
||||
|
||||
#[cfg(test)]
|
||||
fn sub_test(source: &str, expected_tokens: &[Token]) {
|
||||
let mut lex = Lexer::new(source);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::{NumberError, Token};
|
||||
use crate::front::wgsl::error::NumberError;
|
||||
use crate::front::wgsl::parse::lexer::Token;
|
||||
|
||||
/// When using this type assume no Abstract Int/Float for now
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
@@ -42,7 +43,7 @@ impl Number {
|
||||
|
||||
// TODO: when implementing Creation-Time Expressions, remove the ability to match the minus sign
|
||||
|
||||
pub(super) fn consume_number(input: &str) -> (Token<'_>, &str) {
|
||||
pub(in crate::front::wgsl) fn consume_number(input: &str) -> (Token<'_>, &str) {
|
||||
let (result, rest) = parse(input);
|
||||
(
|
||||
Token::Number(result.and_then(Number::abstract_to_concrete)),
|
||||
@@ -146,7 +147,7 @@ fn parse(input: &str) -> (Result<Number, NumberError>, &str) {
|
||||
|
||||
impl<'a> ExtractSubStr<'a> {
|
||||
/// given an `input` and a `start` (tail of the `input`)
|
||||
/// creates a new [ExtractSubStr]
|
||||
/// creates a new [`ExtractSubStr`](`Self`)
|
||||
fn start(input: &'a str, start: &'a [u8]) -> Self {
|
||||
let start = input.len() - start.len();
|
||||
Self(&input[start..])
|
||||
+2
-2
@@ -623,7 +623,7 @@ fn convert_glsl_variations_check() {
|
||||
let root = env!("CARGO_MANIFEST_DIR");
|
||||
let file = fs::read_to_string(format!("{root}/{BASE_DIR_IN}/variations.glsl"))
|
||||
.expect("Couldn't find glsl file");
|
||||
let mut parser = naga::front::glsl::Parser::default();
|
||||
let mut parser = naga::front::glsl::Frontend::default();
|
||||
let module = parser
|
||||
.parse(
|
||||
&naga::front::glsl::Options {
|
||||
@@ -654,7 +654,7 @@ fn convert_glsl_folder() {
|
||||
}
|
||||
println!("Processing {file_name}");
|
||||
|
||||
let mut parser = naga::front::glsl::Parser::default();
|
||||
let mut parser = naga::front::glsl::Frontend::default();
|
||||
let module = parser
|
||||
.parse(
|
||||
&naga::front::glsl::Options {
|
||||
|
||||
Reference in new issue
Block a user