Skip to content

Use string interpolation instead of concatenation or format(). #673

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions jvm/src/test/scala-2.x/scala/xml/CompilerErrors.scala
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ class CompilerTesting {
// note: `code` should have a | margin
// the import's needed because toolbox compiler does not accumulate imports like the real one (TODO: verify hypothesis)
def xmlErrorMessages(msg: String, code: String): List[String] =
errorMessages(msg)("import scala.xml.{TopScope => $scope}\n"+ code.stripMargin)
errorMessages(msg)("import scala.xml.{TopScope => $scope}\n"+ code.stripMargin) // TODO what is this $scope?

def expectXmlError(msg: String, code: String): Unit = {
val errors: List[String] = xmlErrorMessages(msg, code)
Expand All @@ -203,6 +203,6 @@ class CompilerTesting {
def expectXmlErrors(msgCount: Int, msg: String, code: String): Unit = {
val errors: List[String] = xmlErrorMessages(msg, code)
val errorCount: Int = errors.count(_.contains(msg))
assert(errorCount == msgCount, s"$errorCount occurrences of \'$msg\' found -- expected $msgCount in:\n${errors.mkString("\n")}")
assert(errorCount == msgCount, s"$errorCount occurrences of '$msg' found -- expected $msgCount in:\n${errors.mkString("\n")}")
}
}
2 changes: 1 addition & 1 deletion shared/src/main/scala/scala/xml/Atom.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import scala.collection.Seq
*/
class Atom[+A](val data: A) extends SpecialNode with Serializable {
if (data == null)
throw new IllegalArgumentException("cannot construct " + getClass.getSimpleName + " with null")
throw new IllegalArgumentException(s"cannot construct ${getClass.getSimpleName} with null")

override protected def basisForHashCode: Seq[Any] = Seq(data)

Expand Down
4 changes: 2 additions & 2 deletions shared/src/main/scala/scala/xml/Attribute.scala
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,9 @@ trait Attribute extends MetaData {
if (value == null)
return
if (isPrefixed)
sb.append(pre).append(':')
sb.append(s"$pre:")

sb.append(key).append('=')
sb.append(s"$key=")
val sb2: StringBuilder = new StringBuilder()
Utility.sequenceToXML(value, TopScope, sb2, stripComments = true)
Utility.appendQuoted(sb2.toString, sb)
Expand Down
4 changes: 2 additions & 2 deletions shared/src/main/scala/scala/xml/Comment.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ case class Comment(commentText: String) extends SpecialNode {
final override def doTransform: Boolean = false

if (commentText.contains("--")) {
throw new IllegalArgumentException("text contains \"--\"")
throw new IllegalArgumentException(s"""text contains "--"""")
}
if (commentText.nonEmpty && commentText.charAt(commentText.length - 1) == '-') {
throw new IllegalArgumentException("The final character of a XML comment may not be '-'. See https://www.w3.org/TR/xml11//#IDA5CES")
Expand All @@ -40,5 +40,5 @@ case class Comment(commentText: String) extends SpecialNode {
* Appends &quot;<!-- text -->&quot; to this string buffer.
*/
override def buildString(sb: StringBuilder): StringBuilder =
sb.append("<!--").append(commentText).append("-->")
sb.append(s"<!--$commentText-->")
}
2 changes: 1 addition & 1 deletion shared/src/main/scala/scala/xml/EntityRef.scala
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,5 @@ case class EntityRef(entityName: String) extends SpecialNode {
* @return the modified string buffer `sb`.
*/
override def buildString(sb: StringBuilder): StringBuilder =
sb.append("&").append(entityName).append(";")
sb.append(s"&$entityName;")
}
2 changes: 1 addition & 1 deletion shared/src/main/scala/scala/xml/Group.scala
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ final case class Group(nodes: Seq[Node]) extends Node {
* Since Group is very much a hack it throws an exception if you
* try to do anything with it.
*/
private def fail(msg: String): Nothing = throw new UnsupportedOperationException("class Group does not support method '%s'".format(msg))
private def fail(msg: String): Nothing = throw new UnsupportedOperationException(s"class Group does not support method '$msg'")

override def label: Nothing = fail("label")
override def attributes: Nothing = fail("attributes")
Expand Down
2 changes: 1 addition & 1 deletion shared/src/main/scala/scala/xml/MetaData.scala
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ abstract class MetaData
* prefixed, and "key" otherwise.
*/
def prefixedKey: String = this match {
case x: Attribute if x.isPrefixed => x.pre + ":" + key
case x: Attribute if x.isPrefixed => s"${x.pre}:$key"
case _ => key
}

Expand Down
8 changes: 3 additions & 5 deletions shared/src/main/scala/scala/xml/NamespaceBinding.scala
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,8 @@ case class NamespaceBinding(prefix: String, uri: String, parent: NamespaceBindin
private def doBuildString(sb: StringBuilder, stop: NamespaceBinding): Unit = {
if (List(null, stop, TopScope).contains(this)) return

val s: String = " xmlns%s=\"%s\"".format(
if (prefix != null) ":" + prefix else "",
if (uri != null) uri else ""
)
parent.doBuildString(sb.append(s), stop) // copy(ignore)
val prefixStr: String = if (prefix != null) s":$prefix" else ""
val uriStr: String = if (uri != null) uri else ""
parent.doBuildString(sb.append(s""" xmlns$prefixStr="$uriStr""""), stop) // copy(ignore)
}
}
9 changes: 2 additions & 7 deletions shared/src/main/scala/scala/xml/Node.scala
Original file line number Diff line number Diff line change
Expand Up @@ -184,13 +184,8 @@ abstract class Node extends NodeSeq {
/**
* Appends qualified name of this node to `StringBuilder`.
*/
def nameToString(sb: StringBuilder): StringBuilder = {
if (null != prefix) {
sb.append(prefix)
sb.append(':')
}
sb.append(label)
}
def nameToString(sb: StringBuilder): StringBuilder =
sb.append(s"${if (prefix == null) "" else s"$prefix:"}$label")

/**
* Returns a type symbol (e.g. DTD, XSD), default `'''null'''`.
Expand Down
2 changes: 1 addition & 1 deletion shared/src/main/scala/scala/xml/NodeSeq.scala
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ abstract class NodeSeq extends AbstractSeq[Node] with immutable.Seq[Node] with S
* Convenience method which returns string text of the named attribute. Use:
* - `that \@ "foo"` to get the string text of attribute `"foo"`;
*/
def \@(attributeName: String): String = (this \ ("@" + attributeName)).text
def \@(attributeName: String): String = (this \ s"@$attributeName").text

override def toString: String = theSeq.mkString

Expand Down
2 changes: 1 addition & 1 deletion shared/src/main/scala/scala/xml/Null.scala
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ case object Null extends MetaData {
override def apply(namespace: String, scope: NamespaceBinding, key: String): ScalaVersionSpecificReturnTypes.NullApply3 = null
override def apply(key: String): ScalaVersionSpecificReturnTypes.NullApply1 =
if (Utility.isNameStart(key.head)) null
else throw new IllegalArgumentException("not a valid attribute name '" + key + "', so can never match !")
else throw new IllegalArgumentException(s"not a valid attribute name '$key', so can never match !")

override protected def toString1(sb: StringBuilder): Unit = ()
override protected def toString1: String = ""
Expand Down
6 changes: 4 additions & 2 deletions shared/src/main/scala/scala/xml/PCData.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ class PCData(data: String) extends Atom[String](data) {
* @param sb the input string buffer associated to some XML element
* @return the input string buffer with the formatted CDATA section
*/
override def buildString(sb: StringBuilder): StringBuilder =
sb.append("<![CDATA[%s]]>".format(data.replaceAll("]]>", "]]]]><![CDATA[>")))
override def buildString(sb: StringBuilder): StringBuilder = {
val dataStr: String = data.replaceAll("]]>", "]]]]><![CDATA[>")
sb.append(s"<![CDATA[$dataStr]]>")
}
}

/**
Expand Down
12 changes: 7 additions & 5 deletions shared/src/main/scala/scala/xml/ProcInstr.scala
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ package xml
// Note: used by the Scala compiler.
case class ProcInstr(target: String, proctext: String) extends SpecialNode {
if (!Utility.isName(target))
throw new IllegalArgumentException(target + " must be an XML Name")
throw new IllegalArgumentException(s"$target must be an XML Name")
if (proctext.contains("?>"))
throw new IllegalArgumentException(proctext + " may not contain \"?>\"")
throw new IllegalArgumentException(s"""$proctext may not contain "?>"""")
if (target.toLowerCase == "xml")
throw new IllegalArgumentException(target + " is reserved")
throw new IllegalArgumentException(s"$target is reserved")

final override def doCollectNamespaces: Boolean = false
final override def doTransform: Boolean = false
Expand All @@ -39,6 +39,8 @@ case class ProcInstr(target: String, proctext: String) extends SpecialNode {
* appends &quot;&lt;?&quot; target (&quot; &quot;+text)?+&quot;?&gt;&quot;
* to this stringbuffer.
*/
override def buildString(sb: StringBuilder): StringBuilder =
sb.append("<?%s%s?>".format(target, if (proctext == "") "" else " " + proctext))
override def buildString(sb: StringBuilder): StringBuilder = {
val textStr: String = if (proctext == "") "" else s" $proctext"
sb.append(s"<?$target$textStr?>")
}
}
15 changes: 7 additions & 8 deletions shared/src/main/scala/scala/xml/Utility.scala
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ object Utility extends AnyRef with parsing.TokenTests {
"quot" -> '"',
"apos" -> '\''
)
val escMap: Map[Char, String] = (pairs - "apos").map { case (s, c) => c -> "&%s;".format(s) }
val escMap: Map[Char, String] = (pairs - "apos").map { case (s, c) => c -> s"&$s;" }
val unescMap: Map[String, Char] = pairs
}
import Escapes.{ escMap, unescMap }
Expand Down Expand Up @@ -265,7 +265,7 @@ object Utility extends AnyRef with parsing.TokenTests {
val csp = e.child.forall(isAtomAndNotText)
ser(e.child.toList :: ns :: r, e.scope :: pscopes, csp :: spaced, e :: toClose)
}
case n => throw new IllegalArgumentException("Don't know how to serialize a " + n.getClass.getName)
case n => throw new IllegalArgumentException(s"Don't know how to serialize a ${n.getClass.getName}")
}
}
ser(List(ns.toList), List(pscope), List(spaced), Nil)
Expand Down Expand Up @@ -309,7 +309,7 @@ object Utility extends AnyRef with parsing.TokenTests {
*/
def appendQuoted(s: String, sb: StringBuilder): StringBuilder = {
val ch: Char = if (s.contains('"')) '\'' else '"'
sb.append(ch).append(s).append(ch)
sb.append(s"$ch$s$ch")
}

/**
Expand Down Expand Up @@ -347,10 +347,10 @@ object Utility extends AnyRef with parsing.TokenTests {
case '&' =>
val n: String = getName(value, i + 1)
if (n.eq(null))
return "malformed entity reference in attribute value [" + value + "]"
return s"malformed entity reference in attribute value [$value]"
i = i + n.length + 1
if (i >= value.length || value.charAt(i) != ';')
return "malformed entity reference in attribute value [" + value + "]"
return s"malformed entity reference in attribute value [$value]"
case _ =>
}
i = i + 1
Expand Down Expand Up @@ -423,14 +423,13 @@ object Utility extends AnyRef with parsing.TokenTests {
case 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
| 'A' | 'B' | 'C' | 'D' | 'E' | 'F' =>
if (!hex)
reportSyntaxError("hex char not allowed in decimal char ref\n" +
"Did you mean to write &#x ?")
reportSyntaxError("hex char not allowed in decimal char ref\nDid you mean to write &#x ?")
else
i = i * base + ch().asDigit
case SU =>
reportTruncatedError("")
case _ =>
reportSyntaxError("character '" + ch() + "' not allowed in char ref\n")
reportSyntaxError(s"character '${ch()}' not allowed in char ref\n")
}
nextch()
}
Expand Down
4 changes: 2 additions & 2 deletions shared/src/main/scala/scala/xml/XML.scala
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ object XML extends XMLLoader[Elem] {
minimizeTags: MinimizeMode.Value = MinimizeMode.Default
): Unit = {
/* TODO: optimize by giving writer parameter to toXML*/
if (xmlDecl) w.write("<?xml version='1.0' encoding='" + enc + "'?>\n")
if (doctype.ne(null)) w.write(doctype.toString + "\n")
if (xmlDecl) w.write(s"<?xml version='1.0' encoding='$enc'?>\n")
if (doctype.ne(null)) w.write(s"$doctype\n")
w.write(Utility.serialize(node, minimizeTags = minimizeTags).toString)
}
}
2 changes: 1 addition & 1 deletion shared/src/main/scala/scala/xml/dtd/ContentModel.scala
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ object ContentModel extends WordExp {
}

case class ElemName(name: String) extends Label {
override def toString: String = """ElemName("%s")""".format(name)
override def toString: String = s"""ElemName("$name")"""
}

def isMixed(cm: ContentModel): Boolean = cond(cm) { case _: MIXED => true }
Expand Down
5 changes: 1 addition & 4 deletions shared/src/main/scala/scala/xml/dtd/DTD.scala
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,5 @@ abstract class DTD {
var ent: mutable.Map[String, EntityDecl] = new mutable.HashMap[String, EntityDecl]()

override def toString: String =
"DTD %s [\n%s]".format(
Option(externalID).getOrElse(""),
decls.mkString("", "\n", "\n")
)
s"DTD ${Option(externalID).getOrElse("")} [\n${decls.mkString("\n")}\n]"
}
25 changes: 11 additions & 14 deletions shared/src/main/scala/scala/xml/dtd/Decl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,16 @@ sealed abstract class MarkupDecl extends Decl {
case class ElemDecl(name: String, contentModel: ContentModel)
extends MarkupDecl {
override def buildString(sb: StringBuilder): StringBuilder = {
sb.append("<!ELEMENT ").append(name).append(' ')

sb.append(s"<!ELEMENT $name ")
ContentModel.buildString(contentModel, sb)
sb.append('>')
}
}

case class AttListDecl(name: String, attrs: List[AttrDecl])
extends MarkupDecl {
override def buildString(sb: StringBuilder): StringBuilder = {
sb.append("<!ATTLIST ").append(name).append('\n').append(attrs.mkString("", "\n", ">"))
}
override def buildString(sb: StringBuilder): StringBuilder =
sb.append(s"<!ATTLIST $name\n${attrs.mkString("\n")}>")
}

/**
Expand All @@ -63,10 +61,9 @@ case class AttrDecl(name: String, tpe: String, default: DefaultDecl) {
override def toString: String = sbToString(buildString)

def buildString(sb: StringBuilder): StringBuilder = {
sb.append(" ").append(name).append(' ').append(tpe).append(' ')
sb.append(s" $name $tpe ")
default.buildString(sb)
}

}

/** an entity declaration */
Expand All @@ -75,31 +72,31 @@ sealed abstract class EntityDecl extends MarkupDecl
/** a parsed general entity declaration */
case class ParsedEntityDecl(name: String, entdef: EntityDef) extends EntityDecl {
override def buildString(sb: StringBuilder): StringBuilder = {
sb.append("<!ENTITY ").append(name).append(' ')
sb.append(s"<!ENTITY $name ")
entdef.buildString(sb).append('>')
}
}

/** a parameter entity declaration */
case class ParameterEntityDecl(name: String, entdef: EntityDef) extends EntityDecl {
override def buildString(sb: StringBuilder): StringBuilder = {
sb.append("<!ENTITY % ").append(name).append(' ')
sb.append(s"<!ENTITY % $name ")
entdef.buildString(sb).append('>')
}
}

/** an unparsed entity declaration */
case class UnparsedEntityDecl(name: String, extID: ExternalID, notation: String) extends EntityDecl {
override def buildString(sb: StringBuilder): StringBuilder = {
sb.append("<!ENTITY ").append(name).append(' ')
extID.buildString(sb).append(" NDATA ").append(notation).append('>')
sb.append(s"<!ENTITY $name ")
extID.buildString(sb).append(s" NDATA $notation>")
}
}

/** a notation declaration */
case class NotationDecl(name: String, extID: ExternalID) extends MarkupDecl {
override def buildString(sb: StringBuilder): StringBuilder = {
sb.append("<!NOTATION ").append(name).append(' ')
sb.append(s"<!NOTATION $name ")
extID.buildString(sb).append('>')
}
}
Expand All @@ -120,7 +117,7 @@ case class IntDef(value: String) extends EntityDef {
val n: String = tmp.substring(ix, iz)

if (!Utility.isName(n))
throw new IllegalArgumentException("internal entity def: \"" + n + "\" must be an XML Name")
throw new IllegalArgumentException(s"""internal entity def: "$n" must be an XML Name""")

tmp = tmp.substring(iz + 1, tmp.length)
ix = tmp.indexOf('%')
Expand All @@ -145,7 +142,7 @@ case class PEReference(ent: String) extends MarkupDecl {
throw new IllegalArgumentException("ent must be an XML Name")

override def buildString(sb: StringBuilder): StringBuilder =
sb.append('%').append(ent).append(';')
sb.append(s"%$ent;")
}

// default declarations for attributes
Expand Down
4 changes: 2 additions & 2 deletions shared/src/main/scala/scala/xml/dtd/DocType.scala
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ import scala.collection.Seq
*/
case class DocType(name: String, extID: ExternalID, intSubset: Seq[dtd.Decl]) {
if (!Utility.isName(name))
throw new IllegalArgumentException(name + " must be an XML Name")
throw new IllegalArgumentException(s"$name must be an XML Name")

/** returns "&lt;!DOCTYPE + name + extID? + ("["+intSubSet+"]")? >" */
final override def toString: String = {
def intString: String =
if (intSubset.isEmpty) ""
else intSubset.mkString("[", "", "]")

"""<!DOCTYPE %s %s%s>""".format(name, extID.toString, intString)
s"<!DOCTYPE $name $extID$intString>"
}
}

Expand Down
13 changes: 5 additions & 8 deletions shared/src/main/scala/scala/xml/dtd/ExternalID.scala
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,16 @@ package dtd
sealed abstract class ExternalID extends parsing.TokenTests {
def quoted(s: String): String = {
val c: Char = if (s.contains('"')) '\'' else '"'
c.toString + s + c
s"$c$s$c"
}

// public != null: PUBLIC " " publicLiteral " " [systemLiteral]
// public == null: SYSTEM " " systemLiteral
override def toString: String = {
lazy val quotedSystemLiteral: String = quoted(systemId)
lazy val quotedPublicLiteral: String = quoted(publicId)
override def toString: String =
if (publicId == null) s"SYSTEM ${quoted(systemId)}" else
if (systemId == null) s"PUBLIC ${quoted(publicId)}" else
s"PUBLIC ${quoted(publicId)} ${quoted(systemId)}"

if (publicId == null) "SYSTEM " + quotedSystemLiteral
else "PUBLIC " + quotedPublicLiteral +
(if (systemId == null) "" else " " + quotedSystemLiteral)
}
def buildString(sb: StringBuilder): StringBuilder =
sb.append(this.toString)

Expand Down
Loading