From 6ae5f16e3b54978b1bce11b2f184b8b47930b6e8 Mon Sep 17 00:00:00 2001 From: Larry Gritz Date: Tue, 10 May 2022 23:41:14 -0700 Subject: [PATCH 1/2] More conversion of old printf style to std::format style Another semi-random collection of conversions. Bit by bit. These are all internals, none of it involves public interfaces. Signed-off-by: Larry Gritz --- src/liboslcomp/ast.cpp | 4 +- src/liboslcomp/codegen.cpp | 81 ++++++++--------- src/liboslcomp/oslcomp_pvt.h | 7 -- src/liboslcomp/symtab.cpp | 5 +- src/liboslexec/automata.cpp | 12 +-- src/liboslexec/backendllvm.cpp | 4 +- src/liboslexec/backendllvm.h | 3 +- src/liboslexec/batched_backendllvm.cpp | 6 +- src/liboslexec/batched_backendllvm.h | 5 +- src/liboslexec/batched_llvm_gen.cpp | 90 +++++++++--------- src/liboslexec/batched_llvm_instance.cpp | 91 +++++++++---------- src/liboslexec/batched_rendservices.cpp | 4 +- src/liboslexec/constfold.cpp | 3 +- src/liboslexec/context.cpp | 2 +- src/liboslexec/instance.cpp | 17 ++-- src/liboslexec/llvm_gen.cpp | 70 +++++++------- src/liboslexec/llvm_instance.cpp | 62 ++++++++----- src/liboslexec/llvmutil_test.cpp | 2 +- src/liboslexec/loadshader.cpp | 2 +- src/liboslexec/opcolor.cpp | 4 +- src/liboslexec/opmatrix.cpp | 6 +- src/liboslexec/opmessage.cpp | 39 ++++---- src/liboslexec/oslexec_pvt.h | 87 +++++------------- src/liboslexec/rendservices.cpp | 8 +- src/liboslexec/runtimeoptimize.cpp | 44 ++++----- src/liboslexec/shadingsys.cpp | 50 +++++----- src/liboslexec/wide/wide_opmatrix.cpp | 12 +-- src/liboslexec/wide/wide_opmessage.cpp | 41 ++++----- .../wide/wide_opnoise_generic_impl.cpp | 8 +- .../wide_opnoise_periodic_generic_impl.cpp | 8 +- src/liboslexec/wide/wide_oppointcloud.cpp | 33 +++++-- src/liboslexec/wide/wide_optexture.cpp | 12 +-- src/liboslexec/wide/wide_shadingsys.cpp | 58 ++++++------ src/liboslnoise/oslnoise_test.cpp | 4 +- src/osltoy/osltoyapp.cpp | 25 +++-- src/osltoy/qtutils.h | 8 +- src/testrender/optixraytracer.cpp | 14 +-- src/testshade/testshade.cpp | 2 +- 38 files changed, 449 insertions(+), 484 deletions(-) diff --git a/src/liboslcomp/ast.cpp b/src/liboslcomp/ast.cpp index 8a3514d9d..c0316ac8c 100644 --- a/src/liboslcomp/ast.cpp +++ b/src/liboslcomp/ast.cpp @@ -1116,7 +1116,7 @@ ASTunary_expression::ASTunary_expression (OSLCompilerImpl *comp, int op, : ASTNode (unary_expression_node, comp, op, expr) { // Check for a user-overloaded function for this operator - Symbol *sym = comp->symtab().find (ustring::sprintf ("__operator__%s__", opword())); + Symbol *sym = comp->symtab().find(ustring::fmtformat("__operator__{}__", opword())); if (sym && sym->symtype() == SymTypeFunction) m_function_overload = (FunctionSymbol *)sym; } @@ -1171,7 +1171,7 @@ ASTbinary_expression::ASTbinary_expression (OSLCompilerImpl *comp, Operator op, // Check for a user-overloaded function for this operator. // Disallow a few ops from overloading. if (op != And && op != Or) { - ustring funcname = ustring::sprintf ("__operator__%s__", opword()); + ustring funcname = ustring::fmtformat("__operator__{}__", opword()); Symbol *sym = comp->symtab().find (funcname); if (sym && sym->symtype() == SymTypeFunction) m_function_overload = (FunctionSymbol *)sym; diff --git a/src/liboslcomp/codegen.cpp b/src/liboslcomp/codegen.cpp index 9c59e4a03..5557b61e3 100644 --- a/src/liboslcomp/codegen.cpp +++ b/src/liboslcomp/codegen.cpp @@ -101,7 +101,7 @@ OSLCompilerImpl::insert_code(int opnum, const char* opname, size_t nargs, Symbol* OSLCompilerImpl::make_temporary(const TypeSpec& type) { - ustring name = ustring::sprintf("$tmp%d", ++m_next_temp); + ustring name = ustring::fmtformat("$tmp{}", ++m_next_temp); Symbol* s = new Symbol(name, type, SymTypeTemp); symtab().insert(s); @@ -131,7 +131,7 @@ OSLCompilerImpl::add_struct_fields(StructSpec* structspec, ustring basename, // arraylen is the length of the array of the surrounding data type for (int i = 0; i < (int)structspec->numfields(); ++i) { const StructSpec::FieldSpec& field(structspec->field(i)); - ustring fieldname = ustring::sprintf("%s.%s", basename, field.name); + ustring fieldname = ustring::fmtformat("{}.{}", basename, field.name); TypeSpec type = field.type; int arr = type.arraylength(); if (arr && arraylen) { @@ -175,7 +175,7 @@ OSLCompilerImpl::make_constant(ustring val) return sym; } // It's not a constant we've added before - ustring name = ustring::sprintf("$const%d", ++m_next_const); + ustring name = ustring::fmtformat("$const{}", ++m_next_const); ConstantSymbol* s = new ConstantSymbol(name, val); symtab().insert(s); m_const_syms.push_back(s); @@ -194,7 +194,7 @@ OSLCompilerImpl::make_constant(TypeDesc type, const void* val) return sym; } // It's not a constant we've added before - ustring name = ustring::sprintf("$const%d", ++m_next_const); + ustring name = ustring::fmtformat("$const{}", ++m_next_const); ConstantSymbol* s = new ConstantSymbol(name, type); memcpy(s->dataptr(), val, typesize); symtab().insert(s); @@ -212,7 +212,7 @@ OSLCompilerImpl::make_constant(int val) return sym; } // It's not a constant we've added before - ustring name = ustring::sprintf("$const%d", ++m_next_const); + ustring name = ustring::fmtformat("$const{}", ++m_next_const); ConstantSymbol* s = new ConstantSymbol(name, val); symtab().insert(s); m_const_syms.push_back(s); @@ -229,7 +229,7 @@ OSLCompilerImpl::make_constant(float val) return sym; } // It's not a constant we've added before - ustring name = ustring::sprintf("$const%d", ++m_next_const); + ustring name = ustring::fmtformat("$const{}", ++m_next_const); ConstantSymbol* s = new ConstantSymbol(name, val); symtab().insert(s); m_const_syms.push_back(s); @@ -247,7 +247,7 @@ OSLCompilerImpl::make_constant(TypeDesc type, float x, float y, float z) return sym; } // It's not a constant we've added before - ustring name = ustring::sprintf("$const%d", ++m_next_const); + ustring name = ustring::fmtformat("$const{}", ++m_next_const); ConstantSymbol* s = new ConstantSymbol(name, type, x, y, z); symtab().insert(s); m_const_syms.push_back(s); @@ -550,8 +550,8 @@ ASTNode::codegen_assign_struct(StructSpec* structspec, ustring dstsym, // struct within struct -- recurse ustring fieldname(structspec->field(i).name); codegen_assign_struct(fieldtype.structspec(), - ustring::sprintf("%s.%s", dstsym, fieldname), - ustring::sprintf("%s.%s", srcsym, fieldname), + ustring::fmtformat("{}.{}", dstsym, fieldname), + ustring::fmtformat("{}.{}", srcsym, fieldname), arrayindex, copywholearrays, 0, paraminit); continue; } @@ -560,8 +560,8 @@ ASTNode::codegen_assign_struct(StructSpec* structspec, ustring dstsym, // struct array within struct -- loop over indices and recurse OSL_ASSERT(!arrayindex && "two levels of arrays not allowed"); ustring fieldname(structspec->field(i).name); - ustring dstfield = ustring::sprintf("%s.%s", dstsym, fieldname); - ustring srcfield = ustring::sprintf("%s.%s", srcsym, fieldname); + ustring dstfield = ustring::fmtformat("{}.{}", dstsym, fieldname); + ustring srcfield = ustring::fmtformat("{}.{}", srcsym, fieldname); for (int i = 0; i < fieldtype.arraylength(); ++i) { codegen_assign_struct(fieldtype.structspec(), dstfield, srcfield, m_compiler->make_constant(i), @@ -632,16 +632,16 @@ ASTNode::one_default_literal(const Symbol* sym, ASTNode* init, std::string& out, completed = false; } else if (type.is_int()) { if (islit && lit->typespec().is_int()) - out += Strutil::sprintf("%d", lit->intval()); + out += fmtformat("{}", lit->intval()); else { out += "0"; // FIXME? completed = false; } } else if (type.is_float()) { if (islit && lit->typespec().is_int()) - out += Strutil::sprintf("%d", lit->intval()); + out += fmtformat("{}", lit->intval()); else if (islit && lit->typespec().is_float()) - out += Strutil::sprintf("%.9g", lit->floatval()); + out += fmtformat("{:.9g}", lit->floatval()); else { out += "0"; // FIXME? completed = false; @@ -649,10 +649,10 @@ ASTNode::one_default_literal(const Symbol* sym, ASTNode* init, std::string& out, } else if (type.is_triple()) { if (islit && lit->typespec().is_int()) { float f = lit->intval(); - out += Strutil::sprintf("%.9g%s%.9g%s%.9g", f, sep, f, sep, f); + out += fmtformat("{:.9g}{}{:.9g}{}{:.9g}", f, sep, f, sep, f); } else if (islit && lit->typespec().is_float()) { float f = lit->floatval(); - out += Strutil::sprintf("%.9g%s%.9g%s%.9g", f, sep, f, sep, f); + out += fmtformat("{:.9g}{}{:.9g}{}{:.9g}", f, sep, f, sep, f); } else if (init && init->typespec() == type && (init->nodetype() == ASTNode::type_constructor_node || (init->nodetype() == ASTNode::compound_initializer_node @@ -682,26 +682,26 @@ ASTNode::one_default_literal(const Symbol* sym, ASTNode* init, std::string& out, } } if (nargs == 1) - out += Strutil::sprintf("%.9g%s%.9g%s%.9g", f[0], sep, f[0], - sep, f[0]); + out += fmtformat("{:.9g}{}{:.9g}{}{:.9g}", f[0], sep, f[0], sep, + f[0]); else - out += Strutil::sprintf("%.9g%s%.9g%s%.9g", f[0], sep, f[1], - sep, f[2]); + out += fmtformat("{:.9g}{}{:.9g}{}{:.9g}", f[0], sep, f[1], sep, + f[2]); } else { - out += Strutil::sprintf("0%s0%s0", sep, sep); + out += fmtformat("0{}0{}0", sep, sep); completed = false; } } else if (type.is_matrix()) { if (islit && lit->typespec().is_int()) { float f = lit->intval(); for (int c = 0; c < 16; ++c) - out += Strutil::sprintf("%.9g%s", (c / 4) == (c % 4) ? f : 0.0f, - c < 15 ? sep : ""); + out += fmtformat("{:.9g}{}", (c / 4) == (c % 4) ? f : 0.0f, + c < 15 ? sep : ""); } else if (islit && lit->typespec().is_float()) { float f = lit->floatval(); for (int c = 0; c < 16; ++c) - out += Strutil::sprintf("%.9g%s", (c / 4) == (c % 4) ? f : 0.0f, - c < 15 ? sep : ""); + out += fmtformat("{:.9g}{}", (c / 4) == (c % 4) ? f : 0.0f, + c < 15 ? sep : ""); } else if (init && init->typespec() == type && init->nodetype() == ASTNode::type_constructor_node) { ASTtype_constructor* ctr = (ASTtype_constructor*)init; @@ -729,22 +729,21 @@ ASTNode::one_default_literal(const Symbol* sym, ASTNode* init, std::string& out, } if (nargs == 1) { for (int c = 0; c < 16; ++c) - out += Strutil::sprintf("%.9g%s", - (c / 4) == (c % 4) ? f[0] : 0.0f, - c < 15 ? sep : ""); + out += fmtformat("{:.9g}{}", + (c / 4) == (c % 4) ? f[0] : 0.0f, + c < 15 ? sep : ""); } else { for (int c = 0; c < 16; ++c) - out += Strutil::sprintf("%.9g%s", f[c], c < 15 ? sep : ""); + out += fmtformat("{:.9g}{}", f[c], c < 15 ? sep : ""); } } else { for (int c = 0; c < 16; ++c) - out += Strutil::sprintf("0%s", c < 15 ? sep : ""); + out += fmtformat("0{}", c < 15 ? sep : ""); completed = false; } } else if (type.is_string()) { if (islit && lit->typespec().is_string()) - out += Strutil::sprintf("\"%s\"", - Strutil::escape_chars(lit->strval())); + out += fmtformat("\"{}\"", Strutil::escape_chars(lit->strval())); else { out += "\"\""; // FIXME? completed = false; @@ -903,8 +902,8 @@ ASTNode::codegen_initlist(ref init, TypeSpec type, Symbol* sym) for (int i = 0; init && i < structspec->numfields(); init = init->next(), ++i) { const StructSpec::FieldSpec& field(structspec->field(i)); - ustring fieldname = ustring::sprintf("%s.%s", sym->mangled(), - field.name); + ustring fieldname = ustring::fmtformat("{}.{}", sym->mangled(), + field.name); Symbol* fieldsym = m_compiler->symtab().find_exact(fieldname); if (paraminit) { OSL_DASSERT(nodetype() == variable_declaration_node); @@ -1073,8 +1072,8 @@ ASTNode::codegen_struct_initializers(ref init, Symbol* sym, bool is_constructor, init = init->next(), ++i) { // Structure element -- assign to the i-th member field const StructSpec::FieldSpec& field(structspec->field(i)); - ustring fieldname = ustring::sprintf("%s.%s", sym->mangled(), - field.name); + ustring fieldname = ustring::fmtformat("{}.{}", sym->mangled(), + field.name); Symbol* fieldsym = m_compiler->symtab().find_exact(fieldname); if (fieldsym->typespec().is_structure_based() && (init->nodetype() == type_constructor_node @@ -1240,8 +1239,8 @@ ASTindex::codegen_copy_struct_array_element(StructSpec* structspec, // struct within struct -- recurse! codegen_copy_struct_array_element( type.structspec(), - ustring::sprintf("%s.%s", destname, field.name), - ustring::sprintf("%s.%s", srcname, field.name), index); + ustring::fmtformat("{}.{}", destname, field.name), + ustring::fmtformat("{}.{}", srcname, field.name), index); } else { OSL_ASSERT(!type.is_array()); Symbol *dfield, *sfield; @@ -1464,7 +1463,7 @@ ASTunary_expression::codegen(Symbol* dest) if (m_function_overload) { // A little crazy, but we temporarily construct an ASTfunction_call // in order to codegen this overloaded operator. - ustring funcname = ustring::sprintf("__operator__%s__", opword()); + ustring funcname = ustring::fmtformat("__operator__{}__", opword()); ASTfunction_call fc(m_compiler, funcname, expr().get(), m_function_overload); fc.typecheck(typespec()); @@ -2023,8 +2022,8 @@ ASTfunction_call::struct_pair_all_fields(StructSpec* structspec, ustring formal, // struct within struct -- recurse! struct_pair_all_fields( type.structspec(), - ustring::sprintf("%s.%s", formal, field.name), - ustring::sprintf("%s.%s", actual, field.name), arrayindex); + ustring::fmtformat("{}.{}", formal, field.name), + ustring::fmtformat("{}.{}", actual, field.name), arrayindex); } else { Symbol *fsym, *asym; m_compiler->struct_field_pair(structspec, fi, formal, actual, fsym, diff --git a/src/liboslcomp/oslcomp_pvt.h b/src/liboslcomp/oslcomp_pvt.h index 1dd57c746..e9921cbf8 100644 --- a/src/liboslcomp/oslcomp_pvt.h +++ b/src/liboslcomp/oslcomp_pvt.h @@ -390,13 +390,6 @@ class OSLCompilerImpl { void write_oso_metadata(const ASTNode* metanode) const; void write_dependency_file(string_view filename); - template - OSL_DEPRECATED("Use osofmt with std::format conventions") - inline void osof(const char* fmt, const Args&... args) const - { - (*m_osofile) << OIIO::Strutil::sprintf(fmt, args...); - } - // Output text to the osofile, using std::format formatting conventions. template inline void osofmt(const char* fmt, const Args&... args) const diff --git a/src/liboslcomp/symtab.cpp b/src/liboslcomp/symtab.cpp index fd96536ae..e93899932 100644 --- a/src/liboslcomp/symtab.cpp +++ b/src/liboslcomp/symtab.cpp @@ -19,7 +19,7 @@ namespace pvt { // OSL::pvt std::string Symbol::mangled() const { - std::string result = scope() ? Strutil::sprintf("___%d_%s", scope(), m_name) + std::string result = scope() ? fmtformat("___{}_{}", scope(), m_name) : m_name.string(); return result; // Force NRVO (named value return optimization) } @@ -54,8 +54,7 @@ Symbol::symtype_shortname(SymType s) std::string StructSpec::mangled() const { - return scope() ? Strutil::sprintf("___%d_%s", scope(), m_name) - : m_name.string(); + return scope() ? fmtformat("___{}_{}", scope(), m_name) : m_name.string(); } diff --git a/src/liboslexec/automata.cpp b/src/liboslexec/automata.cpp index 250da580b..32ecfe908 100644 --- a/src/liboslexec/automata.cpp +++ b/src/liboslexec/automata.cpp @@ -86,7 +86,7 @@ NdfAutomata::State::tostr()const for (IntSet::const_iterator j = dest.begin(); j != dest.end(); ++j) { if (s[s.size()-1] != '{') s += ", "; - s += Strutil::sprintf("%d", *j); + s += Strutil::to_string(*j); } s += "}"; } @@ -108,12 +108,12 @@ NdfAutomata::State::tostr()const } s += "]:"; } - s += Strutil::sprintf("%d", m_wildcard_trans); + s += Strutil::to_string(m_wildcard_trans); } // and finally the rule if we have it if (m_rule) { s += " | "; - s += Strutil::sprintf("%p", m_rule); + s += Strutil::fmt::format("{:p}", m_rule); } return s; } @@ -336,7 +336,7 @@ DfAutomata::State::tostr()const else s += sym.c_str(); s += ":"; - s += Strutil::sprintf("%d", dest); + s += Strutil::to_string(dest); } // wildcard if (m_wildcard_trans >= 0) { @@ -354,7 +354,7 @@ DfAutomata::State::tostr()const } s += "}:"; } - s += Strutil::sprintf("%d", m_wildcard_trans); + s += Strutil::to_string(m_wildcard_trans); } // and the rules if (m_rules.size()) { @@ -362,7 +362,7 @@ DfAutomata::State::tostr()const for (RuleSet::const_iterator i = m_rules.begin(); i != m_rules.end(); ++i) { if (s[s.size()-1] != '[') s += ", "; - s += Strutil::sprintf("%p", *i); + s += Strutil::fmt::format("{:p}", *i); } s += "]"; } diff --git a/src/liboslexec/backendllvm.cpp b/src/liboslexec/backendllvm.cpp index e19fabff3..e42278349 100644 --- a/src/liboslexec/backendllvm.cpp +++ b/src/liboslexec/backendllvm.cpp @@ -266,8 +266,8 @@ BackendLLVM::getLLVMSymbolBase (const Symbol &sym) std::string mangled_name = dealiased->mangled(); AllocationMap::iterator map_iter = named_values().find (mangled_name); if (map_iter == named_values().end()) { - shadingcontext()->errorf("Couldn't find symbol '%s' (unmangled = '%s'). Did you forget to allocate it?", - mangled_name, dealiased->unmangled()); + shadingcontext()->errorfmt("Couldn't find symbol '{}' (unmangled = '{}'). Did you forget to allocate it?", + mangled_name, dealiased->unmangled()); return 0; } return (llvm::Value*) map_iter->second; diff --git a/src/liboslexec/backendllvm.h b/src/liboslexec/backendllvm.h index ed0c69276..0c7b9cdf7 100644 --- a/src/liboslexec/backendllvm.h +++ b/src/liboslexec/backendllvm.h @@ -418,7 +418,8 @@ class BackendLLVM final : public OSOProcessorBase { /// llvm::BasicBlock *llvm_exit_instance_block () { if (! m_exit_instance_block) { - std::string name = Strutil::sprintf ("%s_%d_exit_", inst()->layername(), inst()->id()); + std::string name = fmtformat("{}_{}_exit_", inst()->layername(), + inst()->id()); m_exit_instance_block = ll.new_basic_block (name); } return m_exit_instance_block; diff --git a/src/liboslexec/batched_backendllvm.cpp b/src/liboslexec/batched_backendllvm.cpp index 5a05f94bc..831281665 100644 --- a/src/liboslexec/batched_backendllvm.cpp +++ b/src/liboslexec/batched_backendllvm.cpp @@ -450,9 +450,9 @@ BatchedBackendLLVM::getLLVMSymbolBase(const Symbol& sym) std::string mangled_name = dealiased->mangled(); AllocationMap::iterator map_iter = named_values().find(mangled_name); if (map_iter == named_values().end()) { - shadingcontext()->errorf( - "Couldn't find symbol '%s' (unmangled = '%s'). Did you forget to allocate it?", - mangled_name.c_str(), dealiased->unmangled()); + shadingcontext()->errorfmt( + "Couldn't find symbol '{}' (unmangled = '{}'). Did you forget to allocate it?", + mangled_name, dealiased->unmangled()); return 0; } return (llvm::Value*)map_iter->second; diff --git a/src/liboslexec/batched_backendllvm.h b/src/liboslexec/batched_backendllvm.h index da49bce42..d6d1bb901 100644 --- a/src/liboslexec/batched_backendllvm.h +++ b/src/liboslexec/batched_backendllvm.h @@ -678,9 +678,8 @@ class BatchedBackendLLVM : public OSOProcessorBase { llvm::BasicBlock* llvm_exit_instance_block() { if (!m_exit_instance_block) { - std::string name = Strutil::sprintf("%s_%d_exit_", - inst()->layername(), - inst()->id()); + std::string name = fmtformat("{}_{}_exit_", inst()->layername(), + inst()->id()); m_exit_instance_block = ll.new_basic_block(name); } return m_exit_instance_block; diff --git a/src/liboslexec/batched_llvm_gen.cpp b/src/liboslexec/batched_llvm_gen.cpp index 11b869a47..ae73023a2 100644 --- a/src/liboslexec/batched_llvm_gen.cpp +++ b/src/liboslexec/batched_llvm_gen.cpp @@ -77,8 +77,8 @@ typedef typename BatchedBackendLLVM::FuncSpec FuncSpec; void BatchedBackendLLVM::llvm_gen_debug_printf(string_view message) { - ustring s = ustring::sprintf("(%s %s) %s", inst()->shadername(), - inst()->layername(), message); + ustring s = ustring::fmtformat("({} {}) {}", inst()->shadername(), + inst()->layername(), message); ll.call_function(build_name("printf"), sg_void_ptr(), ll.constant("%s\n"), ll.constant(s)); } @@ -268,8 +268,8 @@ LLVMGEN (llvm_gen_printf) std::vector delay_extraction_args; std::vector call_args; if (!format_sym.is_constant()) { - rop.shadingcontext()->warningf ("%s must currently have constant format\n", - op.opname().c_str()); + rop.shadingcontext()->warningfmt( + "{} must currently have constant format\n", op.opname()); return false; } @@ -344,8 +344,9 @@ LLVMGEN (llvm_gen_printf) ++format; char formatchar = *format++; // Also eat the format char if (arg >= op.nargs()) { - rop.shadingcontext()->errorf ("Mismatch between format string and arguments (%s:%d)", - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "Mismatch between format string and arguments ({}:{})", + op.sourcefile(), op.sourceline()); return false; } @@ -2079,7 +2080,9 @@ LLVMGEN (llvm_gen_unary_op) } } else { // Don't know how to handle this. - rop.shadingcontext()->errorf ("Don't know how to handle op '%s', eliding the store\n", opname.c_str()); + rop.shadingcontext()->errorfmt( + "Don't know how to handle op '{}', eliding the store\n", + opname); } // Store the result @@ -2097,7 +2100,7 @@ LLVMGEN (llvm_gen_unary_op) if (dst_derivs) { // mul results in - rop.shadingcontext()->infof ("punting on derivatives for now\n"); + rop.shadingcontext()->infofmt("punting on derivatives for now\n"); // FIXME!! } } @@ -4210,10 +4213,9 @@ llvm_batched_texture_options(BatchedBackendLLVM &rop, int opnum, continue; } - rop.shadingcontext()->errorf ("Unknown texture%s optional argument: \"%s\", <%s> (%s:%d)", - tex3d ? "3d" : "", - name.c_str(), valtype.c_str(), - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "Unknown texture{} optional argument: \"{}\", <{}> ({}:{})", + tex3d ? "3d" : "", name, valtype, op.sourcefile(), op.sourceline()); #undef PARAM_WIDE_FLOAT #undef PARAM_WIDE_FLOAT_S_T_R @@ -4430,10 +4432,9 @@ llvm_batched_texture_varying_options(BatchedBackendLLVM &rop, int opnum, SKIP_PARAM_WIDE_FLOAT(time) - rop.shadingcontext()->errorf ("Unknown texture%s optional argument: \"%s\", <%s> (%s:%d)", - tex3d ? "3d" : "", - name.c_str(), valtype.c_str(), - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "Unknown texture{} optional argument: \"{}\", <{}> ({}:{})", + tex3d ? "3d" : "", name, valtype, op.sourcefile(), op.sourceline()); #undef SKIP_PARAM_WIDE_FLOAT #undef SKIP_PARAM_WIDE_STRING @@ -5045,9 +5046,9 @@ llvm_batched_trace_options(BatchedBackendLLVM &rop, int opnum, PARAM_UNIFORM(shade, TypeDesc::INT) PARAM_UNIFORM(traceset, TypeDesc::STRING) - rop.shadingcontext()->errorf ("Unknown trace optional argument: \"%s\", <%s> (%s:%d)", - name.c_str(), valtype.c_str(), - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "Unknown trace optional argument: \"{}\", <{}> ({}:{})", name, + valtype, op.sourcefile(), op.sourceline()); #undef PARAM_UNIFORM } @@ -5124,9 +5125,9 @@ llvm::Value* llvm_batched_trace_varying_options(BatchedBackendLLVM &rop, int opn PARAM_VARYING(shade, TypeDesc::INT) PARAM_VARYING(traceset, TypeDesc::STRING) - rop.shadingcontext()->errorf ("Unknown trace optional argument: \"%s\", <%s> (%s:%d)", - name.c_str(), valtype.c_str(), - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "Unknown trace optional argument: \"{}\", <{}> ({}:{})", name, + valtype, op.sourcefile(), op.sourceline()); #undef PARAM_VARYING @@ -5317,10 +5318,9 @@ llvm_batched_noise_options (BatchedBackendLLVM &rop, int opnum, rop.llvm_load_value (Val, 0, NULL, 0, TypeDesc::TypeFloat)); } else { - rop.shadingcontext()->errorf ("Unknown %s optional argument: \"%s\", <%s> (%s:%d)", - op.opname().c_str(), - name.c_str(), valtype.c_str(), - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "Unknown {} optional argument: \"{}\", <{}> ({}:{})", + op.opname(), name, valtype, op.sourcefile(), op.sourceline()); } } @@ -5408,10 +5408,9 @@ llvm_batched_noise_varying_options ( // do any binning for the varying direction. continue; } else { - rop.shadingcontext()->errorf ("Unknown %s optional argument: \"%s\", <%s> (%s:%d)", - op.opname().c_str(), - name.c_str(), valtype.c_str(), - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "Unknown {} optional argument: \"{}\", <{}> ({}:{})", + op.opname(), name, valtype, op.sourcefile(), op.sourceline()); } } return remainingMask; @@ -5522,9 +5521,10 @@ LLVMGEN (llvm_gen_noise) derivs = true; name = periodic ? Strings::gaborpnoise : Strings::gabornoise; } else { - rop.shadingcontext()->errorf ("%snoise type \"%s\" is unknown, called from (%s:%d)", - (periodic ? "periodic " : ""), name.c_str(), - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "{}noise type \"{}\" is unknown, called from ({}:{})", + (periodic ? "periodic " : ""), name, op.sourcefile(), + op.sourceline()); return false; } @@ -6806,9 +6806,9 @@ LLVMGEN (llvm_gen_pointcloud_search) } else { // It is a regular attribute, push it to the arg list if (!Name.is_uniform()) { - rop.shadingcontext()->errorf ( - "pointcloud_search named attribute parameter is varying, batched code gen requires a constant or uniform attribute name, called from (%s:%d)", - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "pointcloud_search named attribute parameter is varying, batched code gen requires a constant or uniform attribute name, called from ({}:{})", + op.sourcefile(), op.sourceline()); return false; } @@ -6835,9 +6835,9 @@ LLVMGEN (llvm_gen_pointcloud_search) // per the OSL language specification const int const_max_points = Max_points.get_int(); if (capacity < const_max_points) { - rop.shadingcontext()->warningf ( - "Arrays too small for pointcloud lookup at (%s:%d) (%s:%d)", - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->warningfmt( + "Arrays too small for pointcloud lookup at ({}:{}) ({}:{})", + op.sourcefile(), op.sourceline()); args[maxPointsArgumentIndex] = rop.ll.constant(capacity); } } else { @@ -6947,9 +6947,9 @@ LLVMGEN (llvm_gen_pointcloud_get) OSL_ASSERT(Data.is_varying()); if (!Attr_name.is_uniform()) { - rop.shadingcontext()->errorf ( - "pointcloud_get named attribute parameter is varying, batched code gen requires a constant or uniform attribute name, called from (%s:%d)", - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "pointcloud_get named attribute parameter is varying, batched code gen requires a constant or uniform attribute name, called from ({}:{})", + op.sourcefile(), op.sourceline()); return false; } bool requires_binning = Filename.is_varying(); @@ -7092,9 +7092,9 @@ LLVMGEN (llvm_gen_pointcloud_write) for (int i = 0; i < nattrs; ++i) { Symbol *namesym = rop.opargsym (op, 3+2*i); if (!namesym->is_uniform()) { - rop.shadingcontext()->errorf ( - "pointcloud_write named attribute parameter is varying, batched code gen requires a constant or uniform attribute name, called from (%s:%d)", - op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "pointcloud_write named attribute parameter is varying, batched code gen requires a constant or uniform attribute name, called from ({}:{})", + op.sourcefile(), op.sourceline()); return false; } diff --git a/src/liboslexec/batched_llvm_instance.cpp b/src/liboslexec/batched_llvm_instance.cpp index 83fbbfc96..853f02ba5 100644 --- a/src/liboslexec/batched_llvm_instance.cpp +++ b/src/liboslexec/batched_llvm_instance.cpp @@ -897,12 +897,11 @@ BatchedBackendLLVM::llvm_type_groupdata() } group().llvm_groupdata_wide_size(offset); if (llvm_debug() >= 2) - std::cout << " Group struct had " << order << " fields, total size " - << offset << "\n\n"; + OSL::print(" Group struct had {} fields, total size {}\n\n", order, + offset); - std::string groupdataname - = Strutil::sprintf("Groupdata_%llu", - (long long unsigned int)group().name().hash()); + std::string groupdataname = fmtformat("Groupdata_{}", + group().name().hash()); m_llvm_type_groupdata = ll.type_struct(fields, groupdataname, false /*is_packed*/); @@ -1063,9 +1062,9 @@ BatchedBackendLLVM::llvm_assign_initial_value( // We had a userdata pre-placement record for this variable. // Just copy from the correct offset location! - // Strutil::print("GEN found placeable userdata input {} -> {} {} size={}\n", - // sym.name(), symloc->name, sym.typespec(), - // symloc->type.size()); + // OSL::print("GEN found placeable userdata input {} -> {} {} size={}\n", + // sym.name(), symloc->name, sym.typespec(), + // symloc->type.size()); const int deriv_count = (symloc->derivs && sym.has_derivs()) ? 3 : 1; llvm::Value* sym_offset = ll.constanti64(symloc->offset); @@ -1703,9 +1702,8 @@ BatchedBackendLLVM::build_llvm_init() // Make a group init function: void group_init(ShaderGlobals*, GroupData*) // Note that the GroupData* is passed as a void*. OSL_ASSERT(m_library_selector); - std::string unique_name = Strutil::sprintf("%s_group_%d_init", - m_library_selector, - group().id()); + std::string unique_name = fmtformat("{}_group_{}_init", m_library_selector, + group().id()); ll.current_function(ll.make_function(unique_name, false, ll.type_void(), // return type { llvm_type_sg_ptr(), @@ -1750,7 +1748,7 @@ BatchedBackendLLVM::build_llvm_init() #if 0 /* helpful for debugging */ if (llvm_debug()) { - llvm_gen_debug_printf (Strutil::sprintf("\n\n\n\nGROUP! %s",group().name())); + llvm_gen_debug_printf (fmtformat("\n\n\n\nGROUP! {}",group().name())); llvm_gen_debug_printf ("enter group initlayer %d %s %s"); this->layer(), inst()->layername(), inst()->shadername())); } #endif @@ -1794,15 +1792,13 @@ BatchedBackendLLVM::build_llvm_init() // All done #if 0 /* helpful for debugging */ if (llvm_debug()) - llvm_gen_debug_printf (Strutil::sprintf("exit group init %s", - group().name()); + llvm_gen_debug_printf(fmtformat("exit group init {}", group().name()); #endif ll.op_return(); if (llvm_debug()) - std::cout << "group init func (" << unique_name << ") " - << " after llvm = " - << ll.bitcode_string(ll.current_function()) << "\n"; + OSL::print("group init func ({}) after llvm = {}\n", unique_name, + ll.bitcode_string(ll.current_function())); if (ll.debug_is_enabled()) { ll.debug_pop_function(); @@ -1828,9 +1824,9 @@ BatchedBackendLLVM::build_llvm_instance(bool groupentry) // Note that the GroupData* is passed as a void*. OSL_ASSERT(m_library_selector); std::string unique_layer_name - = Strutil::sprintf("%s_%s%s", m_library_selector, - (groupentry ? "__direct_callable__" : ""), - layer_function_name().c_str()); + = fmtformat("{}_{}{}", m_library_selector, + (groupentry ? "__direct_callable__" : ""), + layer_function_name()); bool is_entry_layer = group().is_entry_layer(layer()); ll.current_function( @@ -1908,9 +1904,9 @@ BatchedBackendLLVM::build_llvm_instance(bool groupentry) // and then run the layer. if (shadingsys().llvm_debug_layers()) llvm_gen_debug_printf( - Strutil::sprintf("checking for already-run layer %d %s %s", - this->layer(), inst()->layername(), - inst()->shadername())); + fmtformat("checking for already-run layer {} {} {}", + this->layer(), inst()->layername(), + inst()->shadername())); llvm::Value* previously_executed = ll.int_as_mask( previously_executed_value); llvm::Value* required_lanes_executed @@ -1926,17 +1922,17 @@ BatchedBackendLLVM::build_llvm_instance(bool groupentry) // insert point is now then_block // we've already executed, so return early if (shadingsys().llvm_debug_layers()) - llvm_gen_debug_printf(Strutil::sprintf( - " taking early exit, already executed layer %d %s %s", + llvm_gen_debug_printf(fmtformat( + " taking early exit, already executed layer {} {} {}", this->layer(), inst()->layername(), inst()->shadername())); ll.op_return(); ll.set_insert_point(after_block); } if (shadingsys().llvm_debug_layers()) - llvm_gen_debug_printf( - Strutil::sprintf("enter layer %d %s %s", this->layer(), - inst()->layername(), inst()->shadername())); + llvm_gen_debug_printf(fmtformat("enter layer {} {} {}", this->layer(), + inst()->layername(), + inst()->shadername())); // Mark this layer as executed if (!group().is_last_layer(layer())) { // Caller may only be asking for a subset of the lanes to be executed @@ -1980,8 +1976,8 @@ BatchedBackendLLVM::build_llvm_instance(bool groupentry) // If debugnan is turned on, globals check that their values are ok if (s.symtype() == SymTypeGlobal && shadingsys().debug_nan()) { TypeDesc t = s.typespec().simpletype(); - if (t.basetype - == TypeDesc::FLOAT) { // just check float-based types + if (t.basetype == TypeDesc::FLOAT) { + // just check float-based types int ncomps = t.numelements() * t.aggregate; if (s.is_uniform()) { llvm::Value* args[] @@ -2182,9 +2178,8 @@ BatchedBackendLLVM::build_llvm_instance(bool groupentry) if (! equivalent(s.typespec(), symloc->type) || s.typespec().is_closure()) { - std::cout << "No output copy for " << s.typespec() << ' ' << s.name() - << " because of type mismatch vs symloc=" << symloc->type - << "\n"; + // print("No output copy for {} {} because of type mismatch vs symloc={}\n", + // s.typespec(), s.name(), symloc->type); continue; // types didn't match } auto type = s.typespec().simpletype(); @@ -2243,9 +2238,9 @@ BatchedBackendLLVM::build_llvm_instance(bool groupentry) // All done if (shadingsys().llvm_debug_layers()) - llvm_gen_debug_printf( - Strutil::sprintf("exit layer %d %s %s", this->layer(), - inst()->layername(), inst()->shadername())); + llvm_gen_debug_printf(fmtformat("exit layer {} {} {}", this->layer(), + inst()->layername(), + inst()->shadername())); ll.op_return(); if (llvm_debug()) @@ -2679,11 +2674,10 @@ BatchedBackendLLVM::run() std::string safegroup = Strutil::replace(group().name(), "/", ".", true); if (safegroup.size() > 235) - safegroup - = Strutil::sprintf("TRUNC_%s_%d", - safegroup.substr(safegroup.size() - 235), - group().id()); - std::string name = Strutil::sprintf("%s.ll", safegroup); + safegroup = fmtformat("TRUNC_{}_{}", + safegroup.substr(safegroup.size() - 235), + group().id()); + std::string name = fmtformat("{}.ll", safegroup); std::ofstream out(name, std::ios_base::out | std::ios_base::trunc); if (out.good()) { out << ll.bitcode_string(ll.module()); @@ -2725,11 +2719,10 @@ BatchedBackendLLVM::run() std::string safegroup = Strutil::replace(group().name(), "/", ".", true); if (safegroup.size() > 235) - safegroup - = Strutil::sprintf("TRUNC_%s_%d", - safegroup.substr(safegroup.size() - 235), - group().id()); - std::string name = Strutil::sprintf("%s_opt.ll", safegroup); + safegroup = fmtformat("TRUNC_{}_{}", + safegroup.substr(safegroup.size() - 235), + group().id()); + std::string name = fmtformat("{}_opt.ll", safegroup); std::ofstream out(name, std::ios_base::out | std::ios_base::trunc); if (out.good()) { out << ll.bitcode_string(ll.module()); @@ -2769,9 +2762,9 @@ BatchedBackendLLVM::run() m_stat_total_llvm_time = timer(); if (shadingsys().m_compile_report) { - shadingcontext()->infof("JITed shader group %s:", group().name()); - shadingcontext()->infof( - " (%1.2fs = %1.2f setup, %1.2f ir, %1.2f opt, %1.2f jit; local mem %dKB)", + shadingcontext()->infofmt("JITed shader group {}:", group().name()); + shadingcontext()->infofmt( + " ({:1.2f}s = {:1.2f} setup, {:1.2f} ir, {:1.2f} opt, {:1.2f} jit; local mem {}KB)", m_stat_total_llvm_time, m_stat_llvm_setup_time, m_stat_llvm_irgen_time, m_stat_llvm_opt_time, m_stat_llvm_jit_time, m_llvm_local_mem / 1024); diff --git a/src/liboslexec/batched_rendservices.cpp b/src/liboslexec/batched_rendservices.cpp index 2cd30c443..2a0e1be84 100644 --- a/src/liboslexec/batched_rendservices.cpp +++ b/src/liboslexec/batched_rendservices.cpp @@ -180,8 +180,8 @@ BatchedRendererServices::get_texture_info_uniform( if (!status) { std::string err = texturesys()->geterror(); if (err.size() && bsg) { - bsg->uniform.context->errorf( - "[RendererServices::get_texture_info] %s", err); + bsg->uniform.context->errorfmt( + "[RendererServices::get_texture_info] {}", err); } } return status; diff --git a/src/liboslexec/constfold.cpp b/src/liboslexec/constfold.cpp index aea6321fd..2b197de16 100644 --- a/src/liboslexec/constfold.cpp +++ b/src/liboslexec/constfold.cpp @@ -1258,8 +1258,7 @@ DECLFOLDER(constfold_concat) return 0; // something non-constant ustring old = result; ustring s = S.get_string(); - result = ustring::sprintf ("%s%s", old.c_str() ? old.c_str() : "", - s.c_str() ? s.c_str() : ""); + result = ustring::fmtformat("{}{}", old, s); } // If we made it this far, all args were constants, and the // concatenation is in result. diff --git a/src/liboslexec/context.cpp b/src/liboslexec/context.cpp index 73751cbab..ce43d1498 100644 --- a/src/liboslexec/context.cpp +++ b/src/liboslexec/context.cpp @@ -167,7 +167,7 @@ bool ShadingContext::execute_cleanup () { if (! group()) { - errorf("execute_cleanup called again on a cleaned-up context"); + errorfmt("execute_cleanup called again on a cleaned-up context"); return false; } diff --git a/src/liboslexec/instance.cpp b/src/liboslexec/instance.cpp index 95658c45a..fa3c0ac7a 100644 --- a/src/liboslexec/instance.cpp +++ b/src/liboslexec/instance.cpp @@ -511,11 +511,12 @@ std::string ConnectedParam::str (const ShaderInstance *inst, bool unmangle) const { const Symbol *s = inst->symbol(param); - return Strutil::sprintf ("%s%s%s (%s)", - unmangle ? s->unmangled() : string_view(s->name()), - arrayindex >= 0 ? Strutil::sprintf("[%d]", arrayindex) : std::string(), - channel >= 0 ? Strutil::sprintf("[%d]", channel) : std::string(), - type); + return fmtformat("{}{}{} ({})", + unmangle ? s->unmangled() : string_view(s->name()), + arrayindex >= 0 ? fmtformat("[{}]", arrayindex) + : std::string(), + channel >= 0 ? fmtformat("[{}]", channel) : std::string(), + type); } @@ -524,8 +525,8 @@ std::string Connection::str (const ShaderGroup &group, const ShaderInstance *dstinst, bool unmangle) const { - return Strutil::sprintf ("%s -> %s", src.str(group[srclayer], unmangle), - dst.str(dstinst, unmangle)); + return fmtformat("{} -> {}", src.str(group[srclayer], unmangle), + dst.str(dstinst, unmangle)); } @@ -718,7 +719,7 @@ ShaderGroup::ShaderGroup (string_view name) m_name = name; } else { // No name -- make one up using the unique - m_name = ustring::sprintf ("unnamed_group_%d", m_id); + m_name = ustring::fmtformat("unnamed_group_{}", m_id); } } diff --git a/src/liboslexec/llvm_gen.cpp b/src/liboslexec/llvm_gen.cpp index 6a93c9c2c..a9eb421de 100644 --- a/src/liboslexec/llvm_gen.cpp +++ b/src/liboslexec/llvm_gen.cpp @@ -84,8 +84,8 @@ LLVMGEN (llvm_gen_generic); void BackendLLVM::llvm_gen_debug_printf (string_view message) { - ustring s = ustring::sprintf ("(%s %s) %s", inst()->shadername(), - inst()->layername(), message); + ustring s = ustring::fmtformat("({} {}) {}", inst()->shadername(), + inst()->layername(), message); ll.call_function ("osl_printf", sg_void_ptr(), ll.constant("%s\n"), ll.constant(s)); } @@ -256,8 +256,8 @@ LLVMGEN (llvm_gen_printf) std::vector call_args; if (!format_sym.is_constant()) { - rop.shadingcontext()->warningf("%s must currently have constant format\n", - op.opname()); + rop.shadingcontext()->warningfmt( + "{} must currently have constant format\n", op.opname()); return false; } @@ -301,8 +301,8 @@ LLVMGEN (llvm_gen_printf) ++format; char formatchar = *format++; // Also eat the format char if (arg >= op.nargs()) { - rop.shadingcontext()->errorf("Mismatch between format string and arguments (%s:%d)", - op.sourcefile(), op.sourceline()); + rop.shadingcontext()->errorfmt("Mismatch between format string and arguments ({}:{})", + op.sourcefile(), op.sourceline()); return false; } @@ -351,7 +351,9 @@ LLVMGEN (llvm_gen_printf) // In the OptiX case, we register each string separately. if (simpletype.arraylen >= 1) { // Mangle the element's name in case llvm_load_device_string calls getOrAllocateLLVMSymbol - ustring name = ustring::sprintf("__symname__%s[%d]", sym.mangled(), a); + ustring name + = ustring::fmtformat("__symname__{}[{}]", + sym.mangled(), a); Symbol lsym(name, TypeDesc::TypeString, sym.symtype()); lsym.set_dataptr(SymArena::Absolute, &((ustring*)sym.dataptr())[a]); @@ -1115,7 +1117,7 @@ LLVMGEN (llvm_gen_unary_op) result = rop.ll.op_not (src_val); } else { // Don't know how to handle this. - rop.shadingcontext()->errorf("Don't know how to handle op '%s', eliding the store\n", opname); + rop.shadingcontext()->errorfmt("Don't know how to handle op '{}', eliding the store\n", opname); } // Store the result @@ -1133,7 +1135,7 @@ LLVMGEN (llvm_gen_unary_op) if (dst_derivs) { // mul results in - rop.shadingcontext()->infof("punting on derivatives for now\n"); + rop.shadingcontext()->infofmt("punting on derivatives for now\n"); // FIXME!! } } @@ -2429,9 +2431,9 @@ llvm_gen_texture_options (BackendLLVM &rop, int opnum, continue; } - rop.shadingcontext()->errorf("Unknown texture%s optional argument: \"%s\", <%s> (%s:%d)", - tex3d ? "3d" : "", name, valtype, - op.sourcefile(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "Unknown texture{} optional argument: \"{}\", <{}> ({}:{})", + tex3d ? "3d" : "", name, valtype, op.sourcefile(), op.sourceline()); #undef PARAM_INT #undef PARAM_FLOAT #undef PARAM_FLOAT_STR @@ -2655,9 +2657,9 @@ llvm_gen_trace_options (BackendLLVM &rop, int opnum, } else if (name == Strings::traceset && valtype == TypeDesc::STRING) { rop.ll.call_function ("osl_trace_set_traceset", opt, val); } else { - rop.shadingcontext()->errorf("Unknown trace() optional argument: \"%s\", <%s> (%s:%d)", - name, valtype, - op.sourcefile(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "Unknown trace() optional argument: \"{}\", <{}> ({}:{})", name, + valtype, op.sourcefile(), op.sourceline()); } } @@ -2762,9 +2764,9 @@ llvm_gen_noise_options (BackendLLVM &rop, int opnum, rop.llvm_load_value (Val, 0, NULL, 0, TypeDesc::TypeFloat)); } else { - rop.shadingcontext()->errorf("Unknown %s optional argument: \"%s\", <%s> (%s:%d)", - op.opname(), name, valtype, - op.sourcefile(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "Unknown {} optional argument: \"{}\", <{}> ({}:{})", + op.opname(), name, valtype, op.sourcefile(), op.sourceline()); } } return opt; @@ -2862,9 +2864,10 @@ LLVMGEN (llvm_gen_noise) derivs = true; name = periodic ? Strings::gaborpnoise : Strings::gabornoise; } else { - rop.shadingcontext()->errorf("%snoise type \"%s\" is unknown, called from (%s:%d)", - (periodic ? "periodic " : ""), name, - op.sourcefile(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "{}noise type \"{}\" is unknown, called from ({}:{})", + (periodic ? "periodic " : ""), name, op.sourcefile(), + op.sourceline()); return false; } @@ -3339,7 +3342,9 @@ llvm_gen_keyword_fill(BackendLLVM &rop, Opcode &op, const ClosureRegistry::Closu } } if (!legal) { - rop.shadingcontext()->warningf("Unsupported closure keyword arg \"%s\" for %s (%s:%d)", key, clname, op.sourcefile(), op.sourceline()); + rop.shadingcontext()->warningfmt( + "Unsupported closure keyword arg \"{}\" for {} ({}:{})", key, + clname, op.sourcefile(), op.sourceline()); } } } @@ -3361,10 +3366,11 @@ LLVMGEN (llvm_gen_closure) const ClosureRegistry::ClosureEntry * clentry = rop.shadingsys().find_closure(closure_name); if (!clentry) { - rop.llvm_gen_error (Strutil::sprintf("Closure '%s' is not supported by the current renderer, called from %s:%d in shader \"%s\", layer %d \"%s\", group \"%s\"", - closure_name, op.sourcefile(), op.sourceline(), - rop.inst()->shadername(), rop.layer(), - rop.inst()->layername(), rop.group().name())); + rop.llvm_gen_error(fmtformat( + "Closure '{}' is not supported by the current renderer, called from {}:{} in shader \"{}\", layer {} \"{}\", group \"{}\"", + closure_name, op.sourcefile(), op.sourceline(), + rop.inst()->shadername(), rop.layer(), rop.inst()->layername(), + rop.group().name())); return false; } @@ -3431,10 +3437,10 @@ LLVMGEN (llvm_gen_closure) rop.ll.op_memcpy (dst, src, (int)p.type.size(), 4 /* use 4 byte alignment for now */); } else { - rop.shadingcontext()->errorf("Incompatible formal argument %d to '%s' closure (%s %s, expected %s). Prototypes don't match renderer registry (%s:%d).", - carg + 1, closure_name, - sym.typespec(), sym.unmangled(), p.type, - op.sourcefile(), op.sourceline()); + rop.shadingcontext()->errorfmt( + "Incompatible formal argument {} to '{}' closure ({} {}, expected {}). Prototypes don't match renderer registry ({}:{}).", + carg + 1, closure_name, sym.typespec(), sym.unmangled(), p.type, + op.sourcefile(), op.sourceline()); } } @@ -3549,8 +3555,8 @@ LLVMGEN (llvm_gen_pointcloud_search) // per the OSL language specification const int const_max_points = Max_points.get_int(); if (capacity < const_max_points) { - rop.shadingcontext()->warningf ( - "Arrays too small for pointcloud lookup at (%s:%d) (%s:%d)", + rop.shadingcontext()->warningfmt( + "Arrays too small for pointcloud lookup at ({}:{}) ({}:{})", op.sourcefile().c_str(), op.sourceline()); args[maxPointsArgumentIndex] = rop.ll.constant(capacity); } diff --git a/src/liboslexec/llvm_instance.cpp b/src/liboslexec/llvm_instance.cpp index 2d58d0017..081ba0da4 100644 --- a/src/liboslexec/llvm_instance.cpp +++ b/src/liboslexec/llvm_instance.cpp @@ -491,7 +491,8 @@ BackendLLVM::llvm_assign_initial_value (const Symbol& sym, bool force) llvm::Value* name_arg = NULL; if (use_optix()) { // We need to make a DeviceString for the parameter name - ustring arg_name = ustring::sprintf ("osl_paramname_%s_%d", symname, sym.layer()); + ustring arg_name = ustring::fmtformat("osl_paramname_{}_{}", + symname, sym.layer()); Symbol symname_const (arg_name, TypeDesc::TypeString, SymTypeConst); symname_const.set_dataptr(SymArena::Absolute, &symname); name_arg = llvm_load_device_string (symname_const, /*follow*/ true); @@ -547,8 +548,9 @@ BackendLLVM::llvm_assign_initial_value (const Symbol& sym, bool force) } else if (use_optix() && ! sym.typespec().is_closure() && ! sym.typespec().is_string()) { // If the call to osl_bind_interpolated_param returns 0, the default // value needs to be loaded from a CUDA variable. - ustring var_name = ustring::sprintf ("%s_%s_%s_%d", sym.name(), - inst()->layername(), group().name(), group().id()); + ustring var_name = ustring::fmtformat("{}_{}_{}_{}", sym.name(), + inst()->layername(), + group().name(), group().id()); // The "true" argument triggers the creation of the metadata needed to // make the variable visible to OptiX. @@ -833,8 +835,9 @@ BackendLLVM::build_llvm_code (int beginop, int endop, llvm::BasicBlock *bb) op.opname() == op_end) { // Skip this op, it does nothing... } else { - shadingcontext()->errorf("LLVMOSL: Unsupported op %s in layer %s\n", - op.opname(), inst()->layername()); + shadingcontext()->errorfmt( + "LLVMOSL: Unsupported op {} in layer {}\n", op.opname(), + inst()->layername()); return false; } @@ -1336,7 +1339,9 @@ BackendLLVM::run () osl_llvm_compiled_rs_dependant_ops_size, "llvm_rs_dependant_ops", &err)); if (err.length()) - shadingcontext()->errorf("llvm::parseBitcodeFile returned '%s' for llvm_rs_dependant_ops\n", err); + shadingcontext()->errorfmt( + "llvm::parseBitcodeFile returned '{}' for llvm_rs_dependant_ops\n", + err); std::vector& rs_free_function_bitcode = shadingsys().m_rs_bitcode; OSL_ASSERT (rs_free_function_bitcode.size() && "Free Function bitcode is empty"); @@ -1345,18 +1350,20 @@ BackendLLVM::run () ll.module_from_bitcode (static_cast(rs_free_function_bitcode.data()), rs_free_function_bitcode.size(), "rs_free_functions", &err); if (err.length()) - shadingcontext()->errorf("llvm::parseBitcodeFile returned '%s' for rs_free_functions\n", err); - + shadingcontext()->errorfmt( + "llvm::parseBitcodeFile returned '{}' for rs_free_functions\n", + err); std::unique_ptr rs_free_functions_module_ptr (rs_free_functions_module); bool success = ll.absorb_module(std::move(rs_free_functions_module_ptr)); if (!success) - shadingcontext()->errorf("LLVM_Util::absorb_module failed'\n"); + shadingcontext()->errorfmt("LLVM_Util::absorb_module failed'\n"); } else { ll.module (ll.module_from_bitcode ((char*)osl_llvm_compiled_ops_block, osl_llvm_compiled_ops_size, "llvm_ops", &err)); if (err.length()) - shadingcontext()->errorf("llvm::parseBitcodeFile returned '%s' for llvm_ops\n", err); + shadingcontext()->errorfmt( + "llvm::parseBitcodeFile returned '{}' for llvm_ops\n", err); } } else { @@ -1365,7 +1372,7 @@ BackendLLVM::run () osl_llvm_compiled_ops_cuda_size, "llvm_ops", &err)); if (err.length()) - shadingcontext()->errorf("llvm::parseBitcodeFile returned '%s' for cuda llvm_ops\n", err); + shadingcontext()->errorfmt("llvm::parseBitcodeFile returned '{}' for cuda llvm_ops\n", err); #else OSL_ASSERT (0 && "Must generate LLVM CUDA bitcode for OptiX"); #endif @@ -1379,7 +1386,7 @@ BackendLLVM::run () ! ll.make_jit_execengine (&err, ll.lookup_isa_by_name(shadingsys().m_llvm_jit_target), shadingsys().llvm_debugging_symbols(), shadingsys().llvm_profiling_events())) { - shadingcontext()->errorf("Failed to create engine: %s\n", err); + shadingcontext()->errorfmt("Failed to create engine: {}\n", err); OSL_ASSERT (0); return; } @@ -1432,8 +1439,9 @@ BackendLLVM::run () if (shadingsys().m_max_local_mem_KB && m_llvm_local_mem/1024 > shadingsys().m_max_local_mem_KB) { - shadingcontext()->errorf("Shader group \"%s\" needs too much local storage: %d KB", - group().name(), m_llvm_local_mem/1024); + shadingcontext()->errorfmt( + "Shader group \"{}\" needs too much local storage: {} KB", + group().name(), m_llvm_local_mem / 1024); } // The module contains tons of "library" functions that our generated IR @@ -1492,8 +1500,10 @@ BackendLLVM::run () safegroup = Strutil::replace (group().name(), "/", "_", true); safegroup = Strutil::replace (safegroup , ":", "_", true); if (safegroup.size() > 235) - safegroup = Strutil::sprintf ("TRUNC_%s_%d", safegroup.substr(safegroup.size()-235), group().id()); - std::string name = Strutil::sprintf ("%s.ll", safegroup); + safegroup = fmtformat("TRUNC_{}_{}", + safegroup.substr(safegroup.size() - 235), + group().id()); + std::string name = fmtformat("{}.ll", safegroup); OIIO::ofstream out; OIIO::Filesystem::open(out, name); if (out) { @@ -1547,8 +1557,11 @@ BackendLLVM::run () safegroup = Strutil::replace (group().name(), "/", "_", true); safegroup = Strutil::replace (safegroup , ":", "_", true); if (safegroup.size() > 235) - safegroup = Strutil::sprintf ("TRUNC_%s_%d", safegroup.substr(safegroup.size()-235), group().id()); - std::string name = Strutil::sprintf ("%s_O%d.ll", safegroup, shadingsys().llvm_optimize()); + safegroup = fmtformat("TRUNC_{}_{}", + safegroup.substr(safegroup.size() - 235), + group().id()); + std::string name = fmtformat("{}_O{}.ll", safegroup, + shadingsys().llvm_optimize()); OIIO::ofstream out; OIIO::Filesystem::open(out, name); if (out) { @@ -1560,7 +1573,7 @@ BackendLLVM::run () } if (use_optix()) { - std::string name = Strutil::sprintf ("%s_%d", group().name(), group().id()); + std::string name = fmtformat("{}_{}", group().name(), group().id()); #if (OPTIX_VERSION < 70000) // Create an llvm::Module from the renderer-supplied library bitcode @@ -1622,11 +1635,12 @@ BackendLLVM::run () m_stat_total_llvm_time = timer(); if (shadingsys().m_compile_report) { - shadingcontext()->infof("JITed shader group %s:", group().name()); - shadingcontext()->infof(" (%1.2fs = %1.2f setup, %1.2f ir, %1.2f opt, %1.2f jit; local mem %dKB)", - m_stat_total_llvm_time, m_stat_llvm_setup_time, - m_stat_llvm_irgen_time, m_stat_llvm_opt_time, - m_stat_llvm_jit_time, m_llvm_local_mem/1024); + shadingcontext()->infofmt("JITed shader group {}:", group().name()); + shadingcontext()->infofmt( + " ({:1.2f}s = {:1.2f} setup, {:1.2f} ir, {:1.2f} opt, {:1.2f} jit; local mem {}KB)", + m_stat_total_llvm_time, m_stat_llvm_setup_time, + m_stat_llvm_irgen_time, m_stat_llvm_opt_time, m_stat_llvm_jit_time, + m_llvm_local_mem / 1024); } } diff --git a/src/liboslexec/llvmutil_test.cpp b/src/liboslexec/llvmutil_test.cpp index d2d34fe9c..b446c53f2 100644 --- a/src/liboslexec/llvmutil_test.cpp +++ b/src/liboslexec/llvmutil_test.cpp @@ -33,7 +33,7 @@ getargs (int argc, char *argv[]) "--debug", &debug, "Debug mode", "--memtest %d", &memtest, "Memory test mode (arg: iterations)", // "--iters %d", &iterations, - // Strutil::sprintf("Number of iterations (default: %d)", iterations).c_str(), + // Strutil::fmt::format("Number of iterations (default: {})", iterations).c_str(), // "--trials %d", &ntrials, "Number of trials", NULL); if (ap.parse (argc, (const char**)argv) < 0) { diff --git a/src/liboslexec/loadshader.cpp b/src/liboslexec/loadshader.cpp index a9fc36511..5e4f80492 100644 --- a/src/liboslexec/loadshader.cpp +++ b/src/liboslexec/loadshader.cpp @@ -578,7 +578,7 @@ ShadingSystemImpl::loadshader (string_view cname) // if (debug()) { // std::string s = r->print (); // if (s.length()) - // infof("%s", s); + // infofmt("{}", s); // } } else { errorfmt("Unable to read \"{}\"", filename); diff --git a/src/liboslexec/opcolor.cpp b/src/liboslexec/opcolor.cpp index 1e84bf461..a5a3b9f19 100644 --- a/src/liboslexec/opcolor.cpp +++ b/src/liboslexec/opcolor.cpp @@ -249,8 +249,8 @@ ColorSystem::set_colorspace (StringParam colorspace) #else void ColorSystem::error(StringParam src, StringParam dst, Context context) const { - context->errorf("Unknown color space transformation" - " \"%s\" -> \"%s\"", src, dst); + context->errorfmt("Unknown color space transformation \"{}\" -> \"{}\"", + src, dst); } static inline const ColorSystem& op_color_colorsystem (void *sg) { diff --git a/src/liboslexec/opmatrix.cpp b/src/liboslexec/opmatrix.cpp index d3bca7d5f..d684d8ae2 100644 --- a/src/liboslexec/opmatrix.cpp +++ b/src/liboslexec/opmatrix.cpp @@ -152,7 +152,7 @@ osl_get_matrix (void *sg_, void *r, const char *from) MAT(r).makeIdentity(); ShadingContext *ctx = (ShadingContext *)((ShaderGlobals *)sg)->context; if (ctx->shadingsys().unknown_coordsys_error()) - ctx->errorf("Unknown transformation \"%s\"", from); + ctx->errorfmt("Unknown transformation \"{}\"", from); } return ok; } @@ -182,7 +182,7 @@ osl_get_inverse_matrix (void *sg_, void *r, const char *to) MAT(r).makeIdentity (); ShadingContext *ctx = (ShadingContext *)((ShaderGlobals *)sg)->context; if (ctx->shadingsys().unknown_coordsys_error()) - ctx->errorf("Unknown transformation \"%s\"", to); + ctx->errorfmt("Unknown transformation \"{}\"", to); } return ok; } @@ -208,7 +208,7 @@ osl_prepend_matrix_from (void *sg, void *r, const char *from) else { ShadingContext *ctx = (ShadingContext *)((ShaderGlobals *)sg)->context; if (ctx->shadingsys().unknown_coordsys_error()) - ctx->errorf("Unknown transformation \"%s\"", from); + ctx->errorfmt("Unknown transformation \"{}\"", from); } #endif return ok; diff --git a/src/liboslexec/opmessage.cpp b/src/liboslexec/opmessage.cpp index 6f7738e0d..695ac76a0 100644 --- a/src/liboslexec/opmessage.cpp +++ b/src/liboslexec/opmessage.cpp @@ -43,15 +43,15 @@ osl_setmessage (ShaderGlobals *sg, const char *name_, long long type_, void *val if (m->name == name) { // message already exists? if (m->has_data()) - sg->context->errorf( - "message \"%s\" already exists (created here: %s:%d)" - " cannot set again from %s:%d", - name, m->sourcefile, m->sourceline, sourcefile, sourceline); + sg->context->errorfmt( + "message \"{}\" already exists (created here: {}:{})" + " cannot set again from {}:{}", + name, m->sourcefile, m->sourceline, sourcefile, sourceline); else // NOTE: this cannot be triggered when strict_messages=false because we won't record "failed" getmessage calls - sg->context->errorf( - "message \"%s\" was queried before being set (queried here: %s:%d)" - " setting it now (%s:%d) would lead to inconsistent results", - name, m->sourcefile, m->sourceline, sourcefile, sourceline); + sg->context->errorfmt( + "message \"{}\" was queried before being set (queried here: {}:{})" + " setting it now ({}:{}) would lead to inconsistent results", + name, m->sourcefile, m->sourceline, sourcefile, sourceline); return; } } @@ -88,14 +88,15 @@ osl_getmessage (ShaderGlobals *sg, const char *source_, const char *name_, if (m->name == name) { if (m->type != type) { // found message, but types don't match - sg->context->errorf( - "type mismatch for message \"%s\" (%s as %s here: %s:%d)" - " cannot fetch as %s from %s:%d", + sg->context->errorfmt( + "type mismatch for message \"{}\" ({} as {} here: {}:{})" + " cannot fetch as {} from {}:{}", name, m->has_data() ? "created" : "queried", - m->type == TypeDesc::PTR ? "closure color" : m->type.c_str(), + m->type == TypeDesc::PTR ? "closure color" + : m->type.c_str(), m->sourcefile, m->sourceline, - is_closure ? "closure color" : type.c_str(), - sourcefile, sourceline); + is_closure ? "closure color" : type.c_str(), sourcefile, + sourceline); return 0; } if (!m->has_data()) { @@ -104,13 +105,13 @@ osl_getmessage (ShaderGlobals *sg, const char *source_, const char *name_, } if (m->layeridx > layeridx) { // found message, but was set by a layer deeper than the one querying the message - sg->context->errorf( - "message \"%s\" was set by layer #%d (%s:%d)" - " but is being queried by layer #%d (%s:%d)" + sg->context->errorfmt( + "message \"{}\" was set by layer #{} ({}:{})" + " but is being queried by layer #{} ({}:{})" " - messages may only be transfered from nodes " "that appear earlier in the shading network", - name, m->layeridx, m->sourcefile, m->sourceline, - layeridx, sourcefile, sourceline); + name, m->layeridx, m->sourcefile, m->sourceline, layeridx, + sourcefile, sourceline); return 0; } // Message found! diff --git a/src/liboslexec/oslexec_pvt.h b/src/liboslexec/oslexec_pvt.h index 226f0688e..5d6077e1c 100644 --- a/src/liboslexec/oslexec_pvt.h +++ b/src/liboslexec/oslexec_pvt.h @@ -508,25 +508,25 @@ class ShadingSystemImpl // take std::format-like arguments. template inline void errorfmt(const Str& fmt, Args&&... args) const { - error(Strutil::fmt::format(fmt, std::forward(args)...)); + error(fmtformat(fmt, std::forward(args)...)); } void error (const std::string &message) const; template inline void warningfmt(const Str& fmt, Args&&... args) const { - warning(Strutil::fmt::format(fmt, std::forward(args)...)); + warning(fmtformat(fmt, std::forward(args)...)); } void warning (const std::string &message) const; template inline void infofmt(const Str& fmt, Args&&... args) const { - info(Strutil::fmt::format(fmt, std::forward(args)...)); + info(fmtformat(fmt, std::forward(args)...)); } void info (const std::string &message) const; template inline void messagefmt(const Str& fmt, Args&&... args) const { - message(Strutil::fmt::format(fmt, std::forward(args)...)); + message(fmtformat(fmt, std::forward(args)...)); } void message (const std::string &message) const; @@ -1843,41 +1843,14 @@ class OSLEXECPUBLIC ShadingContext { return (ClosureAdd *) m_sc.m_closure_pool.alloc(WidthT * sizeof(ClosureAdd), alignof(ClosureAdd)); } - template - inline - void errorf(Mask mask, const char* fmt, ArgListT... args) const - { - m_sc.record_error(ErrorHandler::EH_ERROR, Strutil::sprintf (fmt, args...), static_cast>(mask)); - } - - template - inline - void warningf(Mask mask, const char* fmt, ArgListT... args) const - { - m_sc.record_error(ErrorHandler::EH_WARNING, Strutil::sprintf (fmt, args...), static_cast>(mask)); - } - - template - inline - void infof(Mask mask, const char* fmt, ArgListT... args) const - { - m_sc.record_error(ErrorHandler::EH_INFO, Strutil::sprintf (fmt, args...), static_cast>(mask)); - } - - template - inline - void messagef(Mask mask, const char* fmt, ArgListT... args) const - { - m_sc.record_error(ErrorHandler::EH_MESSAGE, Strutil::sprintf (fmt, args...), static_cast>(mask)); - } - template inline void errorfmt(Mask mask, const Str& fmt, Args&&... args) const { m_sc.record_error(ErrorHandler::EH_ERROR, - Strutil::fmt::format(fmt, std::forward(args)...), - static_cast>(mask)); + fmtformat(fmt, std::forward(args)...), + static_cast>( + mask)); } template @@ -1885,8 +1858,9 @@ class OSLEXECPUBLIC ShadingContext { void warningfmt(Mask mask, const Str& fmt, Args&&... args) const { m_sc.record_error(ErrorHandler::EH_WARNING, - Strutil::fmt::format(fmt, std::forward(args)...), - static_cast>(mask)); + fmtformat(fmt, std::forward(args)...), + static_cast>( + mask)); } template @@ -1894,8 +1868,9 @@ class OSLEXECPUBLIC ShadingContext { void infofmt(Mask mask, const Str& fmt, Args&&... args) const { m_sc.record_error(ErrorHandler::EH_INFO, - Strutil::fmt::format(fmt, std::forward(args)...), - static_cast>(mask)); + fmtformat(fmt, std::forward(args)...), + static_cast>( + mask)); } template @@ -1903,8 +1878,9 @@ class OSLEXECPUBLIC ShadingContext { void messagefmt(Mask mask, const Str& fmt, Args&&... args) const { m_sc.record_error(ErrorHandler::EH_MESSAGE, - Strutil::fmt::format(fmt, std::forward(args)...), - static_cast>(mask)); + fmtformat(fmt, std::forward(args)...), + static_cast>( + mask)); } }; @@ -2067,44 +2043,24 @@ class OSLEXECPUBLIC ShadingContext { // Process all the recorded errors, warnings, printfs void process_errors () const; - template - inline void errorf(const char* fmt, const Args&... args) const { - record_error(ErrorHandler::EH_ERROR, Strutil::sprintf (fmt, args...)); - } - - template - inline void warningf(const char* fmt, const Args&... args) const { - record_error(ErrorHandler::EH_WARNING, Strutil::sprintf (fmt, args...)); - } - - template - inline void infof(const char* fmt, const Args&... args) const { - record_error(ErrorHandler::EH_INFO, Strutil::sprintf (fmt, args...)); - } - - template - inline void messagef(const char* fmt, const Args&... args) const { - record_error(ErrorHandler::EH_MESSAGE, Strutil::sprintf (fmt, args...)); - } - template inline void errorfmt(const char* fmt, const Args&... args) const { - record_error(ErrorHandler::EH_ERROR, Strutil::fmt::format(fmt, args...)); + record_error(ErrorHandler::EH_ERROR, fmtformat(fmt, args...)); } template inline void warningfmt(const char* fmt, const Args&... args) const { - record_error(ErrorHandler::EH_WARNING, Strutil::fmt::format(fmt, args...)); + record_error(ErrorHandler::EH_WARNING, fmtformat(fmt, args...)); } template inline void infofmt(const char* fmt, const Args&... args) const { - record_error(ErrorHandler::EH_INFO, Strutil::fmt::format(fmt, args...)); + record_error(ErrorHandler::EH_INFO, fmtformat(fmt, args...)); } template inline void messagefmt(const char* fmt, const Args&... args) const { - record_error(ErrorHandler::EH_MESSAGE, Strutil::fmt::format(fmt, args...)); + record_error(ErrorHandler::EH_MESSAGE, fmtformat(fmt, args...)); } void reserve_heap(size_t size) { @@ -2338,8 +2294,7 @@ class OSOProcessorBase { // Mangle the group and layer into a unique function name std::string layer_function_name (const ShaderGroup &group, const ShaderInstance &inst) { - return Strutil::sprintf ("%s_%s_%d", group.name(), - inst.layername(), inst.id()); + return fmtformat("{}_{}_{}", group.name(), inst.layername(), inst.id()); } std::string layer_function_name () { return layer_function_name (group(), *inst()); diff --git a/src/liboslexec/rendservices.cpp b/src/liboslexec/rendservices.cpp index fc856b12a..f28c5d937 100644 --- a/src/liboslexec/rendservices.cpp +++ b/src/liboslexec/rendservices.cpp @@ -145,7 +145,7 @@ RendererServices::texture (ustring filename, TextureHandle *texture_handle, if (errormessage) { *errormessage = ustring(err); } else { - context->errorf("[RendererServices::texture] %s", err); + context->errorfmt("[RendererServices::texture] {}", err); } } else if (errormessage) { *errormessage = Strings::unknown; @@ -181,7 +181,7 @@ RendererServices::texture3d (ustring filename, TextureHandle *texture_handle, if (errormessage) { *errormessage = ustring(err); } else { - sg->context->errorf("[RendererServices::texture3d] %s", err); + sg->context->errorfmt("[RendererServices::texture3d] {}", err); } } else if (errormessage) { *errormessage = Strings::unknown; @@ -215,7 +215,7 @@ RendererServices::environment (ustring filename, TextureHandle *texture_handle, if (errormessage) { *errormessage = ustring(err); } else { - sg->context->errorf("[RendererServices::environment] %s", err); + sg->context->errorfmt("[RendererServices::environment] {}", err); } } else if (errormessage) { *errormessage = Strings::unknown; @@ -247,7 +247,7 @@ RendererServices::get_texture_info (ustring filename, if (errormessage) { *errormessage = ustring(err); } else { - shading_context->errorf("[RendererServices::get_texture_info] %s", err); + shading_context->errorfmt("[RendererServices::get_texture_info] {}", err); } } else if (errormessage) { // gettextureinfo failed but did not provide an error, so none should be emitted diff --git a/src/liboslexec/runtimeoptimize.cpp b/src/liboslexec/runtimeoptimize.cpp index d001e5140..1f0739f28 100644 --- a/src/liboslexec/runtimeoptimize.cpp +++ b/src/liboslexec/runtimeoptimize.cpp @@ -234,8 +234,8 @@ RuntimeOptimizer::add_constant (const TypeSpec &type, const void *data, if (type.is_unsized_array()) newtype.make_array (datatype.numelements()); - Symbol newconst (ustring::sprintf ("$newconst%d", m_next_newconst++), - newtype, SymTypeConst); + Symbol newconst(ustring::fmtformat("$newconst{}", m_next_newconst++), + newtype, SymTypeConst); void *newdata = nullptr; TypeDesc t (newtype.simpletype()); size_t n = t.aggregate * t.numelements(); @@ -289,8 +289,8 @@ RuntimeOptimizer::add_constant (const TypeSpec &type, const void *data, int RuntimeOptimizer::add_temp (const TypeSpec &type) { - return add_symbol (Symbol (ustring::sprintf ("$opttemp%d", m_next_newtemp++), - type, SymTypeTemp)); + return add_symbol(Symbol(ustring::fmtformat("$opttemp{}", m_next_newtemp++), + type, SymTypeTemp)); } @@ -339,9 +339,9 @@ RuntimeOptimizer::debug_opt_ops (int opbegin, int opend, string_view message) co const Opcode &op (inst()->ops()[opbegin]); std::string oprange; if (opbegin >= 0 && opend-opbegin > 1) - oprange = Strutil::sprintf ("ops %d-%d ", opbegin, opend); + oprange = fmtformat("ops {}-{} ", opbegin, opend); else if (opbegin >= 0) - oprange = Strutil::sprintf ("op %d ", opbegin); + oprange = fmtformat("op {} ", opbegin); debug_optfmt(" {}{} (@ {}:{})\n", oprange, message, op.sourcefile(), op.sourceline()); } @@ -357,18 +357,18 @@ RuntimeOptimizer::debug_turn_into (const Opcode &op, int numops, int opnum = &op - &(inst()->ops()[0]); std::string msg; if (numops == 1) - msg = Strutil::fmt::format("turned '{}' to '{}", op_string(op), newop); + msg = fmtformat("turned '{}' to '{}", op_string(op), newop); else - msg = Strutil::fmt::format("turned to '{}", newop); + msg = fmtformat("turned to '{}", newop); if (newarg0 >= 0) - msg += Strutil::fmt::format(" {}", inst()->symbol(newarg0)->name()); + msg += fmtformat(" {}", inst()->symbol(newarg0)->name()); if (newarg1 >= 0) - msg += Strutil::fmt::format(" {}", inst()->symbol(newarg1)->name()); + msg += fmtformat(" {}", inst()->symbol(newarg1)->name()); if (newarg2 >= 0) - msg += Strutil::fmt::format(" {}", inst()->symbol(newarg2)->name()); + msg += fmtformat(" {}", inst()->symbol(newarg2)->name()); msg += "'"; if (why.size()) - msg += Strutil::fmt::format(" : {}", why); + msg += fmtformat(" : {}", why); debug_opt_ops (opnum, opnum+numops, msg); } @@ -1215,7 +1215,7 @@ RuntimeOptimizer::simple_sym_assign (int sym, int opnum) Opcode &uselessop (inst()->ops()[i->second]); if (uselessop.opname() != u_nop && uselessop.opname() != u_functioncall_nr) turn_into_nop (uselessop, - debug() > 1 ? Strutil::fmt::format("remove stale value assignment to {}, reassigned on op {}", + debug() > 1 ? fmtformat("remove stale value assignment to {}, reassigned on op {}", opargsym(uselessop,0)->name(), opnum).c_str() : ""); } } @@ -1408,9 +1408,9 @@ RuntimeOptimizer::outparam_assign_elision (int opnum, Opcode &op) // replace its default value entirely and get rid of the assignment. if (R->firstread() > opnum && ! R->renderer_output() && m_opt_elide_unconnected_outputs) { - make_param_use_instanceval (R, Strutil::fmt::format("- written once, with a constant ({}), before any reads", const_value_as_string(*A))); + make_param_use_instanceval (R, fmtformat("- written once, with a constant ({}), before any reads", const_value_as_string(*A))); replace_param_value (R, A->data(), A->typespec()); - turn_into_nop (op, debug() > 1 ? Strutil::fmt::format("oparam {} never subsequently read or connected", R->name()).c_str() : ""); + turn_into_nop (op, debug() > 1 ? fmtformat("oparam {} never subsequently read or connected", R->name()).c_str() : ""); return true; } } @@ -1420,7 +1420,7 @@ RuntimeOptimizer::outparam_assign_elision (int opnum, Opcode &op) // assignment at all. Note that unread_after() does take into // consideration whether it's a renderer output. if (unread_after(R,opnum)) { - turn_into_nop (op, debug() > 1 ? Strutil::fmt::format("oparam {} never subsequently read or connected", R->name()).c_str() : ""); + turn_into_nop (op, debug() > 1 ? fmtformat("oparam {} never subsequently read or connected", R->name()).c_str() : ""); return true; } @@ -1696,9 +1696,9 @@ RuntimeOptimizer::peephole2 (int opnum, int op2num) (a->symtype() != SymTypeGlobal && a->symtype() != SymTypeOutputParam) && equivalent (a->typespec(), c->typespec())) { if (debug() > 1) - debug_opt_ops (opnum, opnum+1, - Strutil::sprintf ("turned '%s %s...' to '%s %s...' as part of daisy-chain", - op.opname(), a->name(), op.opname(), c->name())); + debug_opt_ops(opnum, opnum+1, + fmtformat("turned '{} {}...' to '{} {}...' as part of daisy-chain", + op.opname(), a->name(), op.opname(), c->name())); inst()->args()[op.firstarg()] = inst()->args()[next.firstarg()]; c->mark_rw (opnum, false, true); // Any time we write to a variable that wasn't written to at @@ -1805,7 +1805,7 @@ RuntimeOptimizer::remove_unused_params () if (param_never_used(s) && s.has_init_ops()) { std::string why; if (debug() > 1) - why = Strutil::fmt::format("remove init ops of unused param {} {}", s.typespec(), s.name()); + why = fmtformat("remove init ops of unused param {} {}", s.typespec(), s.name()); turn_into_nop (s.initbegin(), s.initend(), why); s.set_initrange (0, 0); s.clear_rw(); // mark as totally unused @@ -2363,7 +2363,7 @@ RuntimeOptimizer::optimize_instance () // Not needed. Remove all its connections and ops. inst()->connections().clear (); turn_into_nop (0, (int)inst()->ops().size()-1, - debug() > 1 ? Strutil::fmt::format("eliminate layer {} with no outward connections", inst()->layername()).c_str() : ""); + debug() > 1 ? fmtformat("eliminate layer {} with no outward connections", inst()->layername()).c_str() : ""); for (auto&& s : inst()->symbols()) s.clear_rw (); } @@ -2984,7 +2984,7 @@ RuntimeOptimizer::printinst (std::ostream &out) const if (op.jump(j) >= 0) out << " " << op.jump(j); out << "\t# "; -// out << " rw " << Strutil::fmt::format("{:x}", op.argread_bits()) +// out << " rw " << fmtformat("{:x}", op.argread_bits()) // << ' ' << op.argwrite_bits(); if (op.argtakesderivs_all()) out << " %derivs(" << op.argtakesderivs_all() << ") "; diff --git a/src/liboslexec/shadingsys.cpp b/src/liboslexec/shadingsys.cpp index 1036033e9..a9beaf65f 100644 --- a/src/liboslexec/shadingsys.cpp +++ b/src/liboslexec/shadingsys.cpp @@ -1796,9 +1796,9 @@ ShadingSystemImpl::getattribute (string_view name, TypeDesc type, return true; } if (name == "osl:dependencies" && type == TypeDesc::STRING) { - std::string deps = OIIO::Strutil::sprintf("LLVM-%s,OpenImageIO-%s,Imath-%s", - OSL_LLVM_FULL_VERSION, OIIO_VERSION_STRING, - OPENEXR_VERSION_STRING); + std::string deps = fmtformat("LLVM-{},OpenImageIO-{},Imath-{}", + OSL_LLVM_FULL_VERSION, OIIO_VERSION_STRING, + OPENEXR_VERSION_STRING); if (!strcmp(OSL_CUDA_VERSION, "")) deps += ",Cuda-NONE"; else @@ -1905,16 +1905,18 @@ ShadingSystemImpl::getattribute (ShaderGroup *group, string_view name, return true; } if (name == "group_init_name" && type.basetype == TypeDesc::STRING) { - *(ustring *)val = ustring::sprintf ("__direct_callable__group_%s_%d_init", - group->name(), group->id()); + *(ustring*)val + = ustring::fmtformat("__direct_callable__group_{}_{}_init", + group->name(), group->id()); return true; } if (name == "group_entry_name" && type.basetype == TypeDesc::STRING) { int nlayers = group->nlayers (); ShaderInstance *inst = (*group)[nlayers-1]; // This formulation mirrors OSOProcessorBase::layer_function_name() - *(ustring *)val = ustring::sprintf ("__direct_callable__%s_%s_%d", group->name(), - inst->layername(), inst->id()); + *(ustring*)val = ustring::fmtformat("__direct_callable__{}_{}_{}", + group->name(), inst->layername(), + inst->id()); return true; } if (name == "layer_osofiles" && type.basetype == TypeDesc::STRING) { @@ -3258,7 +3260,7 @@ bool ShadingSystemImpl::is_renderer_output (ustring layername, ustring paramname, ShaderGroup *group) const { - ustring name2 = ustring::sprintf("%s.%s", layername, paramname); + ustring name2 = ustring::fmtformat("{}.{}", layername, paramname); if (group) { for (auto&& sl : group->m_symlocs) { if (sl.arena == SymArena::Outputs && @@ -4156,10 +4158,10 @@ osl_naninf_check (int ncomps, const void *vals_, int has_derivs, for (int c = firstcheck, e = c+nchecks; c < e; ++c) { int i = d*ncomps + c; if (! OIIO::isfinite(vals[i])) { - ctx->errorf("Detected %g value in %s%s at %s:%d (op %s)", - vals[i], d > 0 ? "the derivatives of " : "", - USTR(symbolname), USTR(sourcefile), sourceline, - USTR(opname)); + ctx->errorfmt("Detected {} value in {}{} at {}:{} (op {})", + vals[i], d > 0 ? "the derivatives of " : "", + USTR(symbolname), USTR(sourcefile), sourceline, + USTR(opname)); return; } } @@ -4213,11 +4215,12 @@ osl_uninit_check (long long typedesc_, void *vals_, } } if (uninit) { - ctx->errorf("Detected possible use of uninitialized value in %s %s at %s:%d (group %s, layer %d %s, shader %s, op %d '%s', arg %d)", - typedesc.c_str(), USTR(symbolname), USTR(sourcefile), sourceline, - (groupname && groupname[0]) ? groupname: "", - layer, (layername && layername[0]) ? layername : "", - shadername, opnum, USTR(opname), argnum); + ctx->errorfmt( + "Detected possible use of uninitialized value in {} {} at {}:{} (group {}, layer {} {}, shader {}, op {} '{}', arg {})", + typedesc.c_str(), USTR(symbolname), USTR(sourcefile), sourceline, + (groupname && groupname[0]) ? groupname : "", layer, + (layername && layername[0]) ? layername : "", + shadername, opnum, USTR(opname), argnum); } } @@ -4231,13 +4234,12 @@ osl_range_check_err (int indexvalue, int length, const char *symname, { if (indexvalue < 0 || indexvalue >= length) { ShadingContext *ctx = (ShadingContext *)((ShaderGlobals *)sg)->context; - ctx->errorf("Index [%d] out of range %s[0..%d]: %s:%d" - " (group %s, layer %d %s, shader %s)", - indexvalue, USTR(symname), length-1, - USTR(sourcefile), sourceline, - (groupname && groupname[0]) ? groupname : "", layer, - (layername && layername[0]) ? layername : "", - USTR(shadername)); + ctx->errorfmt( + "Index [{}] out of range {}[0..{}]: {}:{} (group {}, layer {} {}, shader {})", + indexvalue, USTR(symname), length - 1, USTR(sourcefile), sourceline, + (groupname && groupname[0]) ? groupname : "", layer, + (layername && layername[0]) ? layername : "", + USTR(shadername)); if (indexvalue >= length) indexvalue = length-1; else diff --git a/src/liboslexec/wide/wide_opmatrix.cpp b/src/liboslexec/wide/wide_opmatrix.cpp index 3d580e2f9..5ebd614ba 100644 --- a/src/liboslexec/wide/wide_opmatrix.cpp +++ b/src/liboslexec/wide/wide_opmatrix.cpp @@ -535,7 +535,7 @@ impl_get_uniform_from_matrix_masked(void* bsg_, Masked wrm, makeIdentity(failedResults); ShadingContext* ctx = bsg->uniform.context; if (ctx->shadingsys().unknown_coordsys_error()) { - ctx->errorf("Unknown transformation \"%s\"", from); + ctx->errorfmt("Unknown transformation \"{}\"", from); } } return succeeded; @@ -579,7 +579,7 @@ impl_get_uniform_to_inverse_matrix_masked(void* bsg_, Masked wrm, if (failedResults.mask().any_on()) { makeIdentity(failedResults); if (ctx->shadingsys().unknown_coordsys_error()) { - ctx->errorf("Unknown transformation \"%s\"", to); + ctx->errorfmt("Unknown transformation \"{}\"", to); } } return succeeded; @@ -673,8 +673,8 @@ impl_get_varying_from_matrix_batched(BatchedShaderGlobals* bsg, for (int lane = 0; lane < __OSL_WIDTH; ++lane) { if (failedLanes[lane]) { ustring from = wFrom[lane]; - ctx->batched<__OSL_WIDTH>().errorf( - Mask(Lane(lane)), "Unknown transformation \"%s\"", + ctx->batched<__OSL_WIDTH>().errorfmt( + Mask(Lane(lane)), "Unknown transformation \"{}\"", from); } } @@ -790,8 +790,8 @@ impl_get_varying_to_matrix_masked(BatchedShaderGlobals* bsg, for (int lane = 0; lane < __OSL_WIDTH; ++lane) { if (failedLanes[lane]) { ustring to = wTo[lane]; - ctx->batched<__OSL_WIDTH>().errorf( - Mask(Lane(lane)), "Unknown transformation \"%s\"", + ctx->batched<__OSL_WIDTH>().errorfmt( + Mask(Lane(lane)), "Unknown transformation \"{}\"", to); } } diff --git a/src/liboslexec/wide/wide_opmessage.cpp b/src/liboslexec/wide/wide_opmessage.cpp index c73a0562a..8ed87446b 100644 --- a/src/liboslexec/wide/wide_opmessage.cpp +++ b/src/liboslexec/wide/wide_opmessage.cpp @@ -161,12 +161,12 @@ impl_setmessage(BatchedShaderGlobals* bsg, ustring sourcefile, int sourceline, ustring msg_sourcefile = msg_wsourcefile[lane]; int msg_sourceline = msg_wsourceline[lane]; - bsg->uniform.context->batched<__OSL_WIDTH>().errorf( + bsg->uniform.context->batched<__OSL_WIDTH>().errorfmt( lanes_with_data, - "message \"%s\" already exists (created here: %s:%d)" - " cannot set again from %s:%d", - name.c_str(), msg_sourcefile.c_str(), msg_sourceline, - sourcefile.c_str(), sourceline); + "message \"{}\" already exists (created here: {}:{})" + " cannot set again from {}:{}", + name, msg_sourcefile, msg_sourceline, sourcefile, + sourceline); }); auto lanes_to_populate = (~m->valid_mask & matching_lanes) & ~m->get_before_set_mask; @@ -180,12 +180,11 @@ impl_setmessage(BatchedShaderGlobals* bsg, ustring sourcefile, int sourceline, lanes_that_getmessage_called_on.foreach ([=](ActiveLane lane) -> void { ustring msg_sourcefile = msg_wsourcefile[lane]; int msg_sourceline = msg_wsourceline[lane]; - bsg->uniform.context->batched<__OSL_WIDTH>().errorf( + bsg->uniform.context->batched<__OSL_WIDTH>().errorfmt( Mask(Lane(lane)), - "message \"%s\" was queried before being set (queried here: %s:%d)" - " setting it now (%s:%d) would lead to inconsistent results", - name.c_str(), msg_sourcefile.c_str(), msg_sourceline, - sourcefile.c_str(), sourceline); + "message \"{}\" was queried before being set (queried here: {}:{})" + " setting it now ({}:{}) would lead to inconsistent results", + name, msg_sourcefile, msg_sourceline, sourcefile, sourceline); }); } else { // The message didn't exist - create it @@ -324,16 +323,16 @@ OSL_BATCHOP void __OSL_MASKED_OP(getmessage)( // found message, but was set by a layer deeper than the one querying the message bool has_data = m->has_data() ? m->valid_mask[lane] : false; - bsg->uniform.context->batched<__OSL_WIDTH>().errorf( + bsg->uniform.context->batched<__OSL_WIDTH>().errorfmt( Mask(lane), - "type mismatch for message \"%s\" (%s as %s here: %s:%d)" - " cannot fetch as %s from %s:%d", + "type mismatch for message \"{}\" ({} as {} here: {}:{})" + " cannot fetch as {} from {}:{}", name.c_str(), has_data ? "created" : "queried", m->type == TypeDesc::PTR ? "closure color" : m->type.c_str(), - msg_sourcefile.c_str(), msg_sourceline, - is_closure ? "closure color" : type.c_str(), - sourcefile.c_str(), sourceline); + msg_sourcefile, msg_sourceline, + is_closure ? "closure color" : type.c_str(), sourcefile, + sourceline); }); assign_all(wR, 0); @@ -364,14 +363,14 @@ OSL_BATCHOP void __OSL_MASKED_OP(getmessage)( int msg_sourceline = msg_wsourceline[lane]; // found message, but was set by a layer deeper than the one querying the message - bsg->uniform.context->batched<__OSL_WIDTH>().errorf( + bsg->uniform.context->batched<__OSL_WIDTH>().errorfmt( Mask(lane), - "message \"%s\" was set by layer #%d (%s:%d)" - " but is being queried by layer #%d (%s:%d)" + "message \"{}\" was set by layer #{} ({}:{})" + " but is being queried by layer #{} ({}:{})" " - messages may only be transfered from nodes " "that appear earlier in the shading network", - name.c_str(), msg_layerid, msg_sourcefile.c_str(), - msg_sourceline, layeridx, sourcefile.c_str(), sourceline); + name, msg_layerid, msg_sourcefile, msg_sourceline, layeridx, + sourcefile, sourceline); wR[lane] = 0; }); diff --git a/src/liboslexec/wide/wide_opnoise_generic_impl.cpp b/src/liboslexec/wide/wide_opnoise_generic_impl.cpp index 2c3c27f29..2f5679ada 100644 --- a/src/liboslexec/wide/wide_opnoise_generic_impl.cpp +++ b/src/liboslexec/wide/wide_opnoise_generic_impl.cpp @@ -144,8 +144,8 @@ zero_derivs(Masked> wr) zero_derivs(wr); \ } else { \ ((BatchedShaderGlobals*)bsg) \ - ->uniform.context->errorf("Unknown noise type \"%s\"", \ - name.c_str()); \ + ->uniform.context->errorfmt("Unknown noise type \"{}\"", \ + name); \ } \ } @@ -232,8 +232,8 @@ __OSL_GENERIC_DISPATCH2(Wdf, Wdf, Wf, Wf, Dual2) zero_derivs(wr); \ } else { \ ((BatchedShaderGlobals*)bsg) \ - ->uniform.context->errorf("Unknown noise type \"%s\"", \ - name.c_str()); \ + ->uniform.context->errorfmt("Unknown noise type \"{}\"", \ + name); \ } \ } diff --git a/src/liboslexec/wide/wide_opnoise_periodic_generic_impl.cpp b/src/liboslexec/wide/wide_opnoise_periodic_generic_impl.cpp index 22a9632ff..8d0357640 100644 --- a/src/liboslexec/wide/wide_opnoise_periodic_generic_impl.cpp +++ b/src/liboslexec/wide/wide_opnoise_periodic_generic_impl.cpp @@ -86,8 +86,8 @@ OSL_USING_DATA_WIDTH(__OSL_WIDTH) } \ } else { \ ((BatchedShaderGlobals*)bsg) \ - ->uniform.context->errorf("Unknown noise type \"%s\"", \ - name.c_str()); \ + ->uniform.context->errorfmt("Unknown noise type \"{}\"", \ + name); \ } \ } @@ -166,8 +166,8 @@ OSL_USING_DATA_WIDTH(__OSL_WIDTH) } \ } else { \ ((BatchedShaderGlobals*)bsg) \ - ->uniform.context->errorf("Unknown noise type \"%s\"", \ - name.c_str()); \ + ->uniform.context->errorfmt("Unknown noise type \"{}\"", \ + name); \ } \ } diff --git a/src/liboslexec/wide/wide_oppointcloud.cpp b/src/liboslexec/wide/wide_oppointcloud.cpp index 5ec41adac..2e00bd173 100644 --- a/src/liboslexec/wide/wide_oppointcloud.cpp +++ b/src/liboslexec/wide/wide_oppointcloud.cpp @@ -49,14 +49,18 @@ default_pointcloud_search(BatchedShaderGlobals* bsg, } PointCloud *pc = PointCloud::get(filename); if (pc == NULL) { // The file failed to load - ctx->batched<__OSL_WIDTH>().errorf(results.mask(), "pointcloud_search: could not open \"%s\"", filename); + ctx->batched<__OSL_WIDTH>().errorfmt( + results.mask(), "pointcloud_search: could not open \"{}\"", + filename); assign_all(results.wnum_points(), 0); return; } const Partio::ParticlesData *cloud = pc->read_access(); if (cloud == NULL) { // The file failed to load - ctx->batched<__OSL_WIDTH>().errorf(results.mask(), "pointcloud_search: could not open \"%s\"", filename); + ctx->batched<__OSL_WIDTH>().errorfmt( + results.mask(), "pointcloud_search: could not open \"{}\"", + filename); assign_all(results.wnum_points(), 0); return; } @@ -260,33 +264,44 @@ default_pointcloud_get(BatchedShaderGlobals* bsg, } if (pc == nullptr) { // The file failed to load - ctx->batched<__OSL_WIDTH>().errorf(Mask{lane}, "pointcloud_get: could not open \"%s\"", filename); + ctx->batched<__OSL_WIDTH>().errorfmt( + Mask { lane }, "pointcloud_get: could not open \"{}\"", + filename); return; } if (cloud == nullptr) { // The file failed to load - ctx->batched<__OSL_WIDTH>().errorf(Mask{lane}, "pointcloud_get: could not open \"%s\"", filename); + ctx->batched<__OSL_WIDTH>().errorfmt( + Mask { lane }, "pointcloud_get: could not open \"{}\"", + filename); return; } // lookup the ParticleAttribute pointer needed for a query if (attr == nullptr) { - ctx->batched<__OSL_WIDTH>().errorf(Mask{lane}, "Accessing unexisting attribute %s in pointcloud \"%s\"", attr_name, filename); + ctx->batched<__OSL_WIDTH>().errorfmt( + Mask { lane }, + "Accessing unexisting attribute {} in pointcloud \"{}\"", + attr_name, filename); return; } // Finally check for some equivalent types like float3 and vector if (!is_compatible_with_partio) { - ctx->batched<__OSL_WIDTH>().errorf(Mask{lane}, "Type of attribute \"%s\" : %s not compatible with OSL's %s in \"%s\" pointcloud", - attr_name, partio_type, element_type, filename); + ctx->batched<__OSL_WIDTH>().errorfmt( + Mask { lane }, + "Type of attribute \"{}\" : {} not compatible with OSL's {} in \"{}\" pointcloud", + attr_name, partio_type, element_type, filename); return; } // For safety, clamp the count to the most that will fit in the output if (maxn < count) { - ctx->batched<__OSL_WIDTH>().errorf(Mask{lane}, "Point cloud attribute \"%s\" : %s with retrieval count %d will not fit in %s", - attr_name, partio_type, count, attr_type); + ctx->batched<__OSL_WIDTH>().errorfmt( + Mask { lane }, + "Point cloud attribute \"{}\" : {} with retrieval count {} will not fit in {}", + attr_name, partio_type, count, attr_type); count = maxn; } // Copy int indices out of SOA wide format into local AOS size_t diff --git a/src/liboslexec/wide/wide_optexture.cpp b/src/liboslexec/wide/wide_optexture.cpp index 3cd40b921..561d11b9f 100644 --- a/src/liboslexec/wide/wide_optexture.cpp +++ b/src/liboslexec/wide/wide_optexture.cpp @@ -187,8 +187,8 @@ default_texture(BatchedRendererServices* bsr, ustring filename, errormessage[lane] = Strings::unknown; } } else if (errMsgSize) { - context->batched<__OSL_WIDTH>().errorf( - Mask(Lane(lane)), "[RendererServices::texture] %s", err); + context->batched<__OSL_WIDTH>().errorfmt( + Mask(Lane(lane)), "[RendererServices::texture] {}", err); } } }); @@ -382,8 +382,8 @@ default_texture3d(BatchedRendererServices* bsr, ustring filename, errormessage[lane] = Strings::unknown; } } else if (errMsgSize) { - context->batched<__OSL_WIDTH>().errorf( - Mask(Lane(lane)), "[RendererServices::texture3d] %s", err); + context->batched<__OSL_WIDTH>().errorfmt( + Mask(Lane(lane)), "[RendererServices::texture3d] {}", err); } } }); @@ -527,8 +527,8 @@ default_environment(BatchedRendererServices* bsr, ustring filename, errormessage[lane] = Strings::unknown; } } else if (errMsgSize) { - context->batched<__OSL_WIDTH>().errorf( - Mask(Lane(lane)), "[RendererServices::environment] %s", err); + context->batched<__OSL_WIDTH>().errorfmt( + Mask(Lane(lane)), "[RendererServices::environment] {}", err); } } }); diff --git a/src/liboslexec/wide/wide_shadingsys.cpp b/src/liboslexec/wide/wide_shadingsys.cpp index 03a3e8265..981bbd6da 100644 --- a/src/liboslexec/wide/wide_shadingsys.cpp +++ b/src/liboslexec/wide/wide_shadingsys.cpp @@ -40,10 +40,10 @@ OSL_BATCHOP void __OSL_OP(naninf_check)(int ncomps, const void* vals_, for (int c = firstcheck, e = c + nchecks; c < e; ++c) { int i = d * ncomps + c; if (!OIIO::isfinite(vals[i])) { - ctx->errorf("Detected %g value in %s%s at %s:%d (op %s)", - vals[i], d > 0 ? "the derivatives of " : "", - USTR(symbolname), USTR(sourcefile), sourceline, - USTR(opname)); + ctx->errorfmt("Detected {} value in {}{} at {}:{} (op {})", + vals[i], d > 0 ? "the derivatives of " : "", + USTR(symbolname), USTR(sourcefile), sourceline, + USTR(opname)); return; } } @@ -65,8 +65,8 @@ OSL_BATCHOP void __OSL_MASKED_OP1(naninf_check_offset, i)( int i = d * ncomps + c; mask.foreach ([=](ActiveLane lane) -> void { if (!OIIO::isfinite(vals[i * __OSL_WIDTH + lane])) { - ctx->errorf( - "Detected %g value in %s%s at %s:%d (op %s) batch lane:%d", + ctx->errorfmt( + "Detected {} value in {}{} at {}:{} (op {}) batch lane:{}", vals[i * __OSL_WIDTH + lane], d > 0 ? "the derivatives of " : "", USTR(symbolname), USTR(sourcefile), sourceline, USTR(opname), lane); @@ -98,8 +98,8 @@ OSL_BATCHOP void __OSL_MASKED_OP1(naninf_check_offset, Wi)( for (int c = firstcheck, e = c + nchecks; c < e; ++c) { int i = d * ncomps + c; if (!OIIO::isfinite(vals[i * __OSL_WIDTH + lane])) { - ctx->errorf( - "Detected %g value in %s%s at %s:%d (op %s) batch lane:%d", + ctx->errorfmt( + "Detected {} value in {}{} at {}:{} (op {}) batch lane:{}", vals[i * __OSL_WIDTH + lane], d > 0 ? "the derivatives of " : "", USTR(symbolname), USTR(sourcefile), sourceline, USTR(opname), lane); @@ -152,8 +152,8 @@ OSL_BATCHOP void __OSL_OP2(uninit_check_values_offset, X, } } if (uninit) { - ctx->errorf( - "Detected possible use of uninitialized value in %s %s at %s:%d (group %s, layer %d %s, shader %s, op %d '%s', arg %d)", + ctx->errorfmt( + "Detected possible use of uninitialized value in {} {} at {}:{} (group {}, layer {} {}, shader {}, op {} '{}', arg {})", typedesc, USTR(symbolname), USTR(sourcefile), sourceline, (groupname && groupname[0]) ? groupname : "", layer, (layername && layername[0]) ? layername : "", @@ -210,8 +210,8 @@ OSL_BATCHOP void __OSL_MASKED_OP2(uninit_check_values_offset, WX, i)( }); } if (lanes_uninit.any_on()) { - ctx->errorf( - "Detected possible use of uninitialized value in %s %s at %s:%d (group %s, layer %d %s, shader %s, op %d '%s', arg %d) for lanes(%x) of batch", + ctx->errorfmt( + "Detected possible use of uninitialized value in {} {} at {}:{} (group {}, layer {} {}, shader {}, op {} '{}', arg {}) for lanes({:x}) of batch", typedesc, USTR(symbolname), USTR(sourcefile), sourceline, (groupname && groupname[0]) ? groupname : "", layer, (layername && layername[0]) ? layername : "", @@ -270,8 +270,8 @@ OSL_BATCHOP void __OSL_MASKED_OP2(uninit_check_values_offset, X, Wi)( } if (lanes_uninit.any_on()) { - ctx->errorf( - "Detected possible use of uninitialized value in %s %s at %s:%d (group %s, layer %d %s, shader %s, op %d '%s', arg %d) for lanes(%x) of batch", + ctx->errorfmt( + "Detected possible use of uninitialized value in {} {} at {}:{} (group {}, layer {} {}, shader {}, op {} '{}', arg {}) for lanes({:x}) of batch", typedesc, USTR(symbolname), USTR(sourcefile), sourceline, (groupname && groupname[0]) ? groupname : "", layer, (layername && layername[0]) ? layername : "", @@ -332,8 +332,8 @@ OSL_BATCHOP void __OSL_MASKED_OP2(uninit_check_values_offset, WX, Wi)( } if (lanes_uninit.any_on()) { - ctx->errorf( - "Detected possible use of uninitialized value in %s %s at %s:%d (group %s, layer %d %s, shader %s, op %d '%s', arg %d) for lanes(%x) of batch", + ctx->errorfmt( + "Detected possible use of uninitialized value in {} {} at {}:{} (group {}, layer {} {}, shader {}, op {} '{}', arg {}) for lanes({:x}) of batch", typedesc, USTR(symbolname), USTR(sourcefile), sourceline, (groupname && groupname[0]) ? groupname : "", layer, (layername && layername[0]) ? layername : "", @@ -351,8 +351,8 @@ OSL_BATCHOP int __OSL_OP(range_check)(int indexvalue, int length, if (indexvalue < 0 || indexvalue >= length) { auto* bsg = reinterpret_cast(bsg_); ShadingContext* ctx = bsg->uniform.context; - ctx->errorf("Index [%d] out of range %s[0..%d]: %s:%d" - " (group %s, layer %d %s, shader %s)", + ctx->errorfmt("Index [{}] out of range {}[0..{}]: {}:{}" + " (group {}, layer {} {}, shader {})", indexvalue, USTR(symname), length - 1, USTR(sourcefile), sourceline, (groupname && groupname[0]) ? groupname : "", @@ -380,16 +380,14 @@ OSL_BATCHOP void int indexvalue = wIndexValue[lane]; if (indexvalue < 0 || indexvalue >= length) { ShadingContext* ctx = bsg->uniform.context; - ctx->errorf("Index [%d] out of range %s[0..%d]: %s:%d" - " (group %s, layer %d %s, shader %s)", - indexvalue, USTR(symname), length - 1, USTR(sourcefile), - sourceline, - (groupname && groupname[0]) ? groupname - : "", - layer, - (layername && layername[0]) ? layername - : "", - USTR(shadername)); + ctx->errorfmt( + "Index [{}] out of range {}[0..{}]: {}:{} (group {}, layer {} {}, shader {})", + indexvalue, USTR(symname), length - 1, USTR(sourcefile), + sourceline, + (groupname && groupname[0]) ? groupname : "", + layer, + (layername && layername[0]) ? layername : "", + USTR(shadername)); if (indexvalue >= length) indexvalue = length - 1; else @@ -528,8 +526,8 @@ OSL_BATCHOP int __OSL_OP(bind_interpolated_param)( Mask foundUserData = bsg->uniform.renderer->batched(WidthTag()) ->get_userdata(USTR(name), bsg, userDest); - // printf ("Binding %s %s : index %d, ok = %d\n", name, - // TYPEDESC(type).c_str(),userdata_index, foundUserData.value()); + // print("Binding {} {} : index {}, ok = {}\n", name, + // TYPEDESC(type).c_str(),userdata_index, foundUserData.value()); *userdata_initialized = (1 << 31) | foundUserData.value(); bsg->uniform.context->incr_get_userdata_calls(); diff --git a/src/liboslnoise/oslnoise_test.cpp b/src/liboslnoise/oslnoise_test.cpp index bf0c8c999..4b500bbe4 100644 --- a/src/liboslnoise/oslnoise_test.cpp +++ b/src/liboslnoise/oslnoise_test.cpp @@ -73,7 +73,7 @@ inline float abs (const Vec3& a) { img.setpixel (x, y, r_comp); \ } \ } \ - img.write (Strutil::sprintf ("osl_%s_%d_%d.tif", #noisename, outdim, indim)); \ + img.write (Strutil::fmt::format("osl_{}_{}_{}.tif", #noisename, outdim, indim)); \ } \ } @@ -367,7 +367,7 @@ getargs (int argc, const char *argv[]) "-v", &verbose, "Verbose mode", "--img", &make_images, "Make test images", "--iterations %d", &iterations, - ustring::sprintf("Number of iterations (default: %d)", iterations).c_str(), + ustring::fmtformat("Number of iterations (default: {})", iterations).c_str(), "--trials %d", &ntrials, "Number of trials", NULL); if (ap.parse (argc, (const char**)argv) < 0) { diff --git a/src/osltoy/osltoyapp.cpp b/src/osltoy/osltoyapp.cpp index 8131a7c75..2ae5e63e8 100644 --- a/src/osltoy/osltoyapp.cpp +++ b/src/osltoy/osltoyapp.cpp @@ -587,7 +587,7 @@ void OSLToyMainWindow::update_statusbar_fps(float time, float fps) { statusFPS->setText( - OIIO::Strutil::sprintf(" %.2f FPS: %5.1f", time, fps).c_str()); + fmtformat(" {:.2f} FPS: {:5.1f}", time, fps).c_str()); } @@ -637,7 +637,7 @@ OSLToyMainWindow::add_new_editor_window(const std::string& filename) textTabs->addTab(editor_and_error_display, texteditor->brief_filename().c_str()); } else { - std::string title = OIIO::Strutil::sprintf("untitled %d", n + 1); + std::string title = OSL::fmtformat("untitled {}", n + 1); textTabs->addTab(editor_and_error_display, title.c_str()); } textTabs->setCurrentIndex(n); @@ -736,8 +736,7 @@ OSLToyMainWindow::action_save() if (out) out << text; if (out.fail()) { - std::string msg = OIIO::Strutil::sprintf("Could not write %s", - filename); + std::string msg = OSL::fmtformat("Could not write {}", filename); QErrorMessage err(nullptr); err.showMessage(msg.c_str()); err.exec(); @@ -996,16 +995,15 @@ OSLToyMainWindow::make_param_adjustment_row(ParamRec* param, std::string typetext(param->type.c_str()); if (param->isclosure) - typetext = OIIO::Strutil::sprintf("closure %s", typetext); + typetext = OSL::fmtformat("closure {}", typetext); if (param->isstruct) - typetext = OIIO::Strutil::sprintf("struct %s", param->structname); + typetext = OSL::fmtformat("struct {}", param->structname); if (param->isoutput) - typetext = OIIO::Strutil::sprintf("output %s", typetext); - // auto typeLabel = QtUtils::make_qlabelf ("%s", typetext); + typetext = OSL::fmtformat("output {}", typetext); + // auto typeLabel = QtUtils::mtmt{}{}", typetext); // layout->addWidget (typeLabel, row, 1); auto nameLabel = new QLabel( - OIIO::Strutil::sprintf("%s  %s", typetext, - param->name) + OSL::fmtformat("{}  {}", typetext, param->name) .c_str()); nameLabel->setTextFormat(Qt::RichText); layout->addWidget(nameLabel, row, 1); @@ -1044,7 +1042,7 @@ OSLToyMainWindow::make_param_adjustment_row(ParamRec* param, labeltext = string_view(&("RGB"[c]), 1); else labeltext = string_view(&("xyz"[c]), 1); - auto channellabel = QtUtils::make_qlabelf("%s", labeltext); + auto channellabel = QtUtils::make_qlabelfmt("{}", labeltext); label_and_adjust_layout->addWidget(channellabel); auto adjustWidget = new QtUtils::DoubleSpinBox(param->fdefault[c]); if (param->type == TypeDesc::TypeColor) { @@ -1188,9 +1186,8 @@ OSLToyMainWindow::rebuild_param_area() TypeDesc(TypeDesc::STRING, nlayers), &layernames[0]); for (int i = 0; i < nlayers; ++i) { OSLQuery oslquery = ss->oslquery(*group, i); - std::string desc = OIIO::Strutil::sprintf("layer %d %s (%s)", i, - layernames[i], - oslquery.shadername()); + std::string desc = OSL::fmtformat("layer {} {} ({})", i, layernames[i], + oslquery.shadername()); paramLayout->addWidget(new QLabel(desc.c_str()), paramrow++, 0, 1, 2); for (auto&& p : m_shaderparams) { make_param_adjustment_row(p.get(), paramLayout, paramrow++); diff --git a/src/osltoy/qtutils.h b/src/osltoy/qtutils.h index d760231ef..a611aa339 100644 --- a/src/osltoy/qtutils.h +++ b/src/osltoy/qtutils.h @@ -66,15 +66,15 @@ clear_layout(QLayout* lay) -// Create a label whose text is given by printf-style arguments (type safe). -// The label will be "autotext" which means it will auto-detect RTF and +// Create a label whose text is given by std::format-style arguments (type +// safe). The label will be "autotext" which means it will auto-detect RTF and // render a subset of HTML formatting. For example, "blah" will // render the 'blah' in italics. template inline QLabel* -make_qlabelf(const char* fmt, const Args&... args) +make_qlabelfmt(const char* fmt, const Args&... args) { - std::string text = OIIO::Strutil::sprintf(fmt, args...); + std::string text = OIIO::Strutil::fmt::format(fmt, args...); auto label = new QLabel(text.c_str()); label->setTextFormat(Qt::AutoText); return label; diff --git a/src/testrender/optixraytracer.cpp b/src/testrender/optixraytracer.cpp index 88b50ae99..becf1d9cb 100644 --- a/src/testrender/optixraytracer.cpp +++ b/src/testrender/optixraytracer.cpp @@ -463,11 +463,8 @@ OptixRaytracer::make_optix_materials () } if (options.get_int("saveptx")) { - std::string filename = OIIO::Strutil::sprintf("%s_%d.ptx", group_name, - mtl_id++); - OIIO::ofstream out; - OIIO::Filesystem::open (out, filename); - out << osl_ptx; + std::string filename = fmtformat("{}_{}.ptx", group_name, mtl_id++); + OIIO::Filesystem::write_text_file(filename, osl_ptx); } // Create Programs from the init and group_entry functions, @@ -690,11 +687,8 @@ OptixRaytracer::make_optix_materials () } if (options.get_int ("saveptx")) { - std::string filename = OIIO::Strutil::sprintf("%s_%d.ptx", group_name, - mtl_id++); - OIIO::ofstream out; - OIIO::Filesystem::open (out, filename); - out << osl_ptx; + std::string filename = fmtformat("{}_{}.ptx", group_name, mtl_id++); + OIIO::Filesystem::write_text_file(filename, osl_ptx); } OptixModule optix_module; diff --git a/src/testshade/testshade.cpp b/src/testshade/testshade.cpp index a58923562..113c887e1 100644 --- a/src/testshade/testshade.cpp +++ b/src/testshade/testshade.cpp @@ -375,7 +375,7 @@ static void specify_expr (int argc OSL_MAYBE_UNUSED, const char *argv[]) { OSL_DASSERT(argc == 2); - std::string shadername = OIIO::Strutil::sprintf("expr_%d", exprcount++); + std::string shadername = OSL::fmtformat("expr_{}", exprcount++); std::string sourcecode = "shader " + shadername + " (\n" " float s = u [[ int lockgeom=0 ]],\n" From 50c8f7c802b41aa012cc0fa32dbdd9059f3cf9ae Mon Sep 17 00:00:00 2001 From: Larry Gritz Date: Wed, 11 May 2022 08:51:07 -0700 Subject: [PATCH 2/2] Fixes on top of closure change Signed-off-by: Larry Gritz --- src/liboslexec/batched_llvm_gen.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/liboslexec/batched_llvm_gen.cpp b/src/liboslexec/batched_llvm_gen.cpp index ae73023a2..9b17fdf19 100644 --- a/src/liboslexec/batched_llvm_gen.cpp +++ b/src/liboslexec/batched_llvm_gen.cpp @@ -6530,7 +6530,9 @@ llvm_gen_keyword_fill(BatchedBackendLLVM &rop, Opcode &op, const ClosureRegistry } } if (!legal) { - rop.shadingcontext()->warningf("Unsupported closure keyword arg \"%s\" for %s (%s:%d)", key->c_str(), clname.c_str(), op.sourcefile().c_str(), op.sourceline()); + rop.shadingcontext()->warningfmt( + "Unsupported closure keyword arg \"{}\" for {} ({}:{})", *key, + clname, op.sourcefile(), op.sourceline()); } } } @@ -6554,10 +6556,11 @@ LLVMGEN (llvm_gen_closure) const ClosureRegistry::ClosureEntry * clentry = rop.shadingsys().find_closure(closure_name); if (!clentry) { - rop.shadingcontext()->errorf("Closure '%s' is not supported by the current renderer, called from %s:%d in shader \"%s\", layer %d \"%s\", group \"%s\"", - closure_name, op.sourcefile(), op.sourceline(), - rop.inst()->shadername(), rop.layer(), - rop.inst()->layername(), rop.group().name()); + rop.shadingcontext()->errorfmt( + "Closure '{}' is not supported by the current renderer, called from {}:{} in shader \"{}\", layer {} \"{}\", group \"{}\"", + closure_name, op.sourcefile(), op.sourceline(), + rop.inst()->shadername(), rop.layer(), rop.inst()->layername(), + rop.group().name()); return false; }