]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/output.cpp
Move parenthesizing expressions to Formatter
[libs/gl.git] / source / glsl / output.cpp
1 #include <msp/core/raii.h>
2 #include <msp/strings/format.h>
3 #include "output.h"
4
5 using namespace std;
6
7 namespace Msp {
8 namespace GL {
9 namespace SL {
10
11 Formatter::Formatter():
12         stage(0),
13         source_index(0),
14         source_line(1),
15         indent(0),
16         parameter_list(false),
17         omit_builtin(false)
18 { }
19
20 const string &Formatter::apply(Stage &s)
21 {
22         stage = &s;
23         omit_builtin = true;
24
25         const Version &ver = s.required_features.glsl_version;
26
27         if(ver)
28         {
29                 append(format("#version %d%02d", ver.major, ver.minor));
30                 if(s.required_features.gl_api==OPENGL_ES2 && ver>=Version(3, 0))
31                         append(" es");
32                 formatted += '\n';
33         }
34
35         if(s.required_features.arb_explicit_attrib_location)
36                 append("#extension arb_explicit_attrib_location: require\n");
37         if(s.required_features.arb_gpu_shader5)
38                 append("#extension arb_gpu_shader5: require\n");
39         if(s.required_features.arb_uniform_buffer_object)
40                 append("#extension arb_uniform_buffer_object: require\n");
41         if(s.required_features.ext_gpu_shader4)
42                 append("#extension ext_gpu_shader4: require\n");
43         if(s.required_features.ext_texture_array)
44                 append("#extension ext_texture_array: require\n");
45         formatted += '\n';
46
47         s.content.visit(*this);
48
49         return formatted;
50 }
51
52 void Formatter::append(const string &text)
53 {
54         formatted += text;
55         for(string::const_iterator i=text.begin(); i!=text.end(); ++i)
56                 if(*i=='\n')
57                         ++source_line;
58 }
59
60 void Formatter::append(char c)
61 {
62         formatted += c;
63         if(c=='\n')
64                 ++source_line;
65 }
66
67 void Formatter::set_source(unsigned index, unsigned line)
68 {
69         if(index!=source_index || (index && line!=source_line))
70         {
71                 if(index==source_index && line==source_line+1)
72                         formatted += '\n';
73                 else
74                 {
75                         unsigned l = line;
76                         if(stage && stage->required_features.glsl_version && stage->required_features.glsl_version<Version(3, 30))
77                                 --l;
78                         formatted += format("#line %d %d\n", l, index);
79                 }
80         }
81         source_index = index;
82         source_line = line;
83 }
84
85 void Formatter::visit(Block &block)
86 {
87         unsigned brace_indent = indent;
88         bool use_braces = (block.use_braces || (indent && block.body.size()!=1));
89         if(use_braces)
90                 append(format("%s{\n", string(brace_indent*2, ' ')));
91
92         SetForScope<unsigned> set(indent, indent+(indent>0 || use_braces));
93         string spaces(indent*2, ' ');
94         bool first = true;
95         for(NodeList<Statement>::iterator i=block.body.begin(); i!=block.body.end(); ++i)
96         {
97                 if(omit_builtin && (*i)->source<=BUILTIN_SOURCE)
98                         continue;
99                 if(!first)
100                         append('\n');
101                 first = false;
102                 set_source((*i)->source, (*i)->line);
103                 append(spaces);
104                 (*i)->visit(*this);
105         }
106
107         if(use_braces)
108                 append(format("\n%s}", string(brace_indent*2, ' ')));
109 }
110
111 void Formatter::visit_expression(Expression &expr, const Operator *outer_oper, bool on_rhs)
112 {
113         unsigned outer_precedence = (outer_oper ? outer_oper->precedence : 20);
114         unsigned inner_precedence = (expr.oper ? expr.oper->precedence : 0);
115
116         bool needs_parentheses = (inner_precedence>=outer_precedence);
117
118         // Omit parentheses if the outer operator encloses this operand.
119         if(outer_oper && outer_oper->type==Operator::BINARY && outer_oper->token2[0] && on_rhs)
120                 needs_parentheses = false;
121
122         if(expr.oper)
123         {
124                 /* Omit parentheses if the inner expression's operator sits between the
125                 expression and the outer operator. */
126                 bool oper_on_left = expr.oper->type==Operator::PREFIX;
127                 bool oper_on_right = expr.oper->type==Operator::POSTFIX || (expr.oper->type==Operator::BINARY && expr.oper->token2[0]);
128                 if(expr.oper && ((oper_on_left && on_rhs) || (oper_on_right && !on_rhs)))
129                         needs_parentheses = false;
130
131                 // Omit parentheses if the operator's natural grouping works out.
132                 if(expr.oper==outer_oper)
133                         needs_parentheses = (expr.oper->assoc!=Operator::ASSOCIATIVE && on_rhs!=(expr.oper->assoc==Operator::RIGHT_TO_LEFT));
134         }
135
136         if(needs_parentheses)
137                 append('(');
138         expr.visit(*this);
139         if(needs_parentheses)
140                 append(')');
141 }
142
143 void Formatter::visit(Literal &literal)
144 {
145         append(literal.token);
146 }
147
148 void Formatter::visit(ParenthesizedExpression &parexpr)
149 {
150         append('(');
151         parexpr.expression->visit(*this);
152         append(')');
153 }
154
155 void Formatter::visit(VariableReference &var)
156 {
157         append(var.name);
158 }
159
160 void Formatter::visit(InterfaceBlockReference &iface)
161 {
162         append(iface.name);
163 }
164
165 void Formatter::visit(MemberAccess &memacc)
166 {
167         visit_expression(*memacc.left, memacc.oper, false);
168         append(format(".%s", memacc.member));
169 }
170
171 void Formatter::visit(Swizzle &swizzle)
172 {
173         visit_expression(*swizzle.left, swizzle.oper, false);
174         append(format(".%s", swizzle.component_group));
175 }
176
177 void Formatter::visit(UnaryExpression &unary)
178 {
179         if(unary.oper->type==Operator::PREFIX)
180                 append(unary.oper->token);
181         visit_expression(*unary.expression, unary.oper, unary.oper->type==Operator::PREFIX);
182         if(unary.oper->type==Operator::POSTFIX)
183                 append(unary.oper->token);
184 }
185
186 void Formatter::visit(BinaryExpression &binary)
187 {
188         visit_expression(*binary.left, binary.oper, false);
189         append(binary.oper->token);
190         visit_expression(*binary.right, binary.oper, true);
191         if(binary.oper->token2[0])
192                 append(binary.oper->token2);
193 }
194
195 void Formatter::visit(Assignment &assign)
196 {
197         visit_expression(*assign.left, assign.oper, false);
198         append(format(" %s ", assign.oper->token));
199         visit_expression(*assign.right, assign.oper, true);
200 }
201
202 void Formatter::visit(TernaryExpression &ternary)
203 {
204         visit_expression(*ternary.condition, ternary.oper, false);
205         append(ternary.oper->token);
206         visit_expression(*ternary.true_expr, ternary.oper, false);
207         if(ternary.oper->token2)
208                 append(ternary.oper->token2);
209         visit_expression(*ternary.false_expr, ternary.oper, true);
210 }
211
212 void Formatter::visit(FunctionCall &call)
213 {
214         append(format("%s(", call.name));
215         for(NodeArray<Expression>::iterator i=call.arguments.begin(); i!=call.arguments.end(); ++i)
216         {
217                 if(i!=call.arguments.begin())
218                         append(", ");
219                 (*i)->visit(*this);
220         }
221         append(')');
222 }
223
224 void Formatter::visit(ExpressionStatement &expr)
225 {
226         expr.expression->visit(*this);
227         append(';');
228 }
229
230 void Formatter::visit(Import &import)
231 {
232         append(format("import %s;", import.module));
233 }
234
235 void Formatter::visit(Precision &prec)
236 {
237         append(format("precision %s %s;", prec.precision, prec.type));
238 }
239
240 void Formatter::visit(Layout &layout)
241 {
242         append("layout(");
243         for(vector<Layout::Qualifier>::const_iterator i=layout.qualifiers.begin(); i!=layout.qualifiers.end(); ++i)
244         {
245                 if(i!=layout.qualifiers.begin())
246                         append(", ");
247                 append(i->name);
248                 if(i->has_value)
249                         append(format("=%d", i->value));
250         }
251         append(')');
252 }
253
254 void Formatter::visit(InterfaceLayout &layout)
255 {
256         layout.layout.visit(*this);
257         append(format(" %s;", layout.interface));
258 }
259
260 void Formatter::visit(StructDeclaration &strct)
261 {
262         append(format("struct %s\n", strct.name));
263         strct.members.visit(*this);
264         append(';');
265 }
266
267 void Formatter::visit(VariableDeclaration &var)
268 {
269         if(var.layout)
270         {
271                 var.layout->visit(*this);
272                 append(' ');
273         }
274         if(var.constant)
275                 append("const ");
276         if(!var.interpolation.empty())
277                 append(format("%s ", var.interpolation));
278         if(!var.sampling.empty())
279                 append(format("%s ", var.sampling));
280         if(!var.interface.empty())
281         {
282                 string interface = var.interface;
283                 if(stage && stage->required_features.glsl_version && stage->required_features.glsl_version<Version(1, 30))
284                 {
285                         if(stage->type==Stage::VERTEX && var.interface=="in")
286                                 interface = "attribute";
287                         else if((stage->type==Stage::VERTEX && var.interface=="out") || (stage->type==Stage::FRAGMENT && var.interface=="in"))
288                                 interface = "varying";
289                 }
290                 append(format("%s ", interface));
291         }
292         if(!var.precision.empty())
293                 append(format("%s ", var.precision));
294         string type_name = var.type_declaration->name;
295         if(var.array)
296                 type_name = type_name.substr(0, type_name.find('['));
297         append(format("%s %s", type_name, var.name));
298         if(var.array)
299         {
300                 append('[');
301                 if(var.array_size)
302                         var.array_size->visit(*this);
303                 append(']');
304         }
305         if(var.init_expression)
306         {
307                 append(" = ");
308                 var.init_expression->visit(*this);
309         }
310         if(!parameter_list)
311                 append(';');
312 }
313
314 void Formatter::visit(InterfaceBlock &iface)
315 {
316         append(format("%s %s\n", iface.interface, iface.name));
317         if(iface.struct_declaration)
318                 iface.struct_declaration->members.visit(*this);
319         if(!iface.instance_name.empty())
320         {
321                 append(' ');
322                 append(iface.instance_name);
323                 if(iface.array)
324                         append("[]");
325         }
326         append(';');
327 }
328
329 void Formatter::visit(FunctionDeclaration &func)
330 {
331         append(format("%s %s(", func.return_type_declaration->name, func.name));
332         for(NodeArray<VariableDeclaration>::iterator i=func.parameters.begin(); i!=func.parameters.end(); ++i)
333         {
334                 if(i!=func.parameters.begin())
335                         append(", ");
336                 SetFlag set(parameter_list);
337                 (*i)->visit(*this);
338         }
339         append(')');
340         if(func.definition==&func)
341         {
342                 append('\n');
343                 func.body.visit(*this);
344         }
345         else
346                 append(';');
347 }
348
349 void Formatter::visit(Conditional &cond)
350 {
351         append("if(");
352         cond.condition->visit(*this);
353         append(")\n");
354
355         cond.body.visit(*this);
356         if(!cond.else_body.body.empty())
357         {
358                 Conditional *else_cond = dynamic_cast<Conditional *>(cond.else_body.body.front().get());
359                 if(cond.else_body.body.size()==1 && else_cond)
360                 {
361                         append('\n');
362                         set_source(else_cond->source, else_cond->line);
363                         append(format("%selse ", string(indent*2, ' ')));
364                         else_cond->visit(*this);
365                 }
366                 else
367                 {
368                         append(format("\n%selse\n", string(indent*2, ' ')));
369                         cond.else_body.visit(*this);
370                 }
371         }
372 }
373
374 void Formatter::visit(Iteration &iter)
375 {
376         if(!iter.init_statement && iter.condition && !iter.loop_expression)
377         {
378                 append("while(");
379                 iter.condition->visit(*this);
380                 append(')');
381         }
382         else
383         {
384                 append("for(");
385                 if(iter.init_statement)
386                         iter.init_statement->visit(*this);
387                 else
388                         append(';');
389                 if(iter.condition)
390                 {
391                         append(' ');
392                         iter.condition->visit(*this);
393                 }
394                 append(';');
395                 if(iter.loop_expression)
396                 {
397                         append(' ');
398                         iter.loop_expression->visit(*this);
399                 }
400                 append(')');
401         }
402
403         if(iter.body.body.empty())
404                 append(" { }");
405         else
406         {
407                 append('\n');
408                 iter.body.visit(*this);
409         }
410 }
411
412 void Formatter::visit(Passthrough &pass)
413 {
414         append("passthrough");
415         if(pass.subscript)
416         {
417                 append('[');
418                 pass.subscript->visit(*this);
419                 append(']');
420         }
421         append(';');
422 }
423
424 void Formatter::visit(Return &ret)
425 {
426         append("return");
427         if(ret.expression)
428         {
429                 append(' ');
430                 ret.expression->visit(*this);
431         }
432         append(';');
433 }
434
435 void Formatter::visit(Jump &jump)
436 {
437         append(jump.keyword);
438         append(';');
439 }
440
441 } // namespace SL
442 } // namespace GL
443 } // namespace Msp