id
stringlengths
5
19
content
stringlengths
94
57.5k
max_stars_repo_path
stringlengths
36
95
Closure-35
private void inferPropertyTypesToMatchConstraint( JSType type, JSType constraint) { if (type == null || constraint == null) { return; } ObjectType constraintObj = ObjectType.cast(constraint.restrictByNotNullOrUndefined()); if (constraintObj != null && constraintObj.isRecordType()) { ObjectType objType = ObjectType.cast(type.restrictByNotNullOrUndefined()); if (objType != null) { for (String prop : constraintObj.getOwnPropertyNames()) { JSType propType = constraintObj.getPropertyType(prop); if (!objType.isPropertyTypeDeclared(prop)) { JSType typeToInfer = propType; if (!objType.hasProperty(prop)) { typeToInfer = getNativeType(VOID_TYPE).getLeastSupertype(propType); } objType.defineInferredProperty(prop, typeToInfer, null); } } } } } private void inferPropertyTypesToMatchConstraint( JSType type, JSType constraint) { if (type == null || constraint == null) { return; } ObjectType constraintObj = ObjectType.cast(constraint.restrictByNotNullOrUndefined()); if (constraintObj != null) { type.matchConstraint(constraintObj); } }
src/com/google/javascript/jscomp/TypeInference.java
Closure-36
private boolean canInline( Reference declaration, Reference initialization, Reference reference) { if (!isValidDeclaration(declaration) || !isValidInitialization(initialization) || !isValidReference(reference)) { return false; } // If the value is read more than once, skip it. // VAR declarations and EXPR_RESULT don't need the value, but other // ASSIGN expressions parents do. if (declaration != initialization && !initialization.getGrandparent().isExprResult()) { return false; } // Be very conservative and do no cross control structures or // scope boundaries if (declaration.getBasicBlock() != initialization.getBasicBlock() || declaration.getBasicBlock() != reference.getBasicBlock()) { return false; } // Do not inline into a call node. This would change // the context in which it was being called. For example, // var a = b.c; // a(); // should not be inlined, because it calls a in the context of b // rather than the context of the window. // var a = b.c; // f(a) // is ok. Node value = initialization.getAssignedValue(); Preconditions.checkState(value != null); if (value.isGetProp() && reference.getParent().isCall() && reference.getParent().getFirstChild() == reference.getNode()) { return false; } if (value.isFunction()) { Node callNode = reference.getParent(); if (reference.getParent().isCall()) { CodingConvention convention = compiler.getCodingConvention(); // Bug 2388531: Don't inline subclass definitions into class defining // calls as this confused class removing logic. SubclassRelationship relationship = convention.getClassesDefinedByCall(callNode); if (relationship != null) { return false; } // issue 668: Don't inline singleton getter methods // calls as this confused class removing logic. } } return canMoveAggressively(value) || canMoveModerately(initialization, reference); } private boolean canInline( Reference declaration, Reference initialization, Reference reference) { if (!isValidDeclaration(declaration) || !isValidInitialization(initialization) || !isValidReference(reference)) { return false; } // If the value is read more than once, skip it. // VAR declarations and EXPR_RESULT don't need the value, but other // ASSIGN expressions parents do. if (declaration != initialization && !initialization.getGrandparent().isExprResult()) { return false; } // Be very conservative and do no cross control structures or // scope boundaries if (declaration.getBasicBlock() != initialization.getBasicBlock() || declaration.getBasicBlock() != reference.getBasicBlock()) { return false; } // Do not inline into a call node. This would change // the context in which it was being called. For example, // var a = b.c; // a(); // should not be inlined, because it calls a in the context of b // rather than the context of the window. // var a = b.c; // f(a) // is ok. Node value = initialization.getAssignedValue(); Preconditions.checkState(value != null); if (value.isGetProp() && reference.getParent().isCall() && reference.getParent().getFirstChild() == reference.getNode()) { return false; } if (value.isFunction()) { Node callNode = reference.getParent(); if (reference.getParent().isCall()) { CodingConvention convention = compiler.getCodingConvention(); // Bug 2388531: Don't inline subclass definitions into class defining // calls as this confused class removing logic. SubclassRelationship relationship = convention.getClassesDefinedByCall(callNode); if (relationship != null) { return false; } // issue 668: Don't inline singleton getter methods // calls as this confused class removing logic. if (convention.getSingletonGetterClassName(callNode) != null) { return false; } } } return canMoveAggressively(value) || canMoveModerately(initialization, reference); }
src/com/google/javascript/jscomp/InlineVariables.java
Closure-38
void addNumber(double x) { // This is not pretty printing. This is to prevent misparsing of x- -4 as // x--4 (which is a syntax error). char prev = getLastChar(); boolean negativeZero = isNegativeZero(x); if (x < 0 && prev == '-') { add(" "); } if ((long) x == x && !negativeZero) { long value = (long) x; long mantissa = value; int exp = 0; if (Math.abs(x) >= 100) { while (mantissa / 10 * Math.pow(10, exp + 1) == value) { mantissa /= 10; exp++; } } if (exp > 2) { add(Long.toString(mantissa) + "E" + Integer.toString(exp)); } else { add(Long.toString(value)); } } else { add(String.valueOf(x)); } } void addNumber(double x) { // This is not pretty printing. This is to prevent misparsing of x- -4 as // x--4 (which is a syntax error). char prev = getLastChar(); boolean negativeZero = isNegativeZero(x); if ((x < 0 || negativeZero) && prev == '-') { add(" "); } if ((long) x == x && !negativeZero) { long value = (long) x; long mantissa = value; int exp = 0; if (Math.abs(x) >= 100) { while (mantissa / 10 * Math.pow(10, exp + 1) == value) { mantissa /= 10; exp++; } } if (exp > 2) { add(Long.toString(mantissa) + "E" + Integer.toString(exp)); } else { add(Long.toString(value)); } } else { add(String.valueOf(x)); } }
src/com/google/javascript/jscomp/CodeConsumer.java
Closure-39
String toStringHelper(boolean forAnnotations) { if (hasReferenceName()) { return getReferenceName(); } else if (prettyPrint) { // Don't pretty print recursively. prettyPrint = false; // Use a tree set so that the properties are sorted. Set<String> propertyNames = Sets.newTreeSet(); for (ObjectType current = this; current != null && !current.isNativeObjectType() && propertyNames.size() <= MAX_PRETTY_PRINTED_PROPERTIES; current = current.getImplicitPrototype()) { propertyNames.addAll(current.getOwnPropertyNames()); } StringBuilder sb = new StringBuilder(); sb.append("{"); int i = 0; for (String property : propertyNames) { if (i > 0) { sb.append(", "); } sb.append(property); sb.append(": "); sb.append(getPropertyType(property).toString()); ++i; if (i == MAX_PRETTY_PRINTED_PROPERTIES) { sb.append(", ..."); break; } } sb.append("}"); prettyPrint = true; return sb.toString(); } else { return "{...}"; } } String toStringHelper(boolean forAnnotations) { if (hasReferenceName()) { return getReferenceName(); } else if (prettyPrint) { // Don't pretty print recursively. prettyPrint = false; // Use a tree set so that the properties are sorted. Set<String> propertyNames = Sets.newTreeSet(); for (ObjectType current = this; current != null && !current.isNativeObjectType() && propertyNames.size() <= MAX_PRETTY_PRINTED_PROPERTIES; current = current.getImplicitPrototype()) { propertyNames.addAll(current.getOwnPropertyNames()); } StringBuilder sb = new StringBuilder(); sb.append("{"); int i = 0; for (String property : propertyNames) { if (i > 0) { sb.append(", "); } sb.append(property); sb.append(": "); sb.append(getPropertyType(property).toStringHelper(forAnnotations)); ++i; if (!forAnnotations && i == MAX_PRETTY_PRINTED_PROPERTIES) { sb.append(", ..."); break; } } sb.append("}"); prettyPrint = true; return sb.toString(); } else { return forAnnotations ? "?" : "{...}"; } }
src/com/google/javascript/rhino/jstype/PrototypeObjectType.java
Closure-4
JSType resolveInternal(ErrorReporter t, StaticScope<JSType> enclosing) { // TODO(user): Investigate whether it is really necessary to keep two // different mechanisms for resolving named types, and if so, which order // makes more sense. Now, resolution via registry is first in order to // avoid triggering the warnings built into the resolution via properties. boolean resolved = resolveViaRegistry(t, enclosing); if (detectImplicitPrototypeCycle()) { handleTypeCycle(t); } if (resolved) { super.resolveInternal(t, enclosing); finishPropertyContinuations(); return registry.isLastGeneration() ? getReferencedType() : this; } resolveViaProperties(t, enclosing); if (detectImplicitPrototypeCycle()) { handleTypeCycle(t); } super.resolveInternal(t, enclosing); if (isResolved()) { finishPropertyContinuations(); } return registry.isLastGeneration() ? getReferencedType() : this; } JSType resolveInternal(ErrorReporter t, StaticScope<JSType> enclosing) { // TODO(user): Investigate whether it is really necessary to keep two // different mechanisms for resolving named types, and if so, which order // makes more sense. Now, resolution via registry is first in order to // avoid triggering the warnings built into the resolution via properties. boolean resolved = resolveViaRegistry(t, enclosing); if (detectInheritanceCycle()) { handleTypeCycle(t); } if (resolved) { super.resolveInternal(t, enclosing); finishPropertyContinuations(); return registry.isLastGeneration() ? getReferencedType() : this; } resolveViaProperties(t, enclosing); if (detectInheritanceCycle()) { handleTypeCycle(t); } super.resolveInternal(t, enclosing); if (isResolved()) { finishPropertyContinuations(); } return registry.isLastGeneration() ? getReferencedType() : this; }
src/com/google/javascript/rhino/jstype/NamedType.java
Closure-40
public void visit(NodeTraversal t, Node n, Node parent) { // Record global variable and function declarations if (t.inGlobalScope()) { if (NodeUtil.isVarDeclaration(n)) { NameInformation ns = createNameInformation(t, n, parent); Preconditions.checkNotNull(ns); recordSet(ns.name, n); } else if (NodeUtil.isFunctionDeclaration(n)) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { JsName nameInfo = getName(nameNode.getString(), true); recordSet(nameInfo.name, nameNode); } } else if (NodeUtil.isObjectLitKey(n, parent)) { NameInformation ns = createNameInformation(t, n, parent); if (ns != null) { recordSet(ns.name, n); } } } // Record assignments and call sites if (n.isAssign()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { if (ns.isPrototype) { recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n); } else { recordSet(ns.name, nameNode); } } } else if (n.isCall()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null && ns.onlyAffectsClassDef) { JsName name = getName(ns.name, false); if (name != null) { refNodes.add(new ClassDefiningFunctionNode( name, n, parent, parent.getParent())); } } } } public void visit(NodeTraversal t, Node n, Node parent) { // Record global variable and function declarations if (t.inGlobalScope()) { if (NodeUtil.isVarDeclaration(n)) { NameInformation ns = createNameInformation(t, n, parent); Preconditions.checkNotNull(ns); recordSet(ns.name, n); } else if (NodeUtil.isFunctionDeclaration(n)) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { JsName nameInfo = getName(nameNode.getString(), true); recordSet(nameInfo.name, nameNode); } } else if (NodeUtil.isObjectLitKey(n, parent)) { NameInformation ns = createNameInformation(t, n, parent); if (ns != null) { recordSet(ns.name, n); } } } // Record assignments and call sites if (n.isAssign()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null) { if (ns.isPrototype) { recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n); } else { recordSet(ns.name, nameNode); } } } else if (n.isCall()) { Node nameNode = n.getFirstChild(); NameInformation ns = createNameInformation(t, nameNode, n); if (ns != null && ns.onlyAffectsClassDef) { JsName name = getName(ns.name, true); refNodes.add(new ClassDefiningFunctionNode( name, n, parent, parent.getParent())); } } }
src/com/google/javascript/jscomp/NameAnalyzer.java
Closure-42
Node processForInLoop(ForInLoop loopNode) { // Return the bare minimum to put the AST in a valid state. return newNode( Token.FOR, transform(loopNode.getIterator()), transform(loopNode.getIteratedObject()), transformBlock(loopNode.getBody())); } Node processForInLoop(ForInLoop loopNode) { if (loopNode.isForEach()) { errorReporter.error( "unsupported language extension: for each", sourceName, loopNode.getLineno(), "", 0); // Return the bare minimum to put the AST in a valid state. return newNode(Token.EXPR_RESULT, Node.newNumber(0)); } return newNode( Token.FOR, transform(loopNode.getIterator()), transform(loopNode.getIteratedObject()), transformBlock(loopNode.getBody())); }
src/com/google/javascript/jscomp/parsing/IRFactory.java
Closure-44
void add(String newcode) { maybeEndStatement(); if (newcode.length() == 0) { return; } char c = newcode.charAt(0); if ((isWordChar(c) || c == '\\') && isWordChar(getLastChar())) { // need space to separate. This is not pretty printing. // For example: "return foo;" append(" "); // Do not allow a forward slash to appear after a DIV. // For example, // REGEXP DIV REGEXP // is valid and should print like // / // / / } append(newcode); } void add(String newcode) { maybeEndStatement(); if (newcode.length() == 0) { return; } char c = newcode.charAt(0); if ((isWordChar(c) || c == '\\') && isWordChar(getLastChar())) { // need space to separate. This is not pretty printing. // For example: "return foo;" append(" "); } else if (c == '/' && getLastChar() == '/') { // Do not allow a forward slash to appear after a DIV. // For example, // REGEXP DIV REGEXP // is valid and should print like // / // / / append(" "); } append(newcode); }
src/com/google/javascript/jscomp/CodeConsumer.java
Closure-48
void maybeDeclareQualifiedName(NodeTraversal t, JSDocInfo info, Node n, Node parent, Node rhsValue) { Node ownerNode = n.getFirstChild(); String ownerName = ownerNode.getQualifiedName(); String qName = n.getQualifiedName(); String propName = n.getLastChild().getString(); Preconditions.checkArgument(qName != null && ownerName != null); // Precedence of type information on GETPROPs: // 1) @type annnotation / @enum annotation // 2) ASSIGN to FUNCTION literal // 3) @param/@return annotation (with no function literal) // 4) ASSIGN to something marked @const // 5) ASSIGN to anything else // // 1, 3, and 4 are declarations, 5 is inferred, and 2 is a declaration iff // the function has jsdoc or has not been declared before. // // FUNCTION literals are special because TypedScopeCreator is very smart // about getting as much type information as possible for them. // Determining type for #1 + #2 + #3 + #4 JSType valueType = getDeclaredType(t.getSourceName(), info, n, rhsValue); if (valueType == null && rhsValue != null) { // Determining type for #5 valueType = rhsValue.getJSType(); } // Function prototypes are special. // It's a common JS idiom to do: // F.prototype = { ... }; // So if F does not have an explicitly declared super type, // allow F.prototype to be redefined arbitrarily. if ("prototype".equals(propName)) { Var qVar = scope.getVar(qName); if (qVar != null) { // If the programmer has declared that F inherits from Super, // and they assign F.prototype to an object literal, // then they are responsible for making sure that the object literal's // implicit prototype is set up appropriately. We just obey // the @extends tag. ObjectType qVarType = ObjectType.cast(qVar.getType()); if (qVarType != null && rhsValue != null && rhsValue.isObjectLit()) { typeRegistry.resetImplicitPrototype( rhsValue.getJSType(), qVarType.getImplicitPrototype()); } else if (!qVar.isTypeInferred()) { // If the programmer has declared that F inherits from Super, // and they assign F.prototype to some arbitrary expression, // there's not much we can do. We just ignore the expression, // and hope they've annotated their code in a way to tell us // what props are going to be on that prototype. return; } if (qVar.getScope() == scope) { scope.undeclare(qVar); } } } if (valueType == null) { if (parent.isExprResult()) { stubDeclarations.add(new StubDeclaration( n, t.getInput() != null && t.getInput().isExtern(), ownerName)); } return; } // NOTE(nicksantos): Determining whether a property is declared or not // is really really obnoxious. // // The problem is that there are two (equally valid) coding styles: // // (function() { // /* The authoritative definition of goog.bar. */ // goog.bar = function() {}; // })(); // // function f() { // goog.bar(); // /* Reset goog.bar to a no-op. */ // goog.bar = function() {}; // } // // In a dynamic language with first-class functions, it's very difficult // to know which one the user intended without looking at lots of // contextual information (the second example demonstrates a small case // of this, but there are some really pathological cases as well). // // The current algorithm checks if either the declaration has // jsdoc type information, or @const with a known type, // or a function literal with a name we haven't seen before. boolean inferred = true; if (info != null) { // Determining declaration for #1 + #3 + #4 inferred = !(info.hasType() || info.hasEnumParameterType() || (info.isConstant() && valueType != null && !valueType.isUnknownType()) || FunctionTypeBuilder.isFunctionTypeDeclaration(info)); } if (inferred) { // Determining declaration for #2 inferred = !(rhsValue != null && rhsValue.isFunction() && (info != null || !scope.isDeclared(qName, false))); } if (!inferred) { ObjectType ownerType = getObjectSlot(ownerName); if (ownerType != null) { // Only declare this as an official property if it has not been // declared yet. boolean isExtern = t.getInput() != null && t.getInput().isExtern(); if ((!ownerType.hasOwnProperty(propName) || ownerType.isPropertyTypeInferred(propName)) && ((isExtern && !ownerType.isNativeObjectType()) || !ownerType.isInstanceType())) { // If the property is undeclared or inferred, declare it now. ownerType.defineDeclaredProperty(propName, valueType, n); } } // If the property is already declared, the error will be // caught when we try to declare it in the current scope. defineSlot(n, parent, valueType, inferred); } else if (rhsValue != null && rhsValue.isTrue()) { // We declare these for delegate proxy method properties. FunctionType ownerType = JSType.toMaybeFunctionType(getObjectSlot(ownerName)); if (ownerType != null) { JSType ownerTypeOfThis = ownerType.getTypeOfThis(); String delegateName = codingConvention.getDelegateSuperclassName(); JSType delegateType = delegateName == null ? null : typeRegistry.getType(delegateName); if (delegateType != null && ownerTypeOfThis.isSubtype(delegateType)) { defineSlot(n, parent, getNativeType(BOOLEAN_TYPE), true); } } } } void maybeDeclareQualifiedName(NodeTraversal t, JSDocInfo info, Node n, Node parent, Node rhsValue) { Node ownerNode = n.getFirstChild(); String ownerName = ownerNode.getQualifiedName(); String qName = n.getQualifiedName(); String propName = n.getLastChild().getString(); Preconditions.checkArgument(qName != null && ownerName != null); // Precedence of type information on GETPROPs: // 1) @type annnotation / @enum annotation // 2) ASSIGN to FUNCTION literal // 3) @param/@return annotation (with no function literal) // 4) ASSIGN to something marked @const // 5) ASSIGN to anything else // // 1, 3, and 4 are declarations, 5 is inferred, and 2 is a declaration iff // the function has jsdoc or has not been declared before. // // FUNCTION literals are special because TypedScopeCreator is very smart // about getting as much type information as possible for them. // Determining type for #1 + #2 + #3 + #4 JSType valueType = getDeclaredType(t.getSourceName(), info, n, rhsValue); if (valueType == null && rhsValue != null) { // Determining type for #5 valueType = rhsValue.getJSType(); } // Function prototypes are special. // It's a common JS idiom to do: // F.prototype = { ... }; // So if F does not have an explicitly declared super type, // allow F.prototype to be redefined arbitrarily. if ("prototype".equals(propName)) { Var qVar = scope.getVar(qName); if (qVar != null) { // If the programmer has declared that F inherits from Super, // and they assign F.prototype to an object literal, // then they are responsible for making sure that the object literal's // implicit prototype is set up appropriately. We just obey // the @extends tag. ObjectType qVarType = ObjectType.cast(qVar.getType()); if (qVarType != null && rhsValue != null && rhsValue.isObjectLit()) { typeRegistry.resetImplicitPrototype( rhsValue.getJSType(), qVarType.getImplicitPrototype()); } else if (!qVar.isTypeInferred()) { // If the programmer has declared that F inherits from Super, // and they assign F.prototype to some arbitrary expression, // there's not much we can do. We just ignore the expression, // and hope they've annotated their code in a way to tell us // what props are going to be on that prototype. return; } if (qVar.getScope() == scope) { scope.undeclare(qVar); } } } if (valueType == null) { if (parent.isExprResult()) { stubDeclarations.add(new StubDeclaration( n, t.getInput() != null && t.getInput().isExtern(), ownerName)); } return; } // NOTE(nicksantos): Determining whether a property is declared or not // is really really obnoxious. // // The problem is that there are two (equally valid) coding styles: // // (function() { // /* The authoritative definition of goog.bar. */ // goog.bar = function() {}; // })(); // // function f() { // goog.bar(); // /* Reset goog.bar to a no-op. */ // goog.bar = function() {}; // } // // In a dynamic language with first-class functions, it's very difficult // to know which one the user intended without looking at lots of // contextual information (the second example demonstrates a small case // of this, but there are some really pathological cases as well). // // The current algorithm checks if either the declaration has // jsdoc type information, or @const with a known type, // or a function literal with a name we haven't seen before. boolean inferred = true; if (info != null) { // Determining declaration for #1 + #3 + #4 inferred = !(info.hasType() || info.hasEnumParameterType() || (info.isConstant() && valueType != null && !valueType.isUnknownType()) || FunctionTypeBuilder.isFunctionTypeDeclaration(info)); } if (inferred && rhsValue != null && rhsValue.isFunction()) { // Determining declaration for #2 if (info != null) { inferred = false; } else if (!scope.isDeclared(qName, false) && n.isUnscopedQualifiedName()) { inferred = false; } } if (!inferred) { ObjectType ownerType = getObjectSlot(ownerName); if (ownerType != null) { // Only declare this as an official property if it has not been // declared yet. boolean isExtern = t.getInput() != null && t.getInput().isExtern(); if ((!ownerType.hasOwnProperty(propName) || ownerType.isPropertyTypeInferred(propName)) && ((isExtern && !ownerType.isNativeObjectType()) || !ownerType.isInstanceType())) { // If the property is undeclared or inferred, declare it now. ownerType.defineDeclaredProperty(propName, valueType, n); } } // If the property is already declared, the error will be // caught when we try to declare it in the current scope. defineSlot(n, parent, valueType, inferred); } else if (rhsValue != null && rhsValue.isTrue()) { // We declare these for delegate proxy method properties. FunctionType ownerType = JSType.toMaybeFunctionType(getObjectSlot(ownerName)); if (ownerType != null) { JSType ownerTypeOfThis = ownerType.getTypeOfThis(); String delegateName = codingConvention.getDelegateSuperclassName(); JSType delegateType = delegateName == null ? null : typeRegistry.getType(delegateName); if (delegateType != null && ownerTypeOfThis.isSubtype(delegateType)) { defineSlot(n, parent, getNativeType(BOOLEAN_TYPE), true); } } } }
src/com/google/javascript/jscomp/TypedScopeCreator.java
Closure-5
private boolean isInlinableObject(List<Reference> refs) { boolean ret = false; Set<String> validProperties = Sets.newHashSet(); for (Reference ref : refs) { Node name = ref.getNode(); Node parent = ref.getParent(); Node gramps = ref.getGrandparent(); // Ignore most indirect references, like x.y (but not x.y(), // since the function referenced by y might reference 'this'). // if (parent.isGetProp()) { Preconditions.checkState(parent.getFirstChild() == name); // A call target may be using the object as a 'this' value. if (gramps.isCall() && gramps.getFirstChild() == parent) { return false; } // Deleting a property has different semantics from deleting // a variable, so deleted properties should not be inlined. // NOTE(nicksantos): This pass's object-splitting algorithm has // a blind spot. It assumes that if a property isn't defined on an // object, then the value is undefined. This is not true, because // Object.prototype can have arbitrary properties on it. // // We short-circuit this problem by bailing out if we see a reference // to a property that isn't defined on the object literal. This // isn't a perfect algorithm, but it should catch most cases. String propName = parent.getLastChild().getString(); if (!validProperties.contains(propName)) { if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) { validProperties.add(propName); } else { return false; } } continue; } // Only rewrite VAR declarations or simple assignment statements if (!isVarOrAssignExprLhs(name)) { return false; } Node val = ref.getAssignedValue(); if (val == null) { // A var with no assignment. continue; } // We're looking for object literal assignments only. if (!val.isObjectLit()) { return false; } // Make sure that the value is not self-referential. IOW, // disallow things like x = {b: x.a}. // // TODO: Only exclude unorderable self-referential // assignments. i.e. x = {a: x.b, b: x.a} is not orderable, // but x = {a: 1, b: x.a} is. // // Also, ES5 getters/setters aren't handled by this pass. for (Node child = val.getFirstChild(); child != null; child = child.getNext()) { if (child.isGetterDef() || child.isSetterDef()) { // ES5 get/set not supported. return false; } validProperties.add(child.getString()); Node childVal = child.getFirstChild(); // Check if childVal is the parent of any of the passed in // references, as that is how self-referential assignments // will happen. for (Reference t : refs) { Node refNode = t.getParent(); while (!NodeUtil.isStatementBlock(refNode)) { if (refNode == childVal) { // There's a self-referential assignment return false; } refNode = refNode.getParent(); } } } // We have found an acceptable object literal assignment. As // long as there are no other assignments that mess things up, // we can inline. ret = true; } return ret; } private boolean isInlinableObject(List<Reference> refs) { boolean ret = false; Set<String> validProperties = Sets.newHashSet(); for (Reference ref : refs) { Node name = ref.getNode(); Node parent = ref.getParent(); Node gramps = ref.getGrandparent(); // Ignore most indirect references, like x.y (but not x.y(), // since the function referenced by y might reference 'this'). // if (parent.isGetProp()) { Preconditions.checkState(parent.getFirstChild() == name); // A call target may be using the object as a 'this' value. if (gramps.isCall() && gramps.getFirstChild() == parent) { return false; } // Deleting a property has different semantics from deleting // a variable, so deleted properties should not be inlined. if (gramps.isDelProp()) { return false; } // NOTE(nicksantos): This pass's object-splitting algorithm has // a blind spot. It assumes that if a property isn't defined on an // object, then the value is undefined. This is not true, because // Object.prototype can have arbitrary properties on it. // // We short-circuit this problem by bailing out if we see a reference // to a property that isn't defined on the object literal. This // isn't a perfect algorithm, but it should catch most cases. String propName = parent.getLastChild().getString(); if (!validProperties.contains(propName)) { if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) { validProperties.add(propName); } else { return false; } } continue; } // Only rewrite VAR declarations or simple assignment statements if (!isVarOrAssignExprLhs(name)) { return false; } Node val = ref.getAssignedValue(); if (val == null) { // A var with no assignment. continue; } // We're looking for object literal assignments only. if (!val.isObjectLit()) { return false; } // Make sure that the value is not self-referential. IOW, // disallow things like x = {b: x.a}. // // TODO: Only exclude unorderable self-referential // assignments. i.e. x = {a: x.b, b: x.a} is not orderable, // but x = {a: 1, b: x.a} is. // // Also, ES5 getters/setters aren't handled by this pass. for (Node child = val.getFirstChild(); child != null; child = child.getNext()) { if (child.isGetterDef() || child.isSetterDef()) { // ES5 get/set not supported. return false; } validProperties.add(child.getString()); Node childVal = child.getFirstChild(); // Check if childVal is the parent of any of the passed in // references, as that is how self-referential assignments // will happen. for (Reference t : refs) { Node refNode = t.getParent(); while (!NodeUtil.isStatementBlock(refNode)) { if (refNode == childVal) { // There's a self-referential assignment return false; } refNode = refNode.getParent(); } } } // We have found an acceptable object literal assignment. As // long as there are no other assignments that mess things up, // we can inline. ret = true; } return ret; }
src/com/google/javascript/jscomp/InlineObjectLiterals.java
Closure-50
private Node tryFoldArrayJoin(Node n) { Node callTarget = n.getFirstChild(); if (callTarget == null || !NodeUtil.isGetProp(callTarget)) { return n; } Node right = callTarget.getNext(); if (right != null) { if (!NodeUtil.isImmutableValue(right)) { return n; } } Node arrayNode = callTarget.getFirstChild(); Node functionName = arrayNode.getNext(); if ((arrayNode.getType() != Token.ARRAYLIT) || !functionName.getString().equals("join")) { return n; } // "," is the default, it doesn't need to be explicit String joinString = (right == null) ? "," : NodeUtil.getStringValue(right); List<Node> arrayFoldedChildren = Lists.newLinkedList(); StringBuilder sb = null; int foldedSize = 0; Node prev = null; Node elem = arrayNode.getFirstChild(); // Merges adjacent String nodes. while (elem != null) { if (NodeUtil.isImmutableValue(elem) || elem.getType() == Token.EMPTY) { if (sb == null) { sb = new StringBuilder(); } else { sb.append(joinString); } sb.append(NodeUtil.getArrayElementStringValue(elem)); } else { if (sb != null) { Preconditions.checkNotNull(prev); // + 2 for the quotes. foldedSize += sb.length() + 2; arrayFoldedChildren.add( Node.newString(sb.toString()).copyInformationFrom(prev)); sb = null; } foldedSize += InlineCostEstimator.getCost(elem); arrayFoldedChildren.add(elem); } prev = elem; elem = elem.getNext(); } if (sb != null) { Preconditions.checkNotNull(prev); // + 2 for the quotes. foldedSize += sb.length() + 2; arrayFoldedChildren.add( Node.newString(sb.toString()).copyInformationFrom(prev)); } // one for each comma. foldedSize += arrayFoldedChildren.size() - 1; int originalSize = InlineCostEstimator.getCost(n); switch (arrayFoldedChildren.size()) { case 0: Node emptyStringNode = Node.newString(""); n.getParent().replaceChild(n, emptyStringNode); reportCodeChange(); return emptyStringNode; case 1: Node foldedStringNode = arrayFoldedChildren.remove(0); if (foldedSize > originalSize) { return n; } arrayNode.detachChildren(); if (foldedStringNode.getType() != Token.STRING) { // If the Node is not a string literal, ensure that // it is coerced to a string. Node replacement = new Node(Token.ADD, Node.newString("").copyInformationFrom(n), foldedStringNode); foldedStringNode = replacement; } n.getParent().replaceChild(n, foldedStringNode); reportCodeChange(); return foldedStringNode; default: // No folding could actually be performed. if (arrayFoldedChildren.size() == arrayNode.getChildCount()) { return n; } int kJoinOverhead = "[].join()".length(); foldedSize += kJoinOverhead; foldedSize += (right != null) ? InlineCostEstimator.getCost(right) : 0; if (foldedSize > originalSize) { return n; } arrayNode.detachChildren(); for (Node node : arrayFoldedChildren) { arrayNode.addChildToBack(node); } reportCodeChange(); break; } return n; } private Node tryFoldArrayJoin(Node n) { Node callTarget = n.getFirstChild(); if (callTarget == null || !NodeUtil.isGetProp(callTarget)) { return n; } Node right = callTarget.getNext(); if (right != null) { if (right.getNext() != null || !NodeUtil.isImmutableValue(right)) { return n; } } Node arrayNode = callTarget.getFirstChild(); Node functionName = arrayNode.getNext(); if ((arrayNode.getType() != Token.ARRAYLIT) || !functionName.getString().equals("join")) { return n; } if (right != null && right.getType() == Token.STRING && ",".equals(right.getString())) { // "," is the default, it doesn't need to be explicit n.removeChild(right); reportCodeChange(); } String joinString = (right == null) ? "," : NodeUtil.getStringValue(right); List<Node> arrayFoldedChildren = Lists.newLinkedList(); StringBuilder sb = null; int foldedSize = 0; Node prev = null; Node elem = arrayNode.getFirstChild(); // Merges adjacent String nodes. while (elem != null) { if (NodeUtil.isImmutableValue(elem) || elem.getType() == Token.EMPTY) { if (sb == null) { sb = new StringBuilder(); } else { sb.append(joinString); } sb.append(NodeUtil.getArrayElementStringValue(elem)); } else { if (sb != null) { Preconditions.checkNotNull(prev); // + 2 for the quotes. foldedSize += sb.length() + 2; arrayFoldedChildren.add( Node.newString(sb.toString()).copyInformationFrom(prev)); sb = null; } foldedSize += InlineCostEstimator.getCost(elem); arrayFoldedChildren.add(elem); } prev = elem; elem = elem.getNext(); } if (sb != null) { Preconditions.checkNotNull(prev); // + 2 for the quotes. foldedSize += sb.length() + 2; arrayFoldedChildren.add( Node.newString(sb.toString()).copyInformationFrom(prev)); } // one for each comma. foldedSize += arrayFoldedChildren.size() - 1; int originalSize = InlineCostEstimator.getCost(n); switch (arrayFoldedChildren.size()) { case 0: Node emptyStringNode = Node.newString(""); n.getParent().replaceChild(n, emptyStringNode); reportCodeChange(); return emptyStringNode; case 1: Node foldedStringNode = arrayFoldedChildren.remove(0); if (foldedSize > originalSize) { return n; } arrayNode.detachChildren(); if (foldedStringNode.getType() != Token.STRING) { // If the Node is not a string literal, ensure that // it is coerced to a string. Node replacement = new Node(Token.ADD, Node.newString("").copyInformationFrom(n), foldedStringNode); foldedStringNode = replacement; } n.getParent().replaceChild(n, foldedStringNode); reportCodeChange(); return foldedStringNode; default: // No folding could actually be performed. if (arrayFoldedChildren.size() == arrayNode.getChildCount()) { return n; } int kJoinOverhead = "[].join()".length(); foldedSize += kJoinOverhead; foldedSize += (right != null) ? InlineCostEstimator.getCost(right) : 0; if (foldedSize > originalSize) { return n; } arrayNode.detachChildren(); for (Node node : arrayFoldedChildren) { arrayNode.addChildToBack(node); } reportCodeChange(); break; } return n; }
src/com/google/javascript/jscomp/PeepholeReplaceKnownMethods.java
Closure-51
void addNumber(double x) { // This is not pretty printing. This is to prevent misparsing of x- -4 as // x--4 (which is a syntax error). char prev = getLastChar(); if (x < 0 && prev == '-') { add(" "); } if ((long) x == x) { long value = (long) x; long mantissa = value; int exp = 0; if (Math.abs(x) >= 100) { while (mantissa / 10 * Math.pow(10, exp + 1) == value) { mantissa /= 10; exp++; } } if (exp > 2) { add(Long.toString(mantissa) + "E" + Integer.toString(exp)); } else { add(Long.toString(value)); } } else { add(String.valueOf(x)); } } void addNumber(double x) { // This is not pretty printing. This is to prevent misparsing of x- -4 as // x--4 (which is a syntax error). char prev = getLastChar(); if (x < 0 && prev == '-') { add(" "); } if ((long) x == x && !isNegativeZero(x)) { long value = (long) x; long mantissa = value; int exp = 0; if (Math.abs(x) >= 100) { while (mantissa / 10 * Math.pow(10, exp + 1) == value) { mantissa /= 10; exp++; } } if (exp > 2) { add(Long.toString(mantissa) + "E" + Integer.toString(exp)); } else { add(Long.toString(value)); } } else { add(String.valueOf(x)); } }
src/com/google/javascript/jscomp/CodeConsumer.java
Closure-52
static boolean isSimpleNumber(String s) { int len = s.length(); for (int index = 0; index < len; index++) { char c = s.charAt(index); if (c < '0' || c > '9') { return false; } } return len > 0; } static boolean isSimpleNumber(String s) { int len = s.length(); for (int index = 0; index < len; index++) { char c = s.charAt(index); if (c < '0' || c > '9') { return false; } } return len > 0 && s.charAt(0) != '0'; }
src/com/google/javascript/jscomp/CodeGenerator.java
Closure-53
private void replaceAssignmentExpression(Var v, Reference ref, Map<String, String> varmap) { // Compute all of the assignments necessary List<Node> nodes = Lists.newArrayList(); Node val = ref.getAssignedValue(); blacklistVarReferencesInTree(val, v.scope); Preconditions.checkState(val.getType() == Token.OBJECTLIT); Set<String> all = Sets.newLinkedHashSet(varmap.keySet()); for (Node key = val.getFirstChild(); key != null; key = key.getNext()) { String var = key.getString(); Node value = key.removeFirstChild(); // TODO(user): Copy type information. nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), value)); all.remove(var); } // TODO(user): Better source information. for (String var : all) { nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), NodeUtil.newUndefinedNode(null))); } Node replacement; // All assignments evaluate to true, so make sure that the // expr statement evaluates to true in case it matters. nodes.add(new Node(Token.TRUE)); // Join these using COMMA. A COMMA node must have 2 children, so we // create a tree. In the tree the first child be the COMMA to match // the parser, otherwise tree equality tests fail. nodes = Lists.reverse(nodes); replacement = new Node(Token.COMMA); Node cur = replacement; int i; for (i = 0; i < nodes.size() - 2; i++) { cur.addChildToFront(nodes.get(i)); Node t = new Node(Token.COMMA); cur.addChildToFront(t); cur = t; } cur.addChildToFront(nodes.get(i)); cur.addChildToFront(nodes.get(i + 1)); Node replace = ref.getParent(); replacement.copyInformationFromForTree(replace); if (replace.getType() == Token.VAR) { replace.getParent().replaceChild( replace, NodeUtil.newExpr(replacement)); } else { replace.getParent().replaceChild(replace, replacement); } } private void replaceAssignmentExpression(Var v, Reference ref, Map<String, String> varmap) { // Compute all of the assignments necessary List<Node> nodes = Lists.newArrayList(); Node val = ref.getAssignedValue(); blacklistVarReferencesInTree(val, v.scope); Preconditions.checkState(val.getType() == Token.OBJECTLIT); Set<String> all = Sets.newLinkedHashSet(varmap.keySet()); for (Node key = val.getFirstChild(); key != null; key = key.getNext()) { String var = key.getString(); Node value = key.removeFirstChild(); // TODO(user): Copy type information. nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), value)); all.remove(var); } // TODO(user): Better source information. for (String var : all) { nodes.add( new Node(Token.ASSIGN, Node.newString(Token.NAME, varmap.get(var)), NodeUtil.newUndefinedNode(null))); } Node replacement; if (nodes.isEmpty()) { replacement = new Node(Token.TRUE); } else { // All assignments evaluate to true, so make sure that the // expr statement evaluates to true in case it matters. nodes.add(new Node(Token.TRUE)); // Join these using COMMA. A COMMA node must have 2 children, so we // create a tree. In the tree the first child be the COMMA to match // the parser, otherwise tree equality tests fail. nodes = Lists.reverse(nodes); replacement = new Node(Token.COMMA); Node cur = replacement; int i; for (i = 0; i < nodes.size() - 2; i++) { cur.addChildToFront(nodes.get(i)); Node t = new Node(Token.COMMA); cur.addChildToFront(t); cur = t; } cur.addChildToFront(nodes.get(i)); cur.addChildToFront(nodes.get(i + 1)); } Node replace = ref.getParent(); replacement.copyInformationFromForTree(replace); if (replace.getType() == Token.VAR) { replace.getParent().replaceChild( replace, NodeUtil.newExpr(replacement)); } else { replace.getParent().replaceChild(replace, replacement); } }
src/com/google/javascript/jscomp/InlineObjectLiterals.java
Closure-55
private static boolean isReduceableFunctionExpression(Node n) { return NodeUtil.isFunctionExpression(n); } private static boolean isReduceableFunctionExpression(Node n) { return NodeUtil.isFunctionExpression(n) && !NodeUtil.isGetOrSetKey(n.getParent()); }
src/com/google/javascript/jscomp/FunctionRewriter.java
Closure-56
public String getLine(int lineNumber) { String js = ""; try { // NOTE(nicksantos): Right now, this is optimized for few warnings. // This is probably the right trade-off, but will be slow if there // are lots of warnings in one file. js = getCode(); } catch (IOException e) { return null; } int pos = 0; int startLine = 1; // If we've saved a previous offset and it's for a line less than the // one we're searching for, then start at that point. if (lineNumber >= lastLine) { pos = lastOffset; startLine = lastLine; } for (int n = startLine; n < lineNumber; n++) { int nextpos = js.indexOf('\n', pos); if (nextpos == -1) { return null; } pos = nextpos + 1; } // Remember this offset for the next search we do. lastOffset = pos; lastLine = lineNumber; if (js.indexOf('\n', pos) == -1) { // If next new line cannot be found, there are two cases // 1. pos already reaches the end of file, then null should be returned // 2. otherwise, return the contents between pos and the end of file. return null; } else { return js.substring(pos, js.indexOf('\n', pos)); } } public String getLine(int lineNumber) { String js = ""; try { // NOTE(nicksantos): Right now, this is optimized for few warnings. // This is probably the right trade-off, but will be slow if there // are lots of warnings in one file. js = getCode(); } catch (IOException e) { return null; } int pos = 0; int startLine = 1; // If we've saved a previous offset and it's for a line less than the // one we're searching for, then start at that point. if (lineNumber >= lastLine) { pos = lastOffset; startLine = lastLine; } for (int n = startLine; n < lineNumber; n++) { int nextpos = js.indexOf('\n', pos); if (nextpos == -1) { return null; } pos = nextpos + 1; } // Remember this offset for the next search we do. lastOffset = pos; lastLine = lineNumber; if (js.indexOf('\n', pos) == -1) { // If next new line cannot be found, there are two cases // 1. pos already reaches the end of file, then null should be returned // 2. otherwise, return the contents between pos and the end of file. if (pos >= js.length()) { return null; } else { return js.substring(pos, js.length()); } } else { return js.substring(pos, js.indexOf('\n', pos)); } }
src/com/google/javascript/jscomp/SourceFile.java
Closure-57
private static String extractClassNameIfGoog(Node node, Node parent, String functionName){ String className = null; if (NodeUtil.isExprCall(parent)) { Node callee = node.getFirstChild(); if (callee != null && callee.getType() == Token.GETPROP) { String qualifiedName = callee.getQualifiedName(); if (functionName.equals(qualifiedName)) { Node target = callee.getNext(); if (target != null) { className = target.getString(); } } } } return className; } private static String extractClassNameIfGoog(Node node, Node parent, String functionName){ String className = null; if (NodeUtil.isExprCall(parent)) { Node callee = node.getFirstChild(); if (callee != null && callee.getType() == Token.GETPROP) { String qualifiedName = callee.getQualifiedName(); if (functionName.equals(qualifiedName)) { Node target = callee.getNext(); if (target != null && target.getType() == Token.STRING) { className = target.getString(); } } } } return className; }
src/com/google/javascript/jscomp/ClosureCodingConvention.java
Closure-58
private void computeGenKill(Node n, BitSet gen, BitSet kill, boolean conditional) { switch (n.getType()) { case Token.SCRIPT: case Token.BLOCK: case Token.FUNCTION: return; case Token.WHILE: case Token.DO: case Token.IF: computeGenKill(NodeUtil.getConditionExpression(n), gen, kill, conditional); return; case Token.FOR: if (!NodeUtil.isForIn(n)) { computeGenKill(NodeUtil.getConditionExpression(n), gen, kill, conditional); } else { // for(x in y) {...} Node lhs = n.getFirstChild(); Node rhs = lhs.getNext(); if (NodeUtil.isVar(lhs)) { // for(var x in y) {...} lhs = lhs.getLastChild(); } addToSetIfLocal(lhs, kill); addToSetIfLocal(lhs, gen); computeGenKill(rhs, gen, kill, conditional); } return; case Token.VAR: for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (c.hasChildren()) { computeGenKill(c.getFirstChild(), gen, kill, conditional); if (!conditional) { addToSetIfLocal(c, kill); } } } return; case Token.AND: case Token.OR: computeGenKill(n.getFirstChild(), gen, kill, conditional); // May short circuit. computeGenKill(n.getLastChild(), gen, kill, true); return; case Token.HOOK: computeGenKill(n.getFirstChild(), gen, kill, conditional); // Assume both sides are conditional. computeGenKill(n.getFirstChild().getNext(), gen, kill, true); computeGenKill(n.getLastChild(), gen, kill, true); return; case Token.NAME: if (isArgumentsName(n)) { markAllParametersEscaped(); } else { addToSetIfLocal(n, gen); } return; default: if (NodeUtil.isAssignmentOp(n) && NodeUtil.isName(n.getFirstChild())) { Node lhs = n.getFirstChild(); if (!conditional) { addToSetIfLocal(lhs, kill); } if (!NodeUtil.isAssign(n)) { // assignments such as a += 1 reads a. addToSetIfLocal(lhs, gen); } computeGenKill(lhs.getNext(), gen, kill, conditional); } else { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { computeGenKill(c, gen, kill, conditional); } } return; } } private void computeGenKill(Node n, BitSet gen, BitSet kill, boolean conditional) { switch (n.getType()) { case Token.SCRIPT: case Token.BLOCK: case Token.FUNCTION: return; case Token.WHILE: case Token.DO: case Token.IF: computeGenKill(NodeUtil.getConditionExpression(n), gen, kill, conditional); return; case Token.FOR: if (!NodeUtil.isForIn(n)) { computeGenKill(NodeUtil.getConditionExpression(n), gen, kill, conditional); } else { // for(x in y) {...} Node lhs = n.getFirstChild(); Node rhs = lhs.getNext(); if (NodeUtil.isVar(lhs)) { // for(var x in y) {...} lhs = lhs.getLastChild(); } if (NodeUtil.isName(lhs)) { addToSetIfLocal(lhs, kill); addToSetIfLocal(lhs, gen); } else { computeGenKill(lhs, gen, kill, conditional); } computeGenKill(rhs, gen, kill, conditional); } return; case Token.VAR: for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { if (c.hasChildren()) { computeGenKill(c.getFirstChild(), gen, kill, conditional); if (!conditional) { addToSetIfLocal(c, kill); } } } return; case Token.AND: case Token.OR: computeGenKill(n.getFirstChild(), gen, kill, conditional); // May short circuit. computeGenKill(n.getLastChild(), gen, kill, true); return; case Token.HOOK: computeGenKill(n.getFirstChild(), gen, kill, conditional); // Assume both sides are conditional. computeGenKill(n.getFirstChild().getNext(), gen, kill, true); computeGenKill(n.getLastChild(), gen, kill, true); return; case Token.NAME: if (isArgumentsName(n)) { markAllParametersEscaped(); } else { addToSetIfLocal(n, gen); } return; default: if (NodeUtil.isAssignmentOp(n) && NodeUtil.isName(n.getFirstChild())) { Node lhs = n.getFirstChild(); if (!conditional) { addToSetIfLocal(lhs, kill); } if (!NodeUtil.isAssign(n)) { // assignments such as a += 1 reads a. addToSetIfLocal(lhs, gen); } computeGenKill(lhs.getNext(), gen, kill, conditional); } else { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { computeGenKill(c, gen, kill, conditional); } } return; } }
src/com/google/javascript/jscomp/LiveVariablesAnalysis.java
Closure-59
public void initOptions(CompilerOptions options) { this.options = options; if (errorManager == null) { if (outStream == null) { setErrorManager( new LoggerErrorManager(createMessageFormatter(), logger)); } else { PrintStreamErrorManager printer = new PrintStreamErrorManager(createMessageFormatter(), outStream); printer.setSummaryDetailLevel(options.summaryDetailLevel); setErrorManager(printer); } } // DiagnosticGroups override the plain checkTypes option. if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } else if (!options.checkTypes) { // If DiagnosticGroups did not override the plain checkTypes // option, and checkTypes is enabled, then turn off the // parser type warnings. options.setWarningLevel( DiagnosticGroup.forType( RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.OFF); } if (options.checkGlobalThisLevel.isOn()) { options.setWarningLevel( DiagnosticGroups.GLOBAL_THIS, options.checkGlobalThisLevel); } if (options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT) { options.setWarningLevel( DiagnosticGroups.ES5_STRICT, CheckLevel.ERROR); } // Initialize the warnings guard. List<WarningsGuard> guards = Lists.newArrayList(); guards.add( new SuppressDocWarningsGuard( getDiagnosticGroups().getRegisteredGroups())); guards.add(options.getWarningsGuard()); ComposeWarningsGuard composedGuards = new ComposeWarningsGuard(guards); // All passes must run the variable check. This synthesizes // variables later so that the compiler doesn't crash. It also // checks the externs file for validity. If you don't want to warn // about missing variable declarations, we shut that specific // error off. if (!options.checkSymbols && !composedGuards.enables(DiagnosticGroups.CHECK_VARIABLES)) { composedGuards.addGuard(new DiagnosticGroupWarningsGuard( DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF)); } this.warningsGuard = composedGuards; } public void initOptions(CompilerOptions options) { this.options = options; if (errorManager == null) { if (outStream == null) { setErrorManager( new LoggerErrorManager(createMessageFormatter(), logger)); } else { PrintStreamErrorManager printer = new PrintStreamErrorManager(createMessageFormatter(), outStream); printer.setSummaryDetailLevel(options.summaryDetailLevel); setErrorManager(printer); } } // DiagnosticGroups override the plain checkTypes option. if (options.enables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = true; } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) { options.checkTypes = false; } else if (!options.checkTypes) { // If DiagnosticGroups did not override the plain checkTypes // option, and checkTypes is enabled, then turn off the // parser type warnings. options.setWarningLevel( DiagnosticGroup.forType( RhinoErrorReporter.TYPE_PARSE_ERROR), CheckLevel.OFF); } if (options.checkGlobalThisLevel.isOn() && !options.disables(DiagnosticGroups.GLOBAL_THIS)) { options.setWarningLevel( DiagnosticGroups.GLOBAL_THIS, options.checkGlobalThisLevel); } if (options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT) { options.setWarningLevel( DiagnosticGroups.ES5_STRICT, CheckLevel.ERROR); } // Initialize the warnings guard. List<WarningsGuard> guards = Lists.newArrayList(); guards.add( new SuppressDocWarningsGuard( getDiagnosticGroups().getRegisteredGroups())); guards.add(options.getWarningsGuard()); ComposeWarningsGuard composedGuards = new ComposeWarningsGuard(guards); // All passes must run the variable check. This synthesizes // variables later so that the compiler doesn't crash. It also // checks the externs file for validity. If you don't want to warn // about missing variable declarations, we shut that specific // error off. if (!options.checkSymbols && !composedGuards.enables(DiagnosticGroups.CHECK_VARIABLES)) { composedGuards.addGuard(new DiagnosticGroupWarningsGuard( DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF)); } this.warningsGuard = composedGuards; }
src/com/google/javascript/jscomp/Compiler.java
Closure-61
static boolean functionCallHasSideEffects( Node callNode, @Nullable AbstractCompiler compiler) { if (callNode.getType() != Token.CALL) { throw new IllegalStateException( "Expected CALL node, got " + Token.name(callNode.getType())); } if (callNode.isNoSideEffectsCall()) { return false; } Node nameNode = callNode.getFirstChild(); // Built-in functions with no side effects. if (nameNode.getType() == Token.NAME) { String name = nameNode.getString(); if (BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS.contains(name)) { return false; } } else if (nameNode.getType() == Token.GETPROP) { if (callNode.hasOneChild() && OBJECT_METHODS_WITHOUT_SIDEEFFECTS.contains( nameNode.getLastChild().getString())) { return false; } if (callNode.isOnlyModifiesThisCall() && evaluatesToLocalValue(nameNode.getFirstChild())) { return false; } // Functions in the "Math" namespace have no side effects. if (compiler != null && !compiler.hasRegExpGlobalReferences()) { if (nameNode.getFirstChild().getType() == Token.REGEXP && REGEXP_METHODS.contains(nameNode.getLastChild().getString())) { return false; } else if (nameNode.getFirstChild().getType() == Token.STRING && STRING_REGEXP_METHODS.contains( nameNode.getLastChild().getString())) { Node param = nameNode.getNext(); if (param != null && (param.getType() == Token.STRING || param.getType() == Token.REGEXP)) return false; } } } return true; } static boolean functionCallHasSideEffects( Node callNode, @Nullable AbstractCompiler compiler) { if (callNode.getType() != Token.CALL) { throw new IllegalStateException( "Expected CALL node, got " + Token.name(callNode.getType())); } if (callNode.isNoSideEffectsCall()) { return false; } Node nameNode = callNode.getFirstChild(); // Built-in functions with no side effects. if (nameNode.getType() == Token.NAME) { String name = nameNode.getString(); if (BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS.contains(name)) { return false; } } else if (nameNode.getType() == Token.GETPROP) { if (callNode.hasOneChild() && OBJECT_METHODS_WITHOUT_SIDEEFFECTS.contains( nameNode.getLastChild().getString())) { return false; } if (callNode.isOnlyModifiesThisCall() && evaluatesToLocalValue(nameNode.getFirstChild())) { return false; } // Functions in the "Math" namespace have no side effects. if (nameNode.getFirstChild().getType() == Token.NAME) { String namespaceName = nameNode.getFirstChild().getString(); if (namespaceName.equals("Math")) { return false; } } if (compiler != null && !compiler.hasRegExpGlobalReferences()) { if (nameNode.getFirstChild().getType() == Token.REGEXP && REGEXP_METHODS.contains(nameNode.getLastChild().getString())) { return false; } else if (nameNode.getFirstChild().getType() == Token.STRING && STRING_REGEXP_METHODS.contains( nameNode.getLastChild().getString())) { Node param = nameNode.getNext(); if (param != null && (param.getType() == Token.STRING || param.getType() == Token.REGEXP)) return false; } } } return true; }
src/com/google/javascript/jscomp/NodeUtil.java
Closure-62
private String format(JSError error, boolean warning) { // extract source excerpt SourceExcerptProvider source = getSource(); String sourceExcerpt = source == null ? null : excerpt.get( source, error.sourceName, error.lineNumber, excerptFormatter); // formatting the message StringBuilder b = new StringBuilder(); if (error.sourceName != null) { b.append(error.sourceName); if (error.lineNumber > 0) { b.append(':'); b.append(error.lineNumber); } b.append(": "); } b.append(getLevelName(warning ? CheckLevel.WARNING : CheckLevel.ERROR)); b.append(" - "); b.append(error.description); b.append('\n'); if (sourceExcerpt != null) { b.append(sourceExcerpt); b.append('\n'); int charno = error.getCharno(); // padding equal to the excerpt and arrow at the end // charno == sourceExpert.length() means something is missing // at the end of the line if (excerpt.equals(LINE) && 0 <= charno && charno < sourceExcerpt.length()) { for (int i = 0; i < charno; i++) { char c = sourceExcerpt.charAt(i); if (Character.isWhitespace(c)) { b.append(c); } else { b.append(' '); } } b.append("^\n"); } } return b.toString(); } private String format(JSError error, boolean warning) { // extract source excerpt SourceExcerptProvider source = getSource(); String sourceExcerpt = source == null ? null : excerpt.get( source, error.sourceName, error.lineNumber, excerptFormatter); // formatting the message StringBuilder b = new StringBuilder(); if (error.sourceName != null) { b.append(error.sourceName); if (error.lineNumber > 0) { b.append(':'); b.append(error.lineNumber); } b.append(": "); } b.append(getLevelName(warning ? CheckLevel.WARNING : CheckLevel.ERROR)); b.append(" - "); b.append(error.description); b.append('\n'); if (sourceExcerpt != null) { b.append(sourceExcerpt); b.append('\n'); int charno = error.getCharno(); // padding equal to the excerpt and arrow at the end // charno == sourceExpert.length() means something is missing // at the end of the line if (excerpt.equals(LINE) && 0 <= charno && charno <= sourceExcerpt.length()) { for (int i = 0; i < charno; i++) { char c = sourceExcerpt.charAt(i); if (Character.isWhitespace(c)) { b.append(c); } else { b.append(' '); } } b.append("^\n"); } } return b.toString(); }
src/com/google/javascript/jscomp/LightweightMessageFormatter.java
Closure-65
static String strEscape(String s, char quote, String doublequoteEscape, String singlequoteEscape, String backslashEscape, CharsetEncoder outputCharsetEncoder) { StringBuilder sb = new StringBuilder(s.length() + 2); sb.append(quote); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\0': sb.append("\\0"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\\': sb.append(backslashEscape); break; case '\"': sb.append(doublequoteEscape); break; case '\'': sb.append(singlequoteEscape); break; case '>': // Break --> into --\> or ]]> into ]]\> if (i >= 2 && ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') || (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) { sb.append("\\>"); } else { sb.append(c); } break; case '<': // Break </script into <\/script final String END_SCRIPT = "/script"; // Break <!-- into <\!-- final String START_COMMENT = "!--"; if (s.regionMatches(true, i + 1, END_SCRIPT, 0, END_SCRIPT.length())) { sb.append("<\\"); } else if (s.regionMatches(false, i + 1, START_COMMENT, 0, START_COMMENT.length())) { sb.append("<\\"); } else { sb.append(c); } break; default: // If we're given an outputCharsetEncoder, then check if the // character can be represented in this character set. if (outputCharsetEncoder != null) { if (outputCharsetEncoder.canEncode(c)) { sb.append(c); } else { // Unicode-escape the character. appendHexJavaScriptRepresentation(sb, c); } } else { // No charsetEncoder provided - pass straight latin characters // through, and escape the rest. Doing the explicit character // check is measurably faster than using the CharsetEncoder. if (c > 0x1f && c < 0x7f) { sb.append(c); } else { // Other characters can be misinterpreted by some js parsers, // or perhaps mangled by proxies along the way, // so we play it safe and unicode escape them. appendHexJavaScriptRepresentation(sb, c); } } } } sb.append(quote); return sb.toString(); } static String strEscape(String s, char quote, String doublequoteEscape, String singlequoteEscape, String backslashEscape, CharsetEncoder outputCharsetEncoder) { StringBuilder sb = new StringBuilder(s.length() + 2); sb.append(quote); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\0': sb.append("\\000"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\\': sb.append(backslashEscape); break; case '\"': sb.append(doublequoteEscape); break; case '\'': sb.append(singlequoteEscape); break; case '>': // Break --> into --\> or ]]> into ]]\> if (i >= 2 && ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') || (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) { sb.append("\\>"); } else { sb.append(c); } break; case '<': // Break </script into <\/script final String END_SCRIPT = "/script"; // Break <!-- into <\!-- final String START_COMMENT = "!--"; if (s.regionMatches(true, i + 1, END_SCRIPT, 0, END_SCRIPT.length())) { sb.append("<\\"); } else if (s.regionMatches(false, i + 1, START_COMMENT, 0, START_COMMENT.length())) { sb.append("<\\"); } else { sb.append(c); } break; default: // If we're given an outputCharsetEncoder, then check if the // character can be represented in this character set. if (outputCharsetEncoder != null) { if (outputCharsetEncoder.canEncode(c)) { sb.append(c); } else { // Unicode-escape the character. appendHexJavaScriptRepresentation(sb, c); } } else { // No charsetEncoder provided - pass straight latin characters // through, and escape the rest. Doing the explicit character // check is measurably faster than using the CharsetEncoder. if (c > 0x1f && c < 0x7f) { sb.append(c); } else { // Other characters can be misinterpreted by some js parsers, // or perhaps mangled by proxies along the way, // so we play it safe and unicode escape them. appendHexJavaScriptRepresentation(sb, c); } } } } sb.append(quote); return sb.toString(); }
src/com/google/javascript/jscomp/CodeGenerator.java
Closure-66
public void visit(NodeTraversal t, Node n, Node parent) { JSType childType; JSType leftType, rightType; Node left, right; // To be explicitly set to false if the node is not typeable. boolean typeable = true; switch (n.getType()) { case Token.NAME: typeable = visitName(t, n, parent); break; case Token.LP: // If this is under a FUNCTION node, it is a parameter list and can be // ignored here. if (parent.getType() != Token.FUNCTION) { ensureTyped(t, n, getJSType(n.getFirstChild())); } else { typeable = false; } break; case Token.COMMA: ensureTyped(t, n, getJSType(n.getLastChild())); break; case Token.TRUE: case Token.FALSE: ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.THIS: ensureTyped(t, n, t.getScope().getTypeOfThis()); break; case Token.REF_SPECIAL: ensureTyped(t, n); break; case Token.GET_REF: ensureTyped(t, n, getJSType(n.getFirstChild())); break; case Token.NULL: ensureTyped(t, n, NULL_TYPE); break; case Token.NUMBER: ensureTyped(t, n, NUMBER_TYPE); break; case Token.STRING: // Object literal keys are handled with OBJECTLIT if (!NodeUtil.isObjectLitKey(n, n.getParent())) { ensureTyped(t, n, STRING_TYPE); // Object literal keys are not typeable } break; case Token.GET: case Token.SET: // Object literal keys are handled with OBJECTLIT break; case Token.ARRAYLIT: ensureTyped(t, n, ARRAY_TYPE); break; case Token.REGEXP: ensureTyped(t, n, REGEXP_TYPE); break; case Token.GETPROP: visitGetProp(t, n, parent); typeable = !(parent.getType() == Token.ASSIGN && parent.getFirstChild() == n); break; case Token.GETELEM: visitGetElem(t, n); // The type of GETELEM is always unknown, so no point counting that. // If that unknown leaks elsewhere (say by an assignment to another // variable), then it will be counted. typeable = false; break; case Token.VAR: visitVar(t, n); typeable = false; break; case Token.NEW: visitNew(t, n); typeable = true; break; case Token.CALL: visitCall(t, n); typeable = !NodeUtil.isExpressionNode(parent); break; case Token.RETURN: visitReturn(t, n); typeable = false; break; case Token.DEC: case Token.INC: left = n.getFirstChild(); validator.expectNumber( t, left, getJSType(left), "increment/decrement"); ensureTyped(t, n, NUMBER_TYPE); break; case Token.NOT: ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.VOID: ensureTyped(t, n, VOID_TYPE); break; case Token.TYPEOF: ensureTyped(t, n, STRING_TYPE); break; case Token.BITNOT: childType = getJSType(n.getFirstChild()); if (!childType.matchesInt32Context()) { report(t, n, BIT_OPERATION, NodeUtil.opToStr(n.getType()), childType.toString()); } ensureTyped(t, n, NUMBER_TYPE); break; case Token.POS: case Token.NEG: left = n.getFirstChild(); validator.expectNumber(t, left, getJSType(left), "sign operator"); ensureTyped(t, n, NUMBER_TYPE); break; case Token.EQ: case Token.NE: { leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined(); JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined(); TernaryValue result = leftTypeRestricted.testForEquality(rightTypeRestricted); if (result != TernaryValue.UNKNOWN) { if (n.getType() == Token.NE) { result = result.not(); } report(t, n, DETERMINISTIC_TEST, leftType.toString(), rightType.toString(), result.toString()); } ensureTyped(t, n, BOOLEAN_TYPE); break; } case Token.SHEQ: case Token.SHNE: { leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined(); JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined(); if (!leftTypeRestricted.canTestForShallowEqualityWith( rightTypeRestricted)) { report(t, n, DETERMINISTIC_TEST_NO_RESULT, leftType.toString(), rightType.toString()); } ensureTyped(t, n, BOOLEAN_TYPE); break; } case Token.LT: case Token.LE: case Token.GT: case Token.GE: leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); if (rightType.isNumber()) { validator.expectNumber( t, n, leftType, "left side of numeric comparison"); } else if (leftType.isNumber()) { validator.expectNumber( t, n, rightType, "right side of numeric comparison"); } else if (leftType.matchesNumberContext() && rightType.matchesNumberContext()) { // OK. } else { // Whether the comparison is numeric will be determined at runtime // each time the expression is evaluated. Regardless, both operands // should match a string context. String message = "left side of comparison"; validator.expectString(t, n, leftType, message); validator.expectNotNullOrUndefined( t, n, leftType, message, getNativeType(STRING_TYPE)); message = "right side of comparison"; validator.expectString(t, n, rightType, message); validator.expectNotNullOrUndefined( t, n, rightType, message, getNativeType(STRING_TYPE)); } ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.IN: left = n.getFirstChild(); right = n.getLastChild(); leftType = getJSType(left); rightType = getJSType(right); validator.expectObject(t, n, rightType, "'in' requires an object"); validator.expectString(t, left, leftType, "left side of 'in'"); ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.INSTANCEOF: left = n.getFirstChild(); right = n.getLastChild(); leftType = getJSType(left); rightType = getJSType(right).restrictByNotNullOrUndefined(); validator.expectAnyObject( t, left, leftType, "deterministic instanceof yields false"); validator.expectActualObject( t, right, rightType, "instanceof requires an object"); ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.ASSIGN: visitAssign(t, n); typeable = false; break; case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.ASSIGN_URSH: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITOR: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITAND: case Token.ASSIGN_SUB: case Token.ASSIGN_ADD: case Token.ASSIGN_MUL: case Token.LSH: case Token.RSH: case Token.URSH: case Token.DIV: case Token.MOD: case Token.BITOR: case Token.BITXOR: case Token.BITAND: case Token.SUB: case Token.ADD: case Token.MUL: visitBinaryOperator(n.getType(), t, n); break; case Token.DELPROP: if (!isReference(n.getFirstChild())) { report(t, n, BAD_DELETE); } ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.CASE: JSType switchType = getJSType(parent.getFirstChild()); JSType caseType = getJSType(n.getFirstChild()); validator.expectSwitchMatchesCase(t, n, switchType, caseType); typeable = false; break; case Token.WITH: { Node child = n.getFirstChild(); childType = getJSType(child); validator.expectObject( t, child, childType, "with requires an object"); typeable = false; break; } case Token.FUNCTION: visitFunction(t, n); break; // These nodes have no interesting type behavior. case Token.LABEL: case Token.LABEL_NAME: case Token.SWITCH: case Token.BREAK: case Token.CATCH: case Token.TRY: case Token.SCRIPT: case Token.EXPR_RESULT: case Token.BLOCK: case Token.EMPTY: case Token.DEFAULT: case Token.CONTINUE: case Token.DEBUGGER: case Token.THROW: typeable = false; break; // These nodes require data flow analysis. case Token.DO: case Token.FOR: case Token.IF: case Token.WHILE: typeable = false; break; // These nodes are typed during the type inference. case Token.AND: case Token.HOOK: case Token.OBJECTLIT: case Token.OR: if (n.getJSType() != null) { // If we didn't run type inference. ensureTyped(t, n); } else { // If this is an enum, then give that type to the objectlit as well. if ((n.getType() == Token.OBJECTLIT) && (parent.getJSType() instanceof EnumType)) { ensureTyped(t, n, parent.getJSType()); } else { ensureTyped(t, n); } } if (n.getType() == Token.OBJECTLIT) { for (Node key : n.children()) { visitObjLitKey(t, key, n); } } break; default: report(t, n, UNEXPECTED_TOKEN, Token.name(n.getType())); ensureTyped(t, n); break; } // Don't count externs since the user's code may not even use that part. typeable = typeable && !inExterns; if (typeable) { doPercentTypedAccounting(t, n); } checkNoTypeCheckSection(n, false); } public void visit(NodeTraversal t, Node n, Node parent) { JSType childType; JSType leftType, rightType; Node left, right; // To be explicitly set to false if the node is not typeable. boolean typeable = true; switch (n.getType()) { case Token.NAME: typeable = visitName(t, n, parent); break; case Token.LP: // If this is under a FUNCTION node, it is a parameter list and can be // ignored here. if (parent.getType() != Token.FUNCTION) { ensureTyped(t, n, getJSType(n.getFirstChild())); } else { typeable = false; } break; case Token.COMMA: ensureTyped(t, n, getJSType(n.getLastChild())); break; case Token.TRUE: case Token.FALSE: ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.THIS: ensureTyped(t, n, t.getScope().getTypeOfThis()); break; case Token.REF_SPECIAL: ensureTyped(t, n); break; case Token.GET_REF: ensureTyped(t, n, getJSType(n.getFirstChild())); break; case Token.NULL: ensureTyped(t, n, NULL_TYPE); break; case Token.NUMBER: ensureTyped(t, n, NUMBER_TYPE); break; case Token.STRING: // Object literal keys are handled with OBJECTLIT if (!NodeUtil.isObjectLitKey(n, n.getParent())) { ensureTyped(t, n, STRING_TYPE); } else { // Object literal keys are not typeable typeable = false; } break; case Token.GET: case Token.SET: // Object literal keys are handled with OBJECTLIT break; case Token.ARRAYLIT: ensureTyped(t, n, ARRAY_TYPE); break; case Token.REGEXP: ensureTyped(t, n, REGEXP_TYPE); break; case Token.GETPROP: visitGetProp(t, n, parent); typeable = !(parent.getType() == Token.ASSIGN && parent.getFirstChild() == n); break; case Token.GETELEM: visitGetElem(t, n); // The type of GETELEM is always unknown, so no point counting that. // If that unknown leaks elsewhere (say by an assignment to another // variable), then it will be counted. typeable = false; break; case Token.VAR: visitVar(t, n); typeable = false; break; case Token.NEW: visitNew(t, n); typeable = true; break; case Token.CALL: visitCall(t, n); typeable = !NodeUtil.isExpressionNode(parent); break; case Token.RETURN: visitReturn(t, n); typeable = false; break; case Token.DEC: case Token.INC: left = n.getFirstChild(); validator.expectNumber( t, left, getJSType(left), "increment/decrement"); ensureTyped(t, n, NUMBER_TYPE); break; case Token.NOT: ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.VOID: ensureTyped(t, n, VOID_TYPE); break; case Token.TYPEOF: ensureTyped(t, n, STRING_TYPE); break; case Token.BITNOT: childType = getJSType(n.getFirstChild()); if (!childType.matchesInt32Context()) { report(t, n, BIT_OPERATION, NodeUtil.opToStr(n.getType()), childType.toString()); } ensureTyped(t, n, NUMBER_TYPE); break; case Token.POS: case Token.NEG: left = n.getFirstChild(); validator.expectNumber(t, left, getJSType(left), "sign operator"); ensureTyped(t, n, NUMBER_TYPE); break; case Token.EQ: case Token.NE: { leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined(); JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined(); TernaryValue result = leftTypeRestricted.testForEquality(rightTypeRestricted); if (result != TernaryValue.UNKNOWN) { if (n.getType() == Token.NE) { result = result.not(); } report(t, n, DETERMINISTIC_TEST, leftType.toString(), rightType.toString(), result.toString()); } ensureTyped(t, n, BOOLEAN_TYPE); break; } case Token.SHEQ: case Token.SHNE: { leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined(); JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined(); if (!leftTypeRestricted.canTestForShallowEqualityWith( rightTypeRestricted)) { report(t, n, DETERMINISTIC_TEST_NO_RESULT, leftType.toString(), rightType.toString()); } ensureTyped(t, n, BOOLEAN_TYPE); break; } case Token.LT: case Token.LE: case Token.GT: case Token.GE: leftType = getJSType(n.getFirstChild()); rightType = getJSType(n.getLastChild()); if (rightType.isNumber()) { validator.expectNumber( t, n, leftType, "left side of numeric comparison"); } else if (leftType.isNumber()) { validator.expectNumber( t, n, rightType, "right side of numeric comparison"); } else if (leftType.matchesNumberContext() && rightType.matchesNumberContext()) { // OK. } else { // Whether the comparison is numeric will be determined at runtime // each time the expression is evaluated. Regardless, both operands // should match a string context. String message = "left side of comparison"; validator.expectString(t, n, leftType, message); validator.expectNotNullOrUndefined( t, n, leftType, message, getNativeType(STRING_TYPE)); message = "right side of comparison"; validator.expectString(t, n, rightType, message); validator.expectNotNullOrUndefined( t, n, rightType, message, getNativeType(STRING_TYPE)); } ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.IN: left = n.getFirstChild(); right = n.getLastChild(); leftType = getJSType(left); rightType = getJSType(right); validator.expectObject(t, n, rightType, "'in' requires an object"); validator.expectString(t, left, leftType, "left side of 'in'"); ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.INSTANCEOF: left = n.getFirstChild(); right = n.getLastChild(); leftType = getJSType(left); rightType = getJSType(right).restrictByNotNullOrUndefined(); validator.expectAnyObject( t, left, leftType, "deterministic instanceof yields false"); validator.expectActualObject( t, right, rightType, "instanceof requires an object"); ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.ASSIGN: visitAssign(t, n); typeable = false; break; case Token.ASSIGN_LSH: case Token.ASSIGN_RSH: case Token.ASSIGN_URSH: case Token.ASSIGN_DIV: case Token.ASSIGN_MOD: case Token.ASSIGN_BITOR: case Token.ASSIGN_BITXOR: case Token.ASSIGN_BITAND: case Token.ASSIGN_SUB: case Token.ASSIGN_ADD: case Token.ASSIGN_MUL: case Token.LSH: case Token.RSH: case Token.URSH: case Token.DIV: case Token.MOD: case Token.BITOR: case Token.BITXOR: case Token.BITAND: case Token.SUB: case Token.ADD: case Token.MUL: visitBinaryOperator(n.getType(), t, n); break; case Token.DELPROP: if (!isReference(n.getFirstChild())) { report(t, n, BAD_DELETE); } ensureTyped(t, n, BOOLEAN_TYPE); break; case Token.CASE: JSType switchType = getJSType(parent.getFirstChild()); JSType caseType = getJSType(n.getFirstChild()); validator.expectSwitchMatchesCase(t, n, switchType, caseType); typeable = false; break; case Token.WITH: { Node child = n.getFirstChild(); childType = getJSType(child); validator.expectObject( t, child, childType, "with requires an object"); typeable = false; break; } case Token.FUNCTION: visitFunction(t, n); break; // These nodes have no interesting type behavior. case Token.LABEL: case Token.LABEL_NAME: case Token.SWITCH: case Token.BREAK: case Token.CATCH: case Token.TRY: case Token.SCRIPT: case Token.EXPR_RESULT: case Token.BLOCK: case Token.EMPTY: case Token.DEFAULT: case Token.CONTINUE: case Token.DEBUGGER: case Token.THROW: typeable = false; break; // These nodes require data flow analysis. case Token.DO: case Token.FOR: case Token.IF: case Token.WHILE: typeable = false; break; // These nodes are typed during the type inference. case Token.AND: case Token.HOOK: case Token.OBJECTLIT: case Token.OR: if (n.getJSType() != null) { // If we didn't run type inference. ensureTyped(t, n); } else { // If this is an enum, then give that type to the objectlit as well. if ((n.getType() == Token.OBJECTLIT) && (parent.getJSType() instanceof EnumType)) { ensureTyped(t, n, parent.getJSType()); } else { ensureTyped(t, n); } } if (n.getType() == Token.OBJECTLIT) { for (Node key : n.children()) { visitObjLitKey(t, key, n); } } break; default: report(t, n, UNEXPECTED_TOKEN, Token.name(n.getType())); ensureTyped(t, n); break; } // Don't count externs since the user's code may not even use that part. typeable = typeable && !inExterns; if (typeable) { doPercentTypedAccounting(t, n); } checkNoTypeCheckSection(n, false); }
src/com/google/javascript/jscomp/TypeCheck.java
Closure-67
private boolean isPrototypePropertyAssign(Node assign) { Node n = assign.getFirstChild(); if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign) && n.getType() == Token.GETPROP ) { // We want to exclude the assignment itself from the usage list boolean isChainedProperty = n.getFirstChild().getType() == Token.GETPROP; if (isChainedProperty) { Node child = n.getFirstChild().getFirstChild().getNext(); if (child.getType() == Token.STRING && child.getString().equals("prototype")) { return true; } } } return false; } private boolean isPrototypePropertyAssign(Node assign) { Node n = assign.getFirstChild(); if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign) && n.getType() == Token.GETPROP && assign.getParent().getType() == Token.EXPR_RESULT) { // We want to exclude the assignment itself from the usage list boolean isChainedProperty = n.getFirstChild().getType() == Token.GETPROP; if (isChainedProperty) { Node child = n.getFirstChild().getFirstChild().getNext(); if (child.getType() == Token.STRING && child.getString().equals("prototype")) { return true; } } } return false; }
src/com/google/javascript/jscomp/AnalyzePrototypeProperties.java
Closure-69
private void visitCall(NodeTraversal t, Node n) { Node child = n.getFirstChild(); JSType childType = getJSType(child).restrictByNotNullOrUndefined(); if (!childType.canBeCalled()) { report(t, n, NOT_CALLABLE, childType.toString()); ensureTyped(t, n); return; } // A couple of types can be called as if they were functions. // If it is a function type, then validate parameters. if (childType instanceof FunctionType) { FunctionType functionType = (FunctionType) childType; boolean isExtern = false; JSDocInfo functionJSDocInfo = functionType.getJSDocInfo(); if(functionJSDocInfo != null) { String sourceName = functionJSDocInfo.getSourceName(); CompilerInput functionSource = compiler.getInput(sourceName); isExtern = functionSource.isExtern(); } // Non-native constructors should not be called directly // unless they specify a return type and are defined // in an extern. if (functionType.isConstructor() && !functionType.isNativeObjectType() && (functionType.getReturnType().isUnknownType() || functionType.getReturnType().isVoidType() || !isExtern)) { report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString()); } // Functions with explcit 'this' types must be called in a GETPROP // or GETELEM. visitParameterList(t, n, functionType); ensureTyped(t, n, functionType.getReturnType()); } else { ensureTyped(t, n); } // TODO: Add something to check for calls of RegExp objects, which is not // supported by IE. Either say something about the return type or warn // about the non-portability of the call or both. } private void visitCall(NodeTraversal t, Node n) { Node child = n.getFirstChild(); JSType childType = getJSType(child).restrictByNotNullOrUndefined(); if (!childType.canBeCalled()) { report(t, n, NOT_CALLABLE, childType.toString()); ensureTyped(t, n); return; } // A couple of types can be called as if they were functions. // If it is a function type, then validate parameters. if (childType instanceof FunctionType) { FunctionType functionType = (FunctionType) childType; boolean isExtern = false; JSDocInfo functionJSDocInfo = functionType.getJSDocInfo(); if(functionJSDocInfo != null) { String sourceName = functionJSDocInfo.getSourceName(); CompilerInput functionSource = compiler.getInput(sourceName); isExtern = functionSource.isExtern(); } // Non-native constructors should not be called directly // unless they specify a return type and are defined // in an extern. if (functionType.isConstructor() && !functionType.isNativeObjectType() && (functionType.getReturnType().isUnknownType() || functionType.getReturnType().isVoidType() || !isExtern)) { report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString()); } // Functions with explcit 'this' types must be called in a GETPROP // or GETELEM. if (functionType.isOrdinaryFunction() && !functionType.getTypeOfThis().isUnknownType() && !functionType.getTypeOfThis().isNativeObjectType() && !(child.getType() == Token.GETELEM || child.getType() == Token.GETPROP)) { report(t, n, EXPECTED_THIS_TYPE, functionType.toString()); } visitParameterList(t, n, functionType); ensureTyped(t, n, functionType.getReturnType()); } else { ensureTyped(t, n); } // TODO: Add something to check for calls of RegExp objects, which is not // supported by IE. Either say something about the return type or warn // about the non-portability of the call or both. }
src/com/google/javascript/jscomp/TypeCheck.java
Closure-7
public JSType caseObjectType(ObjectType type) { if (value.equals("function")) { JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE); return resultEqualsValue && ctorType.isSubtype(type) ? ctorType : null; // Objects are restricted to "Function", subtypes are left // Only filter out subtypes of "function" } return matchesExpectation("object") ? type : null; } public JSType caseObjectType(ObjectType type) { if (value.equals("function")) { JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE); if (resultEqualsValue) { // Objects are restricted to "Function", subtypes are left return ctorType.getGreatestSubtype(type); } else { // Only filter out subtypes of "function" return type.isSubtype(ctorType) ? null : type; } } return matchesExpectation("object") ? type : null; }
src/com/google/javascript/jscomp/type/ChainableReverseAbstractInterpreter.java
Closure-70
private void declareArguments(Node functionNode) { Node astParameters = functionNode.getFirstChild().getNext(); Node body = astParameters.getNext(); FunctionType functionType = (FunctionType) functionNode.getJSType(); if (functionType != null) { Node jsDocParameters = functionType.getParametersNode(); if (jsDocParameters != null) { Node jsDocParameter = jsDocParameters.getFirstChild(); for (Node astParameter : astParameters.children()) { if (jsDocParameter != null) { defineSlot(astParameter, functionNode, jsDocParameter.getJSType(), true); jsDocParameter = jsDocParameter.getNext(); } else { defineSlot(astParameter, functionNode, null, true); } } } } } // end declareArguments private void declareArguments(Node functionNode) { Node astParameters = functionNode.getFirstChild().getNext(); Node body = astParameters.getNext(); FunctionType functionType = (FunctionType) functionNode.getJSType(); if (functionType != null) { Node jsDocParameters = functionType.getParametersNode(); if (jsDocParameters != null) { Node jsDocParameter = jsDocParameters.getFirstChild(); for (Node astParameter : astParameters.children()) { if (jsDocParameter != null) { defineSlot(astParameter, functionNode, jsDocParameter.getJSType(), false); jsDocParameter = jsDocParameter.getNext(); } else { defineSlot(astParameter, functionNode, null, true); } } } } } // end declareArguments
src/com/google/javascript/jscomp/TypedScopeCreator.java
Closure-71
private void checkPropertyVisibility(NodeTraversal t, Node getprop, Node parent) { ObjectType objectType = ObjectType.cast(dereference(getprop.getFirstChild().getJSType())); String propertyName = getprop.getLastChild().getString(); if (objectType != null) { // Is this a normal property access, or are we trying to override // an existing property? boolean isOverride = t.inGlobalScope() && parent.getType() == Token.ASSIGN && parent.getFirstChild() == getprop; // Find the lowest property defined on a class with visibility // information. if (isOverride) { objectType = objectType.getImplicitPrototype(); } JSDocInfo docInfo = null; for (; objectType != null; objectType = objectType.getImplicitPrototype()) { docInfo = objectType.getOwnPropertyJSDocInfo(propertyName); if (docInfo != null && docInfo.getVisibility() != Visibility.INHERITED) { break; } } if (objectType == null) { // We couldn't find a visibility modifier; assume it's public. return; } boolean sameInput = t.getInput().getName().equals(docInfo.getSourceName()); Visibility visibility = docInfo.getVisibility(); JSType ownerType = normalizeClassType(objectType); if (isOverride) { // Check an ASSIGN statement that's trying to override a property // on a superclass. JSDocInfo overridingInfo = parent.getJSDocInfo(); Visibility overridingVisibility = overridingInfo == null ? Visibility.INHERITED : overridingInfo.getVisibility(); // Check that (a) the property *can* be overridden, and // (b) that the visibility of the override is the same as the // visibility of the original property. if (visibility == Visibility.PRIVATE && !sameInput) { compiler.report( t.makeError(getprop, PRIVATE_OVERRIDE, objectType.toString())); } else if (overridingVisibility != Visibility.INHERITED && overridingVisibility != visibility) { compiler.report( t.makeError(getprop, VISIBILITY_MISMATCH, visibility.name(), objectType.toString(), overridingVisibility.name())); } } else { if (sameInput) { // private access is always allowed in the same file. return; } else if (visibility == Visibility.PRIVATE && (currentClass == null || ownerType.differsFrom(currentClass))) { if (docInfo.isConstructor() && isValidPrivateConstructorAccess(parent)) { return; } // private access is not allowed outside the file from a different // enclosing class. compiler.report( t.makeError(getprop, BAD_PRIVATE_PROPERTY_ACCESS, propertyName, validator.getReadableJSTypeName( getprop.getFirstChild(), true))); } else if (visibility == Visibility.PROTECTED) { // There are 3 types of legal accesses of a protected property: // 1) Accesses in the same file // 2) Overriding the property in a subclass // 3) Accessing the property from inside a subclass // The first two have already been checked for. if (currentClass == null || !currentClass.isSubtype(ownerType)) { compiler.report( t.makeError(getprop, BAD_PROTECTED_PROPERTY_ACCESS, propertyName, validator.getReadableJSTypeName( getprop.getFirstChild(), true))); } } } } } private void checkPropertyVisibility(NodeTraversal t, Node getprop, Node parent) { ObjectType objectType = ObjectType.cast(dereference(getprop.getFirstChild().getJSType())); String propertyName = getprop.getLastChild().getString(); if (objectType != null) { // Is this a normal property access, or are we trying to override // an existing property? boolean isOverride = parent.getJSDocInfo() != null && parent.getType() == Token.ASSIGN && parent.getFirstChild() == getprop; // Find the lowest property defined on a class with visibility // information. if (isOverride) { objectType = objectType.getImplicitPrototype(); } JSDocInfo docInfo = null; for (; objectType != null; objectType = objectType.getImplicitPrototype()) { docInfo = objectType.getOwnPropertyJSDocInfo(propertyName); if (docInfo != null && docInfo.getVisibility() != Visibility.INHERITED) { break; } } if (objectType == null) { // We couldn't find a visibility modifier; assume it's public. return; } boolean sameInput = t.getInput().getName().equals(docInfo.getSourceName()); Visibility visibility = docInfo.getVisibility(); JSType ownerType = normalizeClassType(objectType); if (isOverride) { // Check an ASSIGN statement that's trying to override a property // on a superclass. JSDocInfo overridingInfo = parent.getJSDocInfo(); Visibility overridingVisibility = overridingInfo == null ? Visibility.INHERITED : overridingInfo.getVisibility(); // Check that (a) the property *can* be overridden, and // (b) that the visibility of the override is the same as the // visibility of the original property. if (visibility == Visibility.PRIVATE && !sameInput) { compiler.report( t.makeError(getprop, PRIVATE_OVERRIDE, objectType.toString())); } else if (overridingVisibility != Visibility.INHERITED && overridingVisibility != visibility) { compiler.report( t.makeError(getprop, VISIBILITY_MISMATCH, visibility.name(), objectType.toString(), overridingVisibility.name())); } } else { if (sameInput) { // private access is always allowed in the same file. return; } else if (visibility == Visibility.PRIVATE && (currentClass == null || ownerType.differsFrom(currentClass))) { if (docInfo.isConstructor() && isValidPrivateConstructorAccess(parent)) { return; } // private access is not allowed outside the file from a different // enclosing class. compiler.report( t.makeError(getprop, BAD_PRIVATE_PROPERTY_ACCESS, propertyName, validator.getReadableJSTypeName( getprop.getFirstChild(), true))); } else if (visibility == Visibility.PROTECTED) { // There are 3 types of legal accesses of a protected property: // 1) Accesses in the same file // 2) Overriding the property in a subclass // 3) Accessing the property from inside a subclass // The first two have already been checked for. if (currentClass == null || !currentClass.isSubtype(ownerType)) { compiler.report( t.makeError(getprop, BAD_PROTECTED_PROPERTY_ACCESS, propertyName, validator.getReadableJSTypeName( getprop.getFirstChild(), true))); } } } } }
src/com/google/javascript/jscomp/CheckAccessControls.java
Closure-73
static String strEscape(String s, char quote, String doublequoteEscape, String singlequoteEscape, String backslashEscape, CharsetEncoder outputCharsetEncoder) { StringBuilder sb = new StringBuilder(s.length() + 2); sb.append(quote); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\0': sb.append("\\0"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\\': sb.append(backslashEscape); break; case '\"': sb.append(doublequoteEscape); break; case '\'': sb.append(singlequoteEscape); break; case '>': // Break --> into --\> or ]]> into ]]\> if (i >= 2 && ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') || (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) { sb.append("\\>"); } else { sb.append(c); } break; case '<': // Break </script into <\/script final String END_SCRIPT = "/script"; // Break <!-- into <\!-- final String START_COMMENT = "!--"; if (s.regionMatches(true, i + 1, END_SCRIPT, 0, END_SCRIPT.length())) { sb.append("<\\"); } else if (s.regionMatches(false, i + 1, START_COMMENT, 0, START_COMMENT.length())) { sb.append("<\\"); } else { sb.append(c); } break; default: // If we're given an outputCharsetEncoder, then check if the // character can be represented in this character set. if (outputCharsetEncoder != null) { if (outputCharsetEncoder.canEncode(c)) { sb.append(c); } else { // Unicode-escape the character. appendHexJavaScriptRepresentation(sb, c); } } else { // No charsetEncoder provided - pass straight latin characters // through, and escape the rest. Doing the explicit character // check is measurably faster than using the CharsetEncoder. if (c > 0x1f && c <= 0x7f) { sb.append(c); } else { // Other characters can be misinterpreted by some js parsers, // or perhaps mangled by proxies along the way, // so we play it safe and unicode escape them. appendHexJavaScriptRepresentation(sb, c); } } } } sb.append(quote); return sb.toString(); } static String strEscape(String s, char quote, String doublequoteEscape, String singlequoteEscape, String backslashEscape, CharsetEncoder outputCharsetEncoder) { StringBuilder sb = new StringBuilder(s.length() + 2); sb.append(quote); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\0': sb.append("\\0"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\\': sb.append(backslashEscape); break; case '\"': sb.append(doublequoteEscape); break; case '\'': sb.append(singlequoteEscape); break; case '>': // Break --> into --\> or ]]> into ]]\> if (i >= 2 && ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') || (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) { sb.append("\\>"); } else { sb.append(c); } break; case '<': // Break </script into <\/script final String END_SCRIPT = "/script"; // Break <!-- into <\!-- final String START_COMMENT = "!--"; if (s.regionMatches(true, i + 1, END_SCRIPT, 0, END_SCRIPT.length())) { sb.append("<\\"); } else if (s.regionMatches(false, i + 1, START_COMMENT, 0, START_COMMENT.length())) { sb.append("<\\"); } else { sb.append(c); } break; default: // If we're given an outputCharsetEncoder, then check if the // character can be represented in this character set. if (outputCharsetEncoder != null) { if (outputCharsetEncoder.canEncode(c)) { sb.append(c); } else { // Unicode-escape the character. appendHexJavaScriptRepresentation(sb, c); } } else { // No charsetEncoder provided - pass straight latin characters // through, and escape the rest. Doing the explicit character // check is measurably faster than using the CharsetEncoder. if (c > 0x1f && c < 0x7f) { sb.append(c); } else { // Other characters can be misinterpreted by some js parsers, // or perhaps mangled by proxies along the way, // so we play it safe and unicode escape them. appendHexJavaScriptRepresentation(sb, c); } } } } sb.append(quote); return sb.toString(); }
src/com/google/javascript/jscomp/CodeGenerator.java
Closure-77
static String strEscape(String s, char quote, String doublequoteEscape, String singlequoteEscape, String backslashEscape, CharsetEncoder outputCharsetEncoder) { StringBuilder sb = new StringBuilder(s.length() + 2); sb.append(quote); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\\': sb.append(backslashEscape); break; case '\"': sb.append(doublequoteEscape); break; case '\'': sb.append(singlequoteEscape); break; case '>': // Break --> into --\> or ]]> into ]]\> if (i >= 2 && ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') || (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) { sb.append("\\>"); } else { sb.append(c); } break; case '<': // Break </script into <\/script final String END_SCRIPT = "/script"; // Break <!-- into <\!-- final String START_COMMENT = "!--"; if (s.regionMatches(true, i + 1, END_SCRIPT, 0, END_SCRIPT.length())) { sb.append("<\\"); } else if (s.regionMatches(false, i + 1, START_COMMENT, 0, START_COMMENT.length())) { sb.append("<\\"); } else { sb.append(c); } break; default: // If we're given an outputCharsetEncoder, then check if the // character can be represented in this character set. if (outputCharsetEncoder != null) { if (outputCharsetEncoder.canEncode(c)) { sb.append(c); } else { // Unicode-escape the character. appendHexJavaScriptRepresentation(sb, c); } } else { // No charsetEncoder provided - pass straight latin characters // through, and escape the rest. Doing the explicit character // check is measurably faster than using the CharsetEncoder. if (c > 0x1f && c <= 0x7f) { sb.append(c); } else { // Other characters can be misinterpreted by some js parsers, // or perhaps mangled by proxies along the way, // so we play it safe and unicode escape them. appendHexJavaScriptRepresentation(sb, c); } } } } sb.append(quote); return sb.toString(); } static String strEscape(String s, char quote, String doublequoteEscape, String singlequoteEscape, String backslashEscape, CharsetEncoder outputCharsetEncoder) { StringBuilder sb = new StringBuilder(s.length() + 2); sb.append(quote); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\0': sb.append("\\0"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; case '\\': sb.append(backslashEscape); break; case '\"': sb.append(doublequoteEscape); break; case '\'': sb.append(singlequoteEscape); break; case '>': // Break --> into --\> or ]]> into ]]\> if (i >= 2 && ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') || (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) { sb.append("\\>"); } else { sb.append(c); } break; case '<': // Break </script into <\/script final String END_SCRIPT = "/script"; // Break <!-- into <\!-- final String START_COMMENT = "!--"; if (s.regionMatches(true, i + 1, END_SCRIPT, 0, END_SCRIPT.length())) { sb.append("<\\"); } else if (s.regionMatches(false, i + 1, START_COMMENT, 0, START_COMMENT.length())) { sb.append("<\\"); } else { sb.append(c); } break; default: // If we're given an outputCharsetEncoder, then check if the // character can be represented in this character set. if (outputCharsetEncoder != null) { if (outputCharsetEncoder.canEncode(c)) { sb.append(c); } else { // Unicode-escape the character. appendHexJavaScriptRepresentation(sb, c); } } else { // No charsetEncoder provided - pass straight latin characters // through, and escape the rest. Doing the explicit character // check is measurably faster than using the CharsetEncoder. if (c > 0x1f && c <= 0x7f) { sb.append(c); } else { // Other characters can be misinterpreted by some js parsers, // or perhaps mangled by proxies along the way, // so we play it safe and unicode escape them. appendHexJavaScriptRepresentation(sb, c); } } } } sb.append(quote); return sb.toString(); }
src/com/google/javascript/jscomp/CodeGenerator.java
Closure-78
private Node performArithmeticOp(int opType, Node left, Node right) { // Unlike other operations, ADD operands are not always converted // to Number. if (opType == Token.ADD && (NodeUtil.mayBeString(left, false) || NodeUtil.mayBeString(right, false))) { return null; } double result; // TODO(johnlenz): Handle NaN with unknown value. BIT ops convert NaN // to zero so this is a little akward here. Double lValObj = NodeUtil.getNumberValue(left); if (lValObj == null) { return null; } Double rValObj = NodeUtil.getNumberValue(right); if (rValObj == null) { return null; } double lval = lValObj; double rval = rValObj; switch (opType) { case Token.BITAND: result = ScriptRuntime.toInt32(lval) & ScriptRuntime.toInt32(rval); break; case Token.BITOR: result = ScriptRuntime.toInt32(lval) | ScriptRuntime.toInt32(rval); break; case Token.BITXOR: result = ScriptRuntime.toInt32(lval) ^ ScriptRuntime.toInt32(rval); break; case Token.ADD: result = lval + rval; break; case Token.SUB: result = lval - rval; break; case Token.MUL: result = lval * rval; break; case Token.MOD: if (rval == 0) { error(DiagnosticType.error("JSC_DIVIDE_BY_0_ERROR", "Divide by 0"), right); return null; } result = lval % rval; break; case Token.DIV: if (rval == 0) { error(DiagnosticType.error("JSC_DIVIDE_BY_0_ERROR", "Divide by 0"), right); return null; } result = lval / rval; break; default: throw new Error("Unexpected arithmetic operator"); } // TODO(johnlenz): consider removing the result length check. // length of the left and right value plus 1 byte for the operator. if (String.valueOf(result).length() <= String.valueOf(lval).length() + String.valueOf(rval).length() + 1 && // Do not try to fold arithmetic for numbers > 2^53. After that // point, fixed-point math starts to break down and become inaccurate. Math.abs(result) <= MAX_FOLD_NUMBER) { Node newNumber = Node.newNumber(result); return newNumber; } else if (Double.isNaN(result)) { return Node.newString(Token.NAME, "NaN"); } else if (result == Double.POSITIVE_INFINITY) { return Node.newString(Token.NAME, "Infinity"); } else if (result == Double.NEGATIVE_INFINITY) { return new Node(Token.NEG, Node.newString(Token.NAME, "Infinity")); } return null; } private Node performArithmeticOp(int opType, Node left, Node right) { // Unlike other operations, ADD operands are not always converted // to Number. if (opType == Token.ADD && (NodeUtil.mayBeString(left, false) || NodeUtil.mayBeString(right, false))) { return null; } double result; // TODO(johnlenz): Handle NaN with unknown value. BIT ops convert NaN // to zero so this is a little akward here. Double lValObj = NodeUtil.getNumberValue(left); if (lValObj == null) { return null; } Double rValObj = NodeUtil.getNumberValue(right); if (rValObj == null) { return null; } double lval = lValObj; double rval = rValObj; switch (opType) { case Token.BITAND: result = ScriptRuntime.toInt32(lval) & ScriptRuntime.toInt32(rval); break; case Token.BITOR: result = ScriptRuntime.toInt32(lval) | ScriptRuntime.toInt32(rval); break; case Token.BITXOR: result = ScriptRuntime.toInt32(lval) ^ ScriptRuntime.toInt32(rval); break; case Token.ADD: result = lval + rval; break; case Token.SUB: result = lval - rval; break; case Token.MUL: result = lval * rval; break; case Token.MOD: if (rval == 0) { return null; } result = lval % rval; break; case Token.DIV: if (rval == 0) { return null; } result = lval / rval; break; default: throw new Error("Unexpected arithmetic operator"); } // TODO(johnlenz): consider removing the result length check. // length of the left and right value plus 1 byte for the operator. if (String.valueOf(result).length() <= String.valueOf(lval).length() + String.valueOf(rval).length() + 1 && // Do not try to fold arithmetic for numbers > 2^53. After that // point, fixed-point math starts to break down and become inaccurate. Math.abs(result) <= MAX_FOLD_NUMBER) { Node newNumber = Node.newNumber(result); return newNumber; } else if (Double.isNaN(result)) { return Node.newString(Token.NAME, "NaN"); } else if (result == Double.POSITIVE_INFINITY) { return Node.newString(Token.NAME, "Infinity"); } else if (result == Double.NEGATIVE_INFINITY) { return new Node(Token.NEG, Node.newString(Token.NAME, "Infinity")); } return null; }
src/com/google/javascript/jscomp/PeepholeFoldConstants.java
Closure-81
Node processFunctionNode(FunctionNode functionNode) { Name name = functionNode.getFunctionName(); Boolean isUnnamedFunction = false; if (name == null) { name = new Name(); name.setIdentifier(""); isUnnamedFunction = true; } Node node = newNode(Token.FUNCTION); Node newName = transform(name); if (isUnnamedFunction) { // Old Rhino tagged the empty name node with the line number of the // declaration. newName.setLineno(functionNode.getLineno()); // TODO(bowdidge) Mark line number of paren correctly. // Same problem as below - the left paren might not be on the // same line as the function keyword. int lpColumn = functionNode.getAbsolutePosition() + functionNode.getLp(); newName.setCharno(position2charno(lpColumn)); } node.addChildToBack(newName); Node lp = newNode(Token.LP); // The left paren's complicated because it's not represented by an // AstNode, so there's nothing that has the actual line number that it // appeared on. We know the paren has to appear on the same line as the // function name (or else a semicolon will be inserted.) If there's no // function name, assume the paren was on the same line as the function. // TODO(bowdidge): Mark line number of paren correctly. Name fnName = functionNode.getFunctionName(); if (fnName != null) { lp.setLineno(fnName.getLineno()); } else { lp.setLineno(functionNode.getLineno()); } int lparenCharno = functionNode.getLp() + functionNode.getAbsolutePosition(); lp.setCharno(position2charno(lparenCharno)); for (AstNode param : functionNode.getParams()) { lp.addChildToBack(transform(param)); } node.addChildToBack(lp); Node bodyNode = transform(functionNode.getBody()); parseDirectives(bodyNode); node.addChildToBack(bodyNode); return node; } Node processFunctionNode(FunctionNode functionNode) { Name name = functionNode.getFunctionName(); Boolean isUnnamedFunction = false; if (name == null) { int functionType = functionNode.getFunctionType(); if (functionType != FunctionNode.FUNCTION_EXPRESSION) { errorReporter.error( "unnamed function statement", sourceName, functionNode.getLineno(), "", 0); } name = new Name(); name.setIdentifier(""); isUnnamedFunction = true; } Node node = newNode(Token.FUNCTION); Node newName = transform(name); if (isUnnamedFunction) { // Old Rhino tagged the empty name node with the line number of the // declaration. newName.setLineno(functionNode.getLineno()); // TODO(bowdidge) Mark line number of paren correctly. // Same problem as below - the left paren might not be on the // same line as the function keyword. int lpColumn = functionNode.getAbsolutePosition() + functionNode.getLp(); newName.setCharno(position2charno(lpColumn)); } node.addChildToBack(newName); Node lp = newNode(Token.LP); // The left paren's complicated because it's not represented by an // AstNode, so there's nothing that has the actual line number that it // appeared on. We know the paren has to appear on the same line as the // function name (or else a semicolon will be inserted.) If there's no // function name, assume the paren was on the same line as the function. // TODO(bowdidge): Mark line number of paren correctly. Name fnName = functionNode.getFunctionName(); if (fnName != null) { lp.setLineno(fnName.getLineno()); } else { lp.setLineno(functionNode.getLineno()); } int lparenCharno = functionNode.getLp() + functionNode.getAbsolutePosition(); lp.setCharno(position2charno(lparenCharno)); for (AstNode param : functionNode.getParams()) { lp.addChildToBack(transform(param)); } node.addChildToBack(lp); Node bodyNode = transform(functionNode.getBody()); parseDirectives(bodyNode); node.addChildToBack(bodyNode); return node; }
src/com/google/javascript/jscomp/parsing/IRFactory.java
Closure-82
public final boolean isEmptyType() { return isNoType() || isNoObjectType() || isNoResolvedType(); } public final boolean isEmptyType() { return isNoType() || isNoObjectType() || isNoResolvedType() || (registry.getNativeFunctionType( JSTypeNative.LEAST_FUNCTION_TYPE) == this); }
src/com/google/javascript/rhino/jstype/JSType.java
Closure-83
public int parseArguments(Parameters params) throws CmdLineException { String param = params.getParameter(0); if (param == null) { setter.addValue(true); return 0; } else { String lowerParam = param.toLowerCase(); if (TRUES.contains(lowerParam)) { setter.addValue(true); } else if (FALSES.contains(lowerParam)) { setter.addValue(false); } else { setter.addValue(true); return 0; } return 1; } } public int parseArguments(Parameters params) throws CmdLineException { String param = null; try { param = params.getParameter(0); } catch (CmdLineException e) {} if (param == null) { setter.addValue(true); return 0; } else { String lowerParam = param.toLowerCase(); if (TRUES.contains(lowerParam)) { setter.addValue(true); } else if (FALSES.contains(lowerParam)) { setter.addValue(false); } else { setter.addValue(true); return 0; } return 1; } }
src/com/google/javascript/jscomp/CommandLineRunner.java
Closure-86
static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) { switch (value.getType()) { case Token.ASSIGN: // A result that is aliased by a non-local name, is the effectively the // same as returning a non-local name, but this doesn't matter if the // value is immutable. return NodeUtil.isImmutableValue(value.getLastChild()) || (locals.apply(value) && evaluatesToLocalValue(value.getLastChild(), locals)); case Token.COMMA: return evaluatesToLocalValue(value.getLastChild(), locals); case Token.AND: case Token.OR: return evaluatesToLocalValue(value.getFirstChild(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.HOOK: return evaluatesToLocalValue(value.getFirstChild().getNext(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.INC: case Token.DEC: if (value.getBooleanProp(Node.INCRDECR_PROP)) { return evaluatesToLocalValue(value.getFirstChild(), locals); } else { return true; } case Token.THIS: return locals.apply(value); case Token.NAME: return isImmutableValue(value) || locals.apply(value); case Token.GETELEM: case Token.GETPROP: // There is no information about the locality of object properties. return locals.apply(value); case Token.CALL: return callHasLocalResult(value) || isToStringMethodCall(value) || locals.apply(value); case Token.NEW: // TODO(nicksantos): This needs to be changed so that it // returns true iff we're sure the value was never aliased from inside // the constructor (similar to callHasLocalResult) return true; case Token.FUNCTION: case Token.REGEXP: case Token.ARRAYLIT: case Token.OBJECTLIT: // Literals objects with non-literal children are allowed. return true; case Token.IN: // TODO(johnlenz): should IN operator be included in #isSimpleOperator? return true; default: // Other op force a local value: // x = '' + g (x is now an local string) // x -= g (x is now an local number) if (isAssignmentOp(value) || isSimpleOperator(value) || isImmutableValue(value)) { return true; } throw new IllegalStateException( "Unexpected expression node" + value + "\n parent:" + value.getParent()); } } static boolean evaluatesToLocalValue(Node value, Predicate<Node> locals) { switch (value.getType()) { case Token.ASSIGN: // A result that is aliased by a non-local name, is the effectively the // same as returning a non-local name, but this doesn't matter if the // value is immutable. return NodeUtil.isImmutableValue(value.getLastChild()) || (locals.apply(value) && evaluatesToLocalValue(value.getLastChild(), locals)); case Token.COMMA: return evaluatesToLocalValue(value.getLastChild(), locals); case Token.AND: case Token.OR: return evaluatesToLocalValue(value.getFirstChild(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.HOOK: return evaluatesToLocalValue(value.getFirstChild().getNext(), locals) && evaluatesToLocalValue(value.getLastChild(), locals); case Token.INC: case Token.DEC: if (value.getBooleanProp(Node.INCRDECR_PROP)) { return evaluatesToLocalValue(value.getFirstChild(), locals); } else { return true; } case Token.THIS: return locals.apply(value); case Token.NAME: return isImmutableValue(value) || locals.apply(value); case Token.GETELEM: case Token.GETPROP: // There is no information about the locality of object properties. return locals.apply(value); case Token.CALL: return callHasLocalResult(value) || isToStringMethodCall(value) || locals.apply(value); case Token.NEW: // TODO(nicksantos): This needs to be changed so that it // returns true iff we're sure the value was never aliased from inside // the constructor (similar to callHasLocalResult) return false; case Token.FUNCTION: case Token.REGEXP: case Token.ARRAYLIT: case Token.OBJECTLIT: // Literals objects with non-literal children are allowed. return true; case Token.IN: // TODO(johnlenz): should IN operator be included in #isSimpleOperator? return true; default: // Other op force a local value: // x = '' + g (x is now an local string) // x -= g (x is now an local number) if (isAssignmentOp(value) || isSimpleOperator(value) || isImmutableValue(value)) { return true; } throw new IllegalStateException( "Unexpected expression node" + value + "\n parent:" + value.getParent()); } }
src/com/google/javascript/jscomp/NodeUtil.java
Closure-87
private boolean isFoldableExpressBlock(Node n) { if (n.getType() == Token.BLOCK) { if (n.hasOneChild()) { Node maybeExpr = n.getFirstChild(); // IE has a bug where event handlers behave differently when // their return value is used vs. when their return value is in // an EXPR_RESULT. It's pretty freaking weird. See: // http://code.google.com/p/closure-compiler/issues/detail?id=291 // We try to detect this case, and not fold EXPR_RESULTs // into other expressions. // We only have to worry about methods with an implicit 'this' // param, or this doesn't happen. return NodeUtil.isExpressionNode(maybeExpr); } } return false; } private boolean isFoldableExpressBlock(Node n) { if (n.getType() == Token.BLOCK) { if (n.hasOneChild()) { Node maybeExpr = n.getFirstChild(); if (maybeExpr.getType() == Token.EXPR_RESULT) { // IE has a bug where event handlers behave differently when // their return value is used vs. when their return value is in // an EXPR_RESULT. It's pretty freaking weird. See: // http://code.google.com/p/closure-compiler/issues/detail?id=291 // We try to detect this case, and not fold EXPR_RESULTs // into other expressions. if (maybeExpr.getFirstChild().getType() == Token.CALL) { Node calledFn = maybeExpr.getFirstChild().getFirstChild(); // We only have to worry about methods with an implicit 'this' // param, or this doesn't happen. if (calledFn.getType() == Token.GETELEM) { return false; } else if (calledFn.getType() == Token.GETPROP && calledFn.getLastChild().getString().startsWith("on")) { return false; } } return true; } return false; } } return false; }
src/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntax.java
Closure-88
private VariableLiveness isVariableReadBeforeKill( Node n, String variable) { if (NodeUtil.isName(n) && variable.equals(n.getString())) { if (NodeUtil.isLhs(n, n.getParent())) { // The expression to which the assignment is made is evaluated before // the RHS is evaluated (normal left to right evaluation) but the KILL // occurs after the RHS is evaluated. return VariableLiveness.KILL; } else { return VariableLiveness.READ; } } // Expressions are evaluated left-right, depth first. for (Node child = n.getFirstChild(); child != null; child = child.getNext()) { if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { // Not a FUNCTION VariableLiveness state = isVariableReadBeforeKill(child, variable); if (state != VariableLiveness.MAYBE_LIVE) { return state; } } } return VariableLiveness.MAYBE_LIVE; } private VariableLiveness isVariableReadBeforeKill( Node n, String variable) { if (NodeUtil.isName(n) && variable.equals(n.getString())) { if (NodeUtil.isLhs(n, n.getParent())) { Preconditions.checkState(n.getParent().getType() == Token.ASSIGN); // The expression to which the assignment is made is evaluated before // the RHS is evaluated (normal left to right evaluation) but the KILL // occurs after the RHS is evaluated. Node rhs = n.getNext(); VariableLiveness state = isVariableReadBeforeKill(rhs, variable); if (state == VariableLiveness.READ) { return state; } return VariableLiveness.KILL; } else { return VariableLiveness.READ; } } // Expressions are evaluated left-right, depth first. for (Node child = n.getFirstChild(); child != null; child = child.getNext()) { if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { // Not a FUNCTION VariableLiveness state = isVariableReadBeforeKill(child, variable); if (state != VariableLiveness.MAYBE_LIVE) { return state; } } } return VariableLiveness.MAYBE_LIVE; }
src/com/google/javascript/jscomp/DeadAssignmentsElimination.java
Closure-91
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.getType() == Token.FUNCTION) { // Don't traverse functions that are constructors or have the @this // or @override annotation. JSDocInfo jsDoc = getFunctionJsDocInfo(n); if (jsDoc != null && (jsDoc.isConstructor() || jsDoc.isInterface() || jsDoc.hasThisType() || jsDoc.isOverride())) { return false; } // Don't traverse functions unless they would normally // be able to have a @this annotation associated with them. e.g., // var a = function() { }; // or // function a() {} // or // a.x = function() {}; // or // var a = {x: function() {}}; int pType = parent.getType(); if (!(pType == Token.BLOCK || pType == Token.SCRIPT || pType == Token.NAME || pType == Token.ASSIGN || // object literal keys pType == Token.STRING || pType == Token.NUMBER)) { return false; } // Don't traverse functions that are getting lent to a prototype. } if (parent != null && parent.getType() == Token.ASSIGN) { Node lhs = parent.getFirstChild(); Node rhs = lhs.getNext(); if (n == lhs) { // Always traverse the left side of the assignment. To handle // nested assignments properly (e.g., (a = this).property = c;), // assignLhsChild should not be overridden. if (assignLhsChild == null) { assignLhsChild = lhs; } } else { // Only traverse the right side if it's not an assignment to a prototype // property or subproperty. if (NodeUtil.isGet(lhs)) { if (lhs.getType() == Token.GETPROP && lhs.getLastChild().getString().equals("prototype")) { return false; } Node llhs = lhs.getFirstChild(); if (llhs.getType() == Token.GETPROP && llhs.getLastChild().getString().equals("prototype")) { return false; } } } } return true; } public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.getType() == Token.FUNCTION) { // Don't traverse functions that are constructors or have the @this // or @override annotation. JSDocInfo jsDoc = getFunctionJsDocInfo(n); if (jsDoc != null && (jsDoc.isConstructor() || jsDoc.isInterface() || jsDoc.hasThisType() || jsDoc.isOverride())) { return false; } // Don't traverse functions unless they would normally // be able to have a @this annotation associated with them. e.g., // var a = function() { }; // or // function a() {} // or // a.x = function() {}; // or // var a = {x: function() {}}; int pType = parent.getType(); if (!(pType == Token.BLOCK || pType == Token.SCRIPT || pType == Token.NAME || pType == Token.ASSIGN || // object literal keys pType == Token.STRING || pType == Token.NUMBER)) { return false; } // Don't traverse functions that are getting lent to a prototype. Node gramps = parent.getParent(); if (NodeUtil.isObjectLitKey(parent, gramps)) { JSDocInfo maybeLends = gramps.getJSDocInfo(); if (maybeLends != null && maybeLends.getLendsName() != null && maybeLends.getLendsName().endsWith(".prototype")) { return false; } } } if (parent != null && parent.getType() == Token.ASSIGN) { Node lhs = parent.getFirstChild(); Node rhs = lhs.getNext(); if (n == lhs) { // Always traverse the left side of the assignment. To handle // nested assignments properly (e.g., (a = this).property = c;), // assignLhsChild should not be overridden. if (assignLhsChild == null) { assignLhsChild = lhs; } } else { // Only traverse the right side if it's not an assignment to a prototype // property or subproperty. if (NodeUtil.isGet(lhs)) { if (lhs.getType() == Token.GETPROP && lhs.getLastChild().getString().equals("prototype")) { return false; } Node llhs = lhs.getFirstChild(); if (llhs.getType() == Token.GETPROP && llhs.getLastChild().getString().equals("prototype")) { return false; } } } } return true; }
src/com/google/javascript/jscomp/CheckGlobalThis.java
Closure-92
void replace() { if (firstNode == null) { // Don't touch the base case ('goog'). replacementNode = candidateDefinition; return; } // Handle the case where there is a duplicate definition for an explicitly // provided symbol. if (candidateDefinition != null && explicitNode != null) { explicitNode.detachFromParent(); compiler.reportCodeChange(); // Does this need a VAR keyword? replacementNode = candidateDefinition; if (NodeUtil.isExpressionNode(candidateDefinition)) { candidateDefinition.putBooleanProp(Node.IS_NAMESPACE, true); Node assignNode = candidateDefinition.getFirstChild(); Node nameNode = assignNode.getFirstChild(); if (nameNode.getType() == Token.NAME) { // Need to convert this assign to a var declaration. Node valueNode = nameNode.getNext(); assignNode.removeChild(nameNode); assignNode.removeChild(valueNode); nameNode.addChildToFront(valueNode); Node varNode = new Node(Token.VAR, nameNode); varNode.copyInformationFrom(candidateDefinition); candidateDefinition.getParent().replaceChild( candidateDefinition, varNode); nameNode.setJSDocInfo(assignNode.getJSDocInfo()); compiler.reportCodeChange(); replacementNode = varNode; } } } else { // Handle the case where there's not a duplicate definition. replacementNode = createDeclarationNode(); if (firstModule == minimumModule) { firstNode.getParent().addChildBefore(replacementNode, firstNode); } else { // In this case, the name was implicitly provided by two independent // modules. We need to move this code up to a common module. int indexOfDot = namespace.indexOf('.'); if (indexOfDot == -1) { // Any old place is fine. compiler.getNodeForCodeInsertion(minimumModule) .addChildToBack(replacementNode); } else { // Add it after the parent namespace. ProvidedName parentName = providedNames.get(namespace.substring(0, indexOfDot)); Preconditions.checkNotNull(parentName); Preconditions.checkNotNull(parentName.replacementNode); parentName.replacementNode.getParent().addChildAfter( replacementNode, parentName.replacementNode); } } if (explicitNode != null) { explicitNode.detachFromParent(); } compiler.reportCodeChange(); } } void replace() { if (firstNode == null) { // Don't touch the base case ('goog'). replacementNode = candidateDefinition; return; } // Handle the case where there is a duplicate definition for an explicitly // provided symbol. if (candidateDefinition != null && explicitNode != null) { explicitNode.detachFromParent(); compiler.reportCodeChange(); // Does this need a VAR keyword? replacementNode = candidateDefinition; if (NodeUtil.isExpressionNode(candidateDefinition)) { candidateDefinition.putBooleanProp(Node.IS_NAMESPACE, true); Node assignNode = candidateDefinition.getFirstChild(); Node nameNode = assignNode.getFirstChild(); if (nameNode.getType() == Token.NAME) { // Need to convert this assign to a var declaration. Node valueNode = nameNode.getNext(); assignNode.removeChild(nameNode); assignNode.removeChild(valueNode); nameNode.addChildToFront(valueNode); Node varNode = new Node(Token.VAR, nameNode); varNode.copyInformationFrom(candidateDefinition); candidateDefinition.getParent().replaceChild( candidateDefinition, varNode); nameNode.setJSDocInfo(assignNode.getJSDocInfo()); compiler.reportCodeChange(); replacementNode = varNode; } } } else { // Handle the case where there's not a duplicate definition. replacementNode = createDeclarationNode(); if (firstModule == minimumModule) { firstNode.getParent().addChildBefore(replacementNode, firstNode); } else { // In this case, the name was implicitly provided by two independent // modules. We need to move this code up to a common module. int indexOfDot = namespace.lastIndexOf('.'); if (indexOfDot == -1) { // Any old place is fine. compiler.getNodeForCodeInsertion(minimumModule) .addChildToBack(replacementNode); } else { // Add it after the parent namespace. ProvidedName parentName = providedNames.get(namespace.substring(0, indexOfDot)); Preconditions.checkNotNull(parentName); Preconditions.checkNotNull(parentName.replacementNode); parentName.replacementNode.getParent().addChildAfter( replacementNode, parentName.replacementNode); } } if (explicitNode != null) { explicitNode.detachFromParent(); } compiler.reportCodeChange(); } }
src/com/google/javascript/jscomp/ProcessClosurePrimitives.java
Closure-94
static boolean isValidDefineValue(Node val, Set<String> defines) { switch (val.getType()) { case Token.STRING: case Token.NUMBER: case Token.TRUE: case Token.FALSE: return true; // Binary operators are only valid if both children are valid. case Token.BITAND: case Token.BITNOT: case Token.BITOR: case Token.BITXOR: // Uniary operators are valid if the child is valid. case Token.NOT: case Token.NEG: return isValidDefineValue(val.getFirstChild(), defines); // Names are valid if and only if they are defines themselves. case Token.NAME: case Token.GETPROP: if (val.isQualifiedName()) { return defines.contains(val.getQualifiedName()); } } return false; } static boolean isValidDefineValue(Node val, Set<String> defines) { switch (val.getType()) { case Token.STRING: case Token.NUMBER: case Token.TRUE: case Token.FALSE: return true; // Binary operators are only valid if both children are valid. case Token.ADD: case Token.BITAND: case Token.BITNOT: case Token.BITOR: case Token.BITXOR: case Token.DIV: case Token.EQ: case Token.GE: case Token.GT: case Token.LE: case Token.LSH: case Token.LT: case Token.MOD: case Token.MUL: case Token.NE: case Token.RSH: case Token.SHEQ: case Token.SHNE: case Token.SUB: case Token.URSH: return isValidDefineValue(val.getFirstChild(), defines) && isValidDefineValue(val.getLastChild(), defines); // Uniary operators are valid if the child is valid. case Token.NOT: case Token.NEG: case Token.POS: return isValidDefineValue(val.getFirstChild(), defines); // Names are valid if and only if they are defines themselves. case Token.NAME: case Token.GETPROP: if (val.isQualifiedName()) { return defines.contains(val.getQualifiedName()); } } return false; }
src/com/google/javascript/jscomp/NodeUtil.java
Closure-95
void defineSlot(Node n, Node parent, JSType type, boolean inferred) { Preconditions.checkArgument(inferred || type != null); // Only allow declarations of NAMEs and qualfied names. boolean shouldDeclareOnGlobalThis = false; if (n.getType() == Token.NAME) { Preconditions.checkArgument( parent.getType() == Token.FUNCTION || parent.getType() == Token.VAR || parent.getType() == Token.LP || parent.getType() == Token.CATCH); shouldDeclareOnGlobalThis = scope.isGlobal() && (parent.getType() == Token.VAR || parent.getType() == Token.FUNCTION); } else { Preconditions.checkArgument( n.getType() == Token.GETPROP && (parent.getType() == Token.ASSIGN || parent.getType() == Token.EXPR_RESULT)); } String variableName = n.getQualifiedName(); Preconditions.checkArgument(!variableName.isEmpty()); // If n is a property, then we should really declare it in the // scope where the root object appears. This helps out people // who declare "global" names in an anonymous namespace. Scope scopeToDeclareIn = scope; // don't try to declare in the global scope if there's // already a symbol there with this name. // declared in closest scope? if (scopeToDeclareIn.isDeclared(variableName, false)) { Var oldVar = scopeToDeclareIn.getVar(variableName); validator.expectUndeclaredVariable( sourceName, n, parent, oldVar, variableName, type); } else { if (!inferred) { setDeferredType(n, type); } CompilerInput input = compiler.getInput(sourceName); scopeToDeclareIn.declare(variableName, n, type, input, inferred); if (shouldDeclareOnGlobalThis) { ObjectType globalThis = typeRegistry.getNativeObjectType(JSTypeNative.GLOBAL_THIS); boolean isExtern = input.isExtern(); if (inferred) { globalThis.defineInferredProperty(variableName, type == null ? getNativeType(JSTypeNative.NO_TYPE) : type, isExtern); } else { globalThis.defineDeclaredProperty(variableName, type, isExtern); } } // If we're in the global scope, also declare var.prototype // in the scope chain. if (scopeToDeclareIn.isGlobal() && type instanceof FunctionType) { FunctionType fnType = (FunctionType) type; if (fnType.isConstructor() || fnType.isInterface()) { FunctionType superClassCtor = fnType.getSuperClassConstructor(); scopeToDeclareIn.declare(variableName + ".prototype", n, fnType.getPrototype(), compiler.getInput(sourceName), /* declared iff there's an explicit supertype */ superClassCtor == null || superClassCtor.getInstanceType().equals( getNativeType(OBJECT_TYPE))); } } } } void defineSlot(Node n, Node parent, JSType type, boolean inferred) { Preconditions.checkArgument(inferred || type != null); // Only allow declarations of NAMEs and qualfied names. boolean shouldDeclareOnGlobalThis = false; if (n.getType() == Token.NAME) { Preconditions.checkArgument( parent.getType() == Token.FUNCTION || parent.getType() == Token.VAR || parent.getType() == Token.LP || parent.getType() == Token.CATCH); shouldDeclareOnGlobalThis = scope.isGlobal() && (parent.getType() == Token.VAR || parent.getType() == Token.FUNCTION); } else { Preconditions.checkArgument( n.getType() == Token.GETPROP && (parent.getType() == Token.ASSIGN || parent.getType() == Token.EXPR_RESULT)); } String variableName = n.getQualifiedName(); Preconditions.checkArgument(!variableName.isEmpty()); // If n is a property, then we should really declare it in the // scope where the root object appears. This helps out people // who declare "global" names in an anonymous namespace. Scope scopeToDeclareIn = scope; if (n.getType() == Token.GETPROP && !scope.isGlobal() && isQnameRootedInGlobalScope(n)) { Scope globalScope = scope.getGlobalScope(); // don't try to declare in the global scope if there's // already a symbol there with this name. if (!globalScope.isDeclared(variableName, false)) { scopeToDeclareIn = scope.getGlobalScope(); } } // declared in closest scope? if (scopeToDeclareIn.isDeclared(variableName, false)) { Var oldVar = scopeToDeclareIn.getVar(variableName); validator.expectUndeclaredVariable( sourceName, n, parent, oldVar, variableName, type); } else { if (!inferred) { setDeferredType(n, type); } CompilerInput input = compiler.getInput(sourceName); scopeToDeclareIn.declare(variableName, n, type, input, inferred); if (shouldDeclareOnGlobalThis) { ObjectType globalThis = typeRegistry.getNativeObjectType(JSTypeNative.GLOBAL_THIS); boolean isExtern = input.isExtern(); if (inferred) { globalThis.defineInferredProperty(variableName, type == null ? getNativeType(JSTypeNative.NO_TYPE) : type, isExtern); } else { globalThis.defineDeclaredProperty(variableName, type, isExtern); } } // If we're in the global scope, also declare var.prototype // in the scope chain. if (scopeToDeclareIn.isGlobal() && type instanceof FunctionType) { FunctionType fnType = (FunctionType) type; if (fnType.isConstructor() || fnType.isInterface()) { FunctionType superClassCtor = fnType.getSuperClassConstructor(); scopeToDeclareIn.declare(variableName + ".prototype", n, fnType.getPrototype(), compiler.getInput(sourceName), /* declared iff there's an explicit supertype */ superClassCtor == null || superClassCtor.getInstanceType().equals( getNativeType(OBJECT_TYPE))); } } } }
src/com/google/javascript/jscomp/TypedScopeCreator.java
Closure-96
private void visitParameterList(NodeTraversal t, Node call, FunctionType functionType) { Iterator<Node> arguments = call.children().iterator(); arguments.next(); // skip the function name Iterator<Node> parameters = functionType.getParameters().iterator(); int ordinal = 0; Node parameter = null; Node argument = null; while (arguments.hasNext() && parameters.hasNext()) { // If there are no parameters left in the list, then the while loop // above implies that this must be a var_args function. parameter = parameters.next(); argument = arguments.next(); ordinal++; validator.expectArgumentMatchesParameter(t, argument, getJSType(argument), getJSType(parameter), call, ordinal); } int numArgs = call.getChildCount() - 1; int minArgs = functionType.getMinArguments(); int maxArgs = functionType.getMaxArguments(); if (minArgs > numArgs || maxArgs < numArgs) { report(t, call, WRONG_ARGUMENT_COUNT, validator.getReadableJSTypeName(call.getFirstChild(), false), String.valueOf(numArgs), String.valueOf(minArgs), maxArgs != Integer.MAX_VALUE ? " and no more than " + maxArgs + " argument(s)" : ""); } } private void visitParameterList(NodeTraversal t, Node call, FunctionType functionType) { Iterator<Node> arguments = call.children().iterator(); arguments.next(); // skip the function name Iterator<Node> parameters = functionType.getParameters().iterator(); int ordinal = 0; Node parameter = null; Node argument = null; while (arguments.hasNext() && (parameters.hasNext() || parameter != null && parameter.isVarArgs())) { // If there are no parameters left in the list, then the while loop // above implies that this must be a var_args function. if (parameters.hasNext()) { parameter = parameters.next(); } argument = arguments.next(); ordinal++; validator.expectArgumentMatchesParameter(t, argument, getJSType(argument), getJSType(parameter), call, ordinal); } int numArgs = call.getChildCount() - 1; int minArgs = functionType.getMinArguments(); int maxArgs = functionType.getMaxArguments(); if (minArgs > numArgs || maxArgs < numArgs) { report(t, call, WRONG_ARGUMENT_COUNT, validator.getReadableJSTypeName(call.getFirstChild(), false), String.valueOf(numArgs), String.valueOf(minArgs), maxArgs != Integer.MAX_VALUE ? " and no more than " + maxArgs + " argument(s)" : ""); } }
src/com/google/javascript/jscomp/TypeCheck.java
Closure-97
private Node tryFoldShift(Node n, Node left, Node right) { if (left.getType() == Token.NUMBER && right.getType() == Token.NUMBER) { double result; double lval = left.getDouble(); double rval = right.getDouble(); // check ranges. We do not do anything that would clip the double to // a 32-bit range, since the user likely does not intend that. if (!(lval >= Integer.MIN_VALUE && lval <= Integer.MAX_VALUE)) { error(BITWISE_OPERAND_OUT_OF_RANGE, left); return n; } // only the lower 5 bits are used when shifting, so don't do anything // if the shift amount is outside [0,32) if (!(rval >= 0 && rval < 32)) { error(SHIFT_AMOUNT_OUT_OF_BOUNDS, right); return n; } // Convert the numbers to ints int lvalInt = (int) lval; if (lvalInt != lval) { error(FRACTIONAL_BITWISE_OPERAND, left); return n; } int rvalInt = (int) rval; if (rvalInt != rval) { error(FRACTIONAL_BITWISE_OPERAND, right); return n; } switch (n.getType()) { case Token.LSH: result = lvalInt << rvalInt; break; case Token.RSH: result = lvalInt >> rvalInt; break; case Token.URSH: // JavaScript handles zero shifts on signed numbers differently than // Java as an Java int can not represent the unsigned 32-bit number // where JavaScript can so use a long here. result = lvalInt >>> rvalInt; break; default: throw new AssertionError("Unknown shift operator: " + Node.tokenToName(n.getType())); } Node newNumber = Node.newNumber(result); n.getParent().replaceChild(n, newNumber); reportCodeChange(); return newNumber; } return n; } private Node tryFoldShift(Node n, Node left, Node right) { if (left.getType() == Token.NUMBER && right.getType() == Token.NUMBER) { double result; double lval = left.getDouble(); double rval = right.getDouble(); // check ranges. We do not do anything that would clip the double to // a 32-bit range, since the user likely does not intend that. if (!(lval >= Integer.MIN_VALUE && lval <= Integer.MAX_VALUE)) { error(BITWISE_OPERAND_OUT_OF_RANGE, left); return n; } // only the lower 5 bits are used when shifting, so don't do anything // if the shift amount is outside [0,32) if (!(rval >= 0 && rval < 32)) { error(SHIFT_AMOUNT_OUT_OF_BOUNDS, right); return n; } // Convert the numbers to ints int lvalInt = (int) lval; if (lvalInt != lval) { error(FRACTIONAL_BITWISE_OPERAND, left); return n; } int rvalInt = (int) rval; if (rvalInt != rval) { error(FRACTIONAL_BITWISE_OPERAND, right); return n; } switch (n.getType()) { case Token.LSH: result = lvalInt << rvalInt; break; case Token.RSH: result = lvalInt >> rvalInt; break; case Token.URSH: // JavaScript handles zero shifts on signed numbers differently than // Java as an Java int can not represent the unsigned 32-bit number // where JavaScript can so use a long here. long lvalLong = lvalInt & 0xffffffffL; result = lvalLong >>> rvalInt; break; default: throw new AssertionError("Unknown shift operator: " + Node.tokenToName(n.getType())); } Node newNumber = Node.newNumber(result); n.getParent().replaceChild(n, newNumber); reportCodeChange(); return newNumber; } return n; }
src/com/google/javascript/jscomp/PeepholeFoldConstants.java
Closure-99
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.getType() == Token.FUNCTION) { // Don't traverse functions that are constructors or have the @this // or @override annotation. JSDocInfo jsDoc = getFunctionJsDocInfo(n); if (jsDoc != null && (jsDoc.isConstructor() || jsDoc.hasThisType() || jsDoc.isOverride())) { return false; } // Don't traverse functions unless they would normally // be able to have a @this annotation associated with them. e.g., // var a = function() { }; // or // function a() {} // or // a.x = function() {}; int pType = parent.getType(); if (!(pType == Token.BLOCK || pType == Token.SCRIPT || pType == Token.NAME || pType == Token.ASSIGN)) { return false; } } if (parent != null && parent.getType() == Token.ASSIGN) { Node lhs = parent.getFirstChild(); Node rhs = lhs.getNext(); if (n == lhs) { // Always traverse the left side of the assignment. To handle // nested assignments properly (e.g., (a = this).property = c;), // assignLhsChild should not be overridden. if (assignLhsChild == null) { assignLhsChild = lhs; } } else { // Only traverse the right side if it's not an assignment to a prototype // property or subproperty. if (lhs.getType() == Token.GETPROP && lhs.getLastChild().getString().equals("prototype")) { return false; } if (lhs.getQualifiedName() != null && lhs.getQualifiedName().contains(".prototype.")) { return false; } } } return true; } public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) { if (n.getType() == Token.FUNCTION) { // Don't traverse functions that are constructors or have the @this // or @override annotation. JSDocInfo jsDoc = getFunctionJsDocInfo(n); if (jsDoc != null && (jsDoc.isConstructor() || jsDoc.isInterface() || jsDoc.hasThisType() || jsDoc.isOverride())) { return false; } // Don't traverse functions unless they would normally // be able to have a @this annotation associated with them. e.g., // var a = function() { }; // or // function a() {} // or // a.x = function() {}; int pType = parent.getType(); if (!(pType == Token.BLOCK || pType == Token.SCRIPT || pType == Token.NAME || pType == Token.ASSIGN)) { return false; } } if (parent != null && parent.getType() == Token.ASSIGN) { Node lhs = parent.getFirstChild(); Node rhs = lhs.getNext(); if (n == lhs) { // Always traverse the left side of the assignment. To handle // nested assignments properly (e.g., (a = this).property = c;), // assignLhsChild should not be overridden. if (assignLhsChild == null) { assignLhsChild = lhs; } } else { // Only traverse the right side if it's not an assignment to a prototype // property or subproperty. if (NodeUtil.isGet(lhs)) { if (lhs.getType() == Token.GETPROP && lhs.getLastChild().getString().equals("prototype")) { return false; } Node llhs = lhs.getFirstChild(); if (llhs.getType() == Token.GETPROP && llhs.getLastChild().getString().equals("prototype")) { return false; } } } } return true; }
src/com/google/javascript/jscomp/CheckGlobalThis.java
Codec-10
public String caverphone(String txt) { // NOTE: Version 1.0 of Caverphone is easily derivable from this code // by commenting out the 2.0 lines and adding in the 1.0 lines if( txt == null || txt.length() == 0 ) { return "1111111111"; } // 1. Convert to lowercase txt = txt.toLowerCase(java.util.Locale.ENGLISH); // 2. Remove anything not A-Z txt = txt.replaceAll("[^a-z]", ""); // 2.5. Remove final e txt = txt.replaceAll("e$", ""); // 2.0 only // 3. Handle various start options txt = txt.replaceAll("^cough", "cou2f"); txt = txt.replaceAll("^rough", "rou2f"); txt = txt.replaceAll("^tough", "tou2f"); txt = txt.replaceAll("^enough", "enou2f"); // 2.0 only txt = txt.replaceAll("^trough", "trou2f"); // 2.0 only - note the spec says ^enough here again, c+p error I assume txt = txt.replaceAll("^gn", "2n"); // End txt = txt.replaceAll("^mb", "m2"); // 4. Handle replacements txt = txt.replaceAll("cq", "2q"); txt = txt.replaceAll("ci", "si"); txt = txt.replaceAll("ce", "se"); txt = txt.replaceAll("cy", "sy"); txt = txt.replaceAll("tch", "2ch"); txt = txt.replaceAll("c", "k"); txt = txt.replaceAll("q", "k"); txt = txt.replaceAll("x", "k"); txt = txt.replaceAll("v", "f"); txt = txt.replaceAll("dg", "2g"); txt = txt.replaceAll("tio", "sio"); txt = txt.replaceAll("tia", "sia"); txt = txt.replaceAll("d", "t"); txt = txt.replaceAll("ph", "fh"); txt = txt.replaceAll("b", "p"); txt = txt.replaceAll("sh", "s2"); txt = txt.replaceAll("z", "s"); txt = txt.replaceAll("^[aeiou]", "A"); txt = txt.replaceAll("[aeiou]", "3"); txt = txt.replaceAll("j", "y"); // 2.0 only txt = txt.replaceAll("^y3", "Y3"); // 2.0 only txt = txt.replaceAll("^y", "A"); // 2.0 only txt = txt.replaceAll("y", "3"); // 2.0 only txt = txt.replaceAll("3gh3", "3kh3"); txt = txt.replaceAll("gh", "22"); txt = txt.replaceAll("g", "k"); txt = txt.replaceAll("s+", "S"); txt = txt.replaceAll("t+", "T"); txt = txt.replaceAll("p+", "P"); txt = txt.replaceAll("k+", "K"); txt = txt.replaceAll("f+", "F"); txt = txt.replaceAll("m+", "M"); txt = txt.replaceAll("n+", "N"); txt = txt.replaceAll("w3", "W3"); //txt = txt.replaceAll("wy", "Wy"); // 1.0 only txt = txt.replaceAll("wh3", "Wh3"); txt = txt.replaceAll("w$", "3"); // 2.0 only //txt = txt.replaceAll("why", "Why"); // 1.0 only txt = txt.replaceAll("w", "2"); txt = txt.replaceAll("^h", "A"); txt = txt.replaceAll("h", "2"); txt = txt.replaceAll("r3", "R3"); txt = txt.replaceAll("r$", "3"); // 2.0 only //txt = txt.replaceAll("ry", "Ry"); // 1.0 only txt = txt.replaceAll("r", "2"); txt = txt.replaceAll("l3", "L3"); txt = txt.replaceAll("l$", "3"); // 2.0 only //txt = txt.replaceAll("ly", "Ly"); // 1.0 only txt = txt.replaceAll("l", "2"); //txt = txt.replaceAll("j", "y"); // 1.0 only //txt = txt.replaceAll("y3", "Y3"); // 1.0 only //txt = txt.replaceAll("y", "2"); // 1.0 only // 5. Handle removals txt = txt.replaceAll("2", ""); txt = txt.replaceAll("3$", "A"); // 2.0 only txt = txt.replaceAll("3", ""); // 6. put ten 1s on the end txt = txt + "111111" + "1111"; // 1.0 only has 6 1s // 7. take the first six characters as the code return txt.substring(0, 10); // 1.0 truncates to 6 } public String caverphone(String txt) { // NOTE: Version 1.0 of Caverphone is easily derivable from this code // by commenting out the 2.0 lines and adding in the 1.0 lines if( txt == null || txt.length() == 0 ) { return "1111111111"; } // 1. Convert to lowercase txt = txt.toLowerCase(java.util.Locale.ENGLISH); // 2. Remove anything not A-Z txt = txt.replaceAll("[^a-z]", ""); // 2.5. Remove final e txt = txt.replaceAll("e$", ""); // 2.0 only // 3. Handle various start options txt = txt.replaceAll("^cough", "cou2f"); txt = txt.replaceAll("^rough", "rou2f"); txt = txt.replaceAll("^tough", "tou2f"); txt = txt.replaceAll("^enough", "enou2f"); // 2.0 only txt = txt.replaceAll("^trough", "trou2f"); // 2.0 only - note the spec says ^enough here again, c+p error I assume txt = txt.replaceAll("^gn", "2n"); // End txt = txt.replaceAll("mb$", "m2"); // 4. Handle replacements txt = txt.replaceAll("cq", "2q"); txt = txt.replaceAll("ci", "si"); txt = txt.replaceAll("ce", "se"); txt = txt.replaceAll("cy", "sy"); txt = txt.replaceAll("tch", "2ch"); txt = txt.replaceAll("c", "k"); txt = txt.replaceAll("q", "k"); txt = txt.replaceAll("x", "k"); txt = txt.replaceAll("v", "f"); txt = txt.replaceAll("dg", "2g"); txt = txt.replaceAll("tio", "sio"); txt = txt.replaceAll("tia", "sia"); txt = txt.replaceAll("d", "t"); txt = txt.replaceAll("ph", "fh"); txt = txt.replaceAll("b", "p"); txt = txt.replaceAll("sh", "s2"); txt = txt.replaceAll("z", "s"); txt = txt.replaceAll("^[aeiou]", "A"); txt = txt.replaceAll("[aeiou]", "3"); txt = txt.replaceAll("j", "y"); // 2.0 only txt = txt.replaceAll("^y3", "Y3"); // 2.0 only txt = txt.replaceAll("^y", "A"); // 2.0 only txt = txt.replaceAll("y", "3"); // 2.0 only txt = txt.replaceAll("3gh3", "3kh3"); txt = txt.replaceAll("gh", "22"); txt = txt.replaceAll("g", "k"); txt = txt.replaceAll("s+", "S"); txt = txt.replaceAll("t+", "T"); txt = txt.replaceAll("p+", "P"); txt = txt.replaceAll("k+", "K"); txt = txt.replaceAll("f+", "F"); txt = txt.replaceAll("m+", "M"); txt = txt.replaceAll("n+", "N"); txt = txt.replaceAll("w3", "W3"); //txt = txt.replaceAll("wy", "Wy"); // 1.0 only txt = txt.replaceAll("wh3", "Wh3"); txt = txt.replaceAll("w$", "3"); // 2.0 only //txt = txt.replaceAll("why", "Why"); // 1.0 only txt = txt.replaceAll("w", "2"); txt = txt.replaceAll("^h", "A"); txt = txt.replaceAll("h", "2"); txt = txt.replaceAll("r3", "R3"); txt = txt.replaceAll("r$", "3"); // 2.0 only //txt = txt.replaceAll("ry", "Ry"); // 1.0 only txt = txt.replaceAll("r", "2"); txt = txt.replaceAll("l3", "L3"); txt = txt.replaceAll("l$", "3"); // 2.0 only //txt = txt.replaceAll("ly", "Ly"); // 1.0 only txt = txt.replaceAll("l", "2"); //txt = txt.replaceAll("j", "y"); // 1.0 only //txt = txt.replaceAll("y3", "Y3"); // 1.0 only //txt = txt.replaceAll("y", "2"); // 1.0 only // 5. Handle removals txt = txt.replaceAll("2", ""); txt = txt.replaceAll("3$", "A"); // 2.0 only txt = txt.replaceAll("3", ""); // 6. put ten 1s on the end txt = txt + "111111" + "1111"; // 1.0 only has 6 1s // 7. take the first six characters as the code return txt.substring(0, 10); // 1.0 truncates to 6 }
src/java/org/apache/commons/codec/language/Caverphone.java
Codec-15
private char getMappingCode(final String str, final int index) { // map() throws IllegalArgumentException final char mappedChar = this.map(str.charAt(index)); // HW rule check if (index > 1 && mappedChar != '0') { final char hwChar = str.charAt(index - 1); if ('H' == hwChar || 'W' == hwChar) { final char preHWChar = str.charAt(index - 2); final char firstCode = this.map(preHWChar); if (firstCode == mappedChar || 'H' == preHWChar || 'W' == preHWChar) { return 0; } } } return mappedChar; } private char getMappingCode(final String str, final int index) { // map() throws IllegalArgumentException final char mappedChar = this.map(str.charAt(index)); // HW rule check if (index > 1 && mappedChar != '0') { for (int i=index-1 ; i>=0 ; i--) { final char prevChar = str.charAt(i); if (this.map(prevChar)==mappedChar) { return 0; } if ('H'!=prevChar && 'W'!=prevChar) { break; } } } return mappedChar; }
src/main/java/org/apache/commons/codec/language/Soundex.java
Codec-17
public static String newStringIso8859_1(final byte[] bytes) { return new String(bytes, Charsets.ISO_8859_1); } public static String newStringIso8859_1(final byte[] bytes) { return newString(bytes, Charsets.ISO_8859_1); }
src/main/java/org/apache/commons/codec/binary/StringUtils.java
Codec-18
public static boolean equals(final CharSequence cs1, final CharSequence cs2) { if (cs1 == cs2) { return true; } if (cs1 == null || cs2 == null) { return false; } if (cs1 instanceof String && cs2 instanceof String) { return cs1.equals(cs2); } return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length())); } public static boolean equals(final CharSequence cs1, final CharSequence cs2) { if (cs1 == cs2) { return true; } if (cs1 == null || cs2 == null) { return false; } if (cs1 instanceof String && cs2 instanceof String) { return cs1.equals(cs2); } return cs1.length() == cs2.length() && CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, cs1.length()); }
src/main/java/org/apache/commons/codec/binary/StringUtils.java
Codec-2
void encode(byte[] in, int inPos, int inAvail) { if (eof) { return; } // inAvail < 0 is how we're informed of EOF in the underlying data we're // encoding. if (inAvail < 0) { eof = true; if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } switch (modulus) { case 1: buf[pos++] = encodeTable[(x >> 2) & MASK_6BITS]; buf[pos++] = encodeTable[(x << 4) & MASK_6BITS]; // URL-SAFE skips the padding to further reduce size. if (encodeTable == STANDARD_ENCODE_TABLE) { buf[pos++] = PAD; buf[pos++] = PAD; } break; case 2: buf[pos++] = encodeTable[(x >> 10) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 4) & MASK_6BITS]; buf[pos++] = encodeTable[(x << 2) & MASK_6BITS]; // URL-SAFE skips the padding to further reduce size. if (encodeTable == STANDARD_ENCODE_TABLE) { buf[pos++] = PAD; } break; } if (lineLength > 0) { System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length); pos += lineSeparator.length; } } else { for (int i = 0; i < inAvail; i++) { if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } modulus = (++modulus) % 3; int b = in[inPos++]; if (b < 0) { b += 256; } x = (x << 8) + b; if (0 == modulus) { buf[pos++] = encodeTable[(x >> 18) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 12) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 6) & MASK_6BITS]; buf[pos++] = encodeTable[x & MASK_6BITS]; currentLinePos += 4; if (lineLength > 0 && lineLength <= currentLinePos) { System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length); pos += lineSeparator.length; currentLinePos = 0; } } } } } void encode(byte[] in, int inPos, int inAvail) { if (eof) { return; } // inAvail < 0 is how we're informed of EOF in the underlying data we're // encoding. if (inAvail < 0) { eof = true; if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } switch (modulus) { case 1: buf[pos++] = encodeTable[(x >> 2) & MASK_6BITS]; buf[pos++] = encodeTable[(x << 4) & MASK_6BITS]; // URL-SAFE skips the padding to further reduce size. if (encodeTable == STANDARD_ENCODE_TABLE) { buf[pos++] = PAD; buf[pos++] = PAD; } break; case 2: buf[pos++] = encodeTable[(x >> 10) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 4) & MASK_6BITS]; buf[pos++] = encodeTable[(x << 2) & MASK_6BITS]; // URL-SAFE skips the padding to further reduce size. if (encodeTable == STANDARD_ENCODE_TABLE) { buf[pos++] = PAD; } break; } if (lineLength > 0 && pos > 0) { System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length); pos += lineSeparator.length; } } else { for (int i = 0; i < inAvail; i++) { if (buf == null || buf.length - pos < encodeSize) { resizeBuf(); } modulus = (++modulus) % 3; int b = in[inPos++]; if (b < 0) { b += 256; } x = (x << 8) + b; if (0 == modulus) { buf[pos++] = encodeTable[(x >> 18) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 12) & MASK_6BITS]; buf[pos++] = encodeTable[(x >> 6) & MASK_6BITS]; buf[pos++] = encodeTable[x & MASK_6BITS]; currentLinePos += 4; if (lineLength > 0 && lineLength <= currentLinePos) { System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length); pos += lineSeparator.length; currentLinePos = 0; } } } } }
src/java/org/apache/commons/codec/binary/Base64.java
Codec-3
private int handleG(String value, DoubleMetaphoneResult result, int index, boolean slavoGermanic) { if (charAt(value, index + 1) == 'H') { index = handleGH(value, result, index); } else if (charAt(value, index + 1) == 'N') { if (index == 1 && isVowel(charAt(value, 0)) && !slavoGermanic) { result.append("KN", "N"); } else if (!contains(value, index + 2, 2, "EY") && charAt(value, index + 1) != 'Y' && !slavoGermanic) { result.append("N", "KN"); } else { result.append("KN"); } index = index + 2; } else if (contains(value, index + 1, 2, "LI") && !slavoGermanic) { result.append("KL", "L"); index += 2; } else if (index == 0 && (charAt(value, index + 1) == 'Y' || contains(value, index + 1, 2, ES_EP_EB_EL_EY_IB_IL_IN_IE_EI_ER))) { //-- -ges-, -gep-, -gel-, -gie- at beginning --// result.append('K', 'J'); index += 2; } else if ((contains(value, index + 1, 2, "ER") || charAt(value, index + 1) == 'Y') && !contains(value, 0, 6, "DANGER", "RANGER", "MANGER") && !contains(value, index - 1, 1, "E", "I") && !contains(value, index - 1, 3, "RGY", "OGY")) { //-- -ger-, -gy- --// result.append('K', 'J'); index += 2; } else if (contains(value, index + 1, 1, "E", "I", "Y") || contains(value, index - 1, 4, "AGGI", "OGGI")) { //-- Italian "biaggi" --// if ((contains(value, 0 ,4, "VAN ", "VON ") || contains(value, 0, 3, "SCH")) || contains(value, index + 1, 2, "ET")) { //-- obvious germanic --// result.append('K'); } else if (contains(value, index + 1, 4, "IER")) { result.append('J'); } else { result.append('J', 'K'); } index += 2; } else if (charAt(value, index + 1) == 'G') { index += 2; result.append('K'); } else { index++; result.append('K'); } return index; } private int handleG(String value, DoubleMetaphoneResult result, int index, boolean slavoGermanic) { if (charAt(value, index + 1) == 'H') { index = handleGH(value, result, index); } else if (charAt(value, index + 1) == 'N') { if (index == 1 && isVowel(charAt(value, 0)) && !slavoGermanic) { result.append("KN", "N"); } else if (!contains(value, index + 2, 2, "EY") && charAt(value, index + 1) != 'Y' && !slavoGermanic) { result.append("N", "KN"); } else { result.append("KN"); } index = index + 2; } else if (contains(value, index + 1, 2, "LI") && !slavoGermanic) { result.append("KL", "L"); index += 2; } else if (index == 0 && (charAt(value, index + 1) == 'Y' || contains(value, index + 1, 2, ES_EP_EB_EL_EY_IB_IL_IN_IE_EI_ER))) { //-- -ges-, -gep-, -gel-, -gie- at beginning --// result.append('K', 'J'); index += 2; } else if ((contains(value, index + 1, 2, "ER") || charAt(value, index + 1) == 'Y') && !contains(value, 0, 6, "DANGER", "RANGER", "MANGER") && !contains(value, index - 1, 1, "E", "I") && !contains(value, index - 1, 3, "RGY", "OGY")) { //-- -ger-, -gy- --// result.append('K', 'J'); index += 2; } else if (contains(value, index + 1, 1, "E", "I", "Y") || contains(value, index - 1, 4, "AGGI", "OGGI")) { //-- Italian "biaggi" --// if ((contains(value, 0 ,4, "VAN ", "VON ") || contains(value, 0, 3, "SCH")) || contains(value, index + 1, 2, "ET")) { //-- obvious germanic --// result.append('K'); } else if (contains(value, index + 1, 3, "IER")) { result.append('J'); } else { result.append('J', 'K'); } index += 2; } else if (charAt(value, index + 1) == 'G') { index += 2; result.append('K'); } else { index++; result.append('K'); } return index; }
src/java/org/apache/commons/codec/language/DoubleMetaphone.java
Codec-4
public Base64() { this(false); } public Base64() { this(0); }
src/java/org/apache/commons/codec/binary/Base64.java
Codec-5
void decode(byte[] in, int inPos, int inAvail) { if (eof) { return; } if (inAvail < 0) { eof = true; } for (int i = 0; i < inAvail; i++) { if (buffer == null || buffer.length - pos < decodeSize) { resizeBuffer(); } byte b = in[inPos++]; if (b == PAD) { // We're done. eof = true; break; } else { if (b >= 0 && b < DECODE_TABLE.length) { int result = DECODE_TABLE[b]; if (result >= 0) { modulus = (++modulus) % 4; x = (x << 6) + result; if (modulus == 0) { buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS); buffer[pos++] = (byte) (x & MASK_8BITS); } } } } } // Two forms of EOF as far as base64 decoder is concerned: actual // EOF (-1) and first time '=' character is encountered in stream. // This approach makes the '=' padding characters completely optional. if (eof && modulus != 0) { x = x << 6; switch (modulus) { case 2 : x = x << 6; buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); break; case 3 : buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS); break; } } } void decode(byte[] in, int inPos, int inAvail) { if (eof) { return; } if (inAvail < 0) { eof = true; } for (int i = 0; i < inAvail; i++) { if (buffer == null || buffer.length - pos < decodeSize) { resizeBuffer(); } byte b = in[inPos++]; if (b == PAD) { // We're done. eof = true; break; } else { if (b >= 0 && b < DECODE_TABLE.length) { int result = DECODE_TABLE[b]; if (result >= 0) { modulus = (++modulus) % 4; x = (x << 6) + result; if (modulus == 0) { buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS); buffer[pos++] = (byte) (x & MASK_8BITS); } } } } } // Two forms of EOF as far as base64 decoder is concerned: actual // EOF (-1) and first time '=' character is encountered in stream. // This approach makes the '=' padding characters completely optional. if (eof && modulus != 0) { if (buffer == null || buffer.length - pos < decodeSize) { resizeBuffer(); } x = x << 6; switch (modulus) { case 2 : x = x << 6; buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); break; case 3 : buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS); buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS); break; } } }
src/java/org/apache/commons/codec/binary/Base64.java
Codec-6
public int read(byte b[], int offset, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (offset < 0 || len < 0) { throw new IndexOutOfBoundsException(); } else if (offset > b.length || offset + len > b.length) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } else { /* Rationale for while-loop on (readLen == 0): ----- Base64.readResults() usually returns > 0 or EOF (-1). In the rare case where it returns 0, we just keep trying. This is essentially an undocumented contract for InputStream implementors that want their code to work properly with java.io.InputStreamReader, since the latter hates it when InputStream.read(byte[]) returns a zero. Unfortunately our readResults() call must return 0 if a large amount of the data being decoded was non-base64, so this while-loop enables proper interop with InputStreamReader for that scenario. ----- This is a fix for CODEC-101 */ if (!base64.hasData()) { byte[] buf = new byte[doEncode ? 4096 : 8192]; int c = in.read(buf); // A little optimization to avoid System.arraycopy() // when possible. if (c > 0 && b.length == len) { base64.setInitialBuffer(b, offset, len); } if (doEncode) { base64.encode(buf, 0, c); } else { base64.decode(buf, 0, c); } } return base64.readResults(b, offset, len); } } public int read(byte b[], int offset, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (offset < 0 || len < 0) { throw new IndexOutOfBoundsException(); } else if (offset > b.length || offset + len > b.length) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } else { int readLen = 0; /* Rationale for while-loop on (readLen == 0): ----- Base64.readResults() usually returns > 0 or EOF (-1). In the rare case where it returns 0, we just keep trying. This is essentially an undocumented contract for InputStream implementors that want their code to work properly with java.io.InputStreamReader, since the latter hates it when InputStream.read(byte[]) returns a zero. Unfortunately our readResults() call must return 0 if a large amount of the data being decoded was non-base64, so this while-loop enables proper interop with InputStreamReader for that scenario. ----- This is a fix for CODEC-101 */ while (readLen == 0) { if (!base64.hasData()) { byte[] buf = new byte[doEncode ? 4096 : 8192]; int c = in.read(buf); // A little optimization to avoid System.arraycopy() // when possible. if (c > 0 && b.length == len) { base64.setInitialBuffer(b, offset, len); } if (doEncode) { base64.encode(buf, 0, c); } else { base64.decode(buf, 0, c); } } readLen = base64.readResults(b, offset, len); } return readLen; } }
src/java/org/apache/commons/codec/binary/Base64InputStream.java
Codec-7
public static String encodeBase64String(byte[] binaryData) { return StringUtils.newStringUtf8(encodeBase64(binaryData, true)); } public static String encodeBase64String(byte[] binaryData) { return StringUtils.newStringUtf8(encodeBase64(binaryData, false)); }
src/java/org/apache/commons/codec/binary/Base64.java
Codec-9
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) { if (binaryData == null || binaryData.length == 0) { return binaryData; } long len = getEncodeLength(binaryData, MIME_CHUNK_SIZE, CHUNK_SEPARATOR); if (len > maxResultSize) { throw new IllegalArgumentException("Input array too big, the output array would be bigger (" + len + ") than the specified maxium size of " + maxResultSize); } Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe); return b64.encode(binaryData); } public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) { if (binaryData == null || binaryData.length == 0) { return binaryData; } long len = getEncodeLength(binaryData, isChunked ? MIME_CHUNK_SIZE : 0, CHUNK_SEPARATOR); if (len > maxResultSize) { throw new IllegalArgumentException("Input array too big, the output array would be bigger (" + len + ") than the specified maxium size of " + maxResultSize); } Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe); return b64.encode(binaryData); }
src/java/org/apache/commons/codec/binary/Base64.java
Collections-26
private Object readResolve() { calculateHashCode(keys); return this; } protected Object readResolve() { calculateHashCode(keys); return this; }
src/main/java/org/apache/commons/collections4/keyvalue/MultiKey.java
Compress-1
public void close() throws IOException { if (!this.closed) { super.close(); this.closed = true; } } public void close() throws IOException { if (!this.closed) { this.finish(); super.close(); this.closed = true; } }
src/main/java/org/apache/commons/compress/archivers/cpio/CpioArchiveOutputStream.java
Compress-10
private void resolveLocalFileHeaderData(Map<ZipArchiveEntry, NameAndComment> entriesWithoutUTF8Flag) throws IOException { // changing the name of a ZipArchiveEntry is going to change // the hashcode - see COMPRESS-164 // Map needs to be reconstructed in order to keep central // directory order for (ZipArchiveEntry ze : entries.keySet()) { OffsetEntry offsetEntry = entries.get(ze); long offset = offsetEntry.headerOffset; archive.seek(offset + LFH_OFFSET_FOR_FILENAME_LENGTH); byte[] b = new byte[SHORT]; archive.readFully(b); int fileNameLen = ZipShort.getValue(b); archive.readFully(b); int extraFieldLen = ZipShort.getValue(b); int lenToSkip = fileNameLen; while (lenToSkip > 0) { int skipped = archive.skipBytes(lenToSkip); if (skipped <= 0) { throw new RuntimeException("failed to skip file name in" + " local file header"); } lenToSkip -= skipped; } byte[] localExtraData = new byte[extraFieldLen]; archive.readFully(localExtraData); ze.setExtra(localExtraData); offsetEntry.dataOffset = offset + LFH_OFFSET_FOR_FILENAME_LENGTH + SHORT + SHORT + fileNameLen + extraFieldLen; if (entriesWithoutUTF8Flag.containsKey(ze)) { String orig = ze.getName(); NameAndComment nc = entriesWithoutUTF8Flag.get(ze); ZipUtil.setNameAndCommentFromExtraFields(ze, nc.name, nc.comment); if (!orig.equals(ze.getName())) { nameMap.remove(orig); nameMap.put(ze.getName(), ze); } } } } private void resolveLocalFileHeaderData(Map<ZipArchiveEntry, NameAndComment> entriesWithoutUTF8Flag) throws IOException { // changing the name of a ZipArchiveEntry is going to change // the hashcode - see COMPRESS-164 // Map needs to be reconstructed in order to keep central // directory order Map<ZipArchiveEntry, OffsetEntry> origMap = new LinkedHashMap<ZipArchiveEntry, OffsetEntry>(entries); entries.clear(); for (ZipArchiveEntry ze : origMap.keySet()) { OffsetEntry offsetEntry = origMap.get(ze); long offset = offsetEntry.headerOffset; archive.seek(offset + LFH_OFFSET_FOR_FILENAME_LENGTH); byte[] b = new byte[SHORT]; archive.readFully(b); int fileNameLen = ZipShort.getValue(b); archive.readFully(b); int extraFieldLen = ZipShort.getValue(b); int lenToSkip = fileNameLen; while (lenToSkip > 0) { int skipped = archive.skipBytes(lenToSkip); if (skipped <= 0) { throw new RuntimeException("failed to skip file name in" + " local file header"); } lenToSkip -= skipped; } byte[] localExtraData = new byte[extraFieldLen]; archive.readFully(localExtraData); ze.setExtra(localExtraData); offsetEntry.dataOffset = offset + LFH_OFFSET_FOR_FILENAME_LENGTH + SHORT + SHORT + fileNameLen + extraFieldLen; if (entriesWithoutUTF8Flag.containsKey(ze)) { String orig = ze.getName(); NameAndComment nc = entriesWithoutUTF8Flag.get(ze); ZipUtil.setNameAndCommentFromExtraFields(ze, nc.name, nc.comment); if (!orig.equals(ze.getName())) { nameMap.remove(orig); nameMap.put(ze.getName(), ze); } } entries.put(ze, offsetEntry); } }
src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java
Compress-11
public ArchiveInputStream createArchiveInputStream(final InputStream in) throws ArchiveException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } final byte[] signature = new byte[12]; in.mark(signature.length); try { int signatureLength = in.read(signature); in.reset(); if (ZipArchiveInputStream.matches(signature, signatureLength)) { return new ZipArchiveInputStream(in); } else if (JarArchiveInputStream.matches(signature, signatureLength)) { return new JarArchiveInputStream(in); } else if (ArArchiveInputStream.matches(signature, signatureLength)) { return new ArArchiveInputStream(in); } else if (CpioArchiveInputStream.matches(signature, signatureLength)) { return new CpioArchiveInputStream(in); } // Dump needs a bigger buffer to check the signature; final byte[] dumpsig = new byte[32]; in.mark(dumpsig.length); signatureLength = in.read(dumpsig); in.reset(); if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) { return new DumpArchiveInputStream(in); } // Tar needs an even bigger buffer to check the signature; read the first block final byte[] tarheader = new byte[512]; in.mark(tarheader.length); signatureLength = in.read(tarheader); in.reset(); if (TarArchiveInputStream.matches(tarheader, signatureLength)) { return new TarArchiveInputStream(in); } // COMPRESS-117 - improve auto-recognition try { TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader)); tais.getNextEntry(); return new TarArchiveInputStream(in); } catch (Exception e) { // NOPMD // can generate IllegalArgumentException as well as IOException // autodetection, simply not a TAR // ignored } } catch (IOException e) { throw new ArchiveException("Could not use reset and mark operations.", e); } throw new ArchiveException("No Archiver found for the stream signature"); } public ArchiveInputStream createArchiveInputStream(final InputStream in) throws ArchiveException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } final byte[] signature = new byte[12]; in.mark(signature.length); try { int signatureLength = in.read(signature); in.reset(); if (ZipArchiveInputStream.matches(signature, signatureLength)) { return new ZipArchiveInputStream(in); } else if (JarArchiveInputStream.matches(signature, signatureLength)) { return new JarArchiveInputStream(in); } else if (ArArchiveInputStream.matches(signature, signatureLength)) { return new ArArchiveInputStream(in); } else if (CpioArchiveInputStream.matches(signature, signatureLength)) { return new CpioArchiveInputStream(in); } // Dump needs a bigger buffer to check the signature; final byte[] dumpsig = new byte[32]; in.mark(dumpsig.length); signatureLength = in.read(dumpsig); in.reset(); if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) { return new DumpArchiveInputStream(in); } // Tar needs an even bigger buffer to check the signature; read the first block final byte[] tarheader = new byte[512]; in.mark(tarheader.length); signatureLength = in.read(tarheader); in.reset(); if (TarArchiveInputStream.matches(tarheader, signatureLength)) { return new TarArchiveInputStream(in); } // COMPRESS-117 - improve auto-recognition if (signatureLength >= 512) { try { TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader)); tais.getNextEntry(); return new TarArchiveInputStream(in); } catch (Exception e) { // NOPMD // can generate IllegalArgumentException as well as IOException // autodetection, simply not a TAR // ignored } } } catch (IOException e) { throw new ArchiveException("Could not use reset and mark operations.", e); } throw new ArchiveException("No Archiver found for the stream signature"); }
src/main/java/org/apache/commons/compress/archivers/ArchiveStreamFactory.java
Compress-12
public TarArchiveEntry getNextTarEntry() throws IOException { if (hasHitEOF) { return null; } if (currEntry != null) { long numToSkip = entrySize - entryOffset; while (numToSkip > 0) { long skipped = skip(numToSkip); if (skipped <= 0) { throw new RuntimeException("failed to skip current tar entry"); } numToSkip -= skipped; } readBuf = null; } byte[] headerBuf = getRecord(); if (hasHitEOF) { currEntry = null; return null; } currEntry = new TarArchiveEntry(headerBuf); entryOffset = 0; entrySize = currEntry.getSize(); if (currEntry.isGNULongNameEntry()) { // read in the name StringBuffer longName = new StringBuffer(); byte[] buf = new byte[SMALL_BUFFER_SIZE]; int length = 0; while ((length = read(buf)) >= 0) { longName.append(new String(buf, 0, length)); } getNextEntry(); if (currEntry == null) { // Bugzilla: 40334 // Malformed tar file - long entry name not followed by entry return null; } // remove trailing null terminator if (longName.length() > 0 && longName.charAt(longName.length() - 1) == 0) { longName.deleteCharAt(longName.length() - 1); } currEntry.setName(longName.toString()); } if (currEntry.isPaxHeader()){ // Process Pax headers paxHeaders(); } if (currEntry.isGNUSparse()){ // Process sparse files readGNUSparse(); } // If the size of the next element in the archive has changed // due to a new size being reported in the posix header // information, we update entrySize here so that it contains // the correct value. entrySize = currEntry.getSize(); return currEntry; } public TarArchiveEntry getNextTarEntry() throws IOException { if (hasHitEOF) { return null; } if (currEntry != null) { long numToSkip = entrySize - entryOffset; while (numToSkip > 0) { long skipped = skip(numToSkip); if (skipped <= 0) { throw new RuntimeException("failed to skip current tar entry"); } numToSkip -= skipped; } readBuf = null; } byte[] headerBuf = getRecord(); if (hasHitEOF) { currEntry = null; return null; } try { currEntry = new TarArchiveEntry(headerBuf); } catch (IllegalArgumentException e) { IOException ioe = new IOException("Error detected parsing the header"); ioe.initCause(e); throw ioe; } entryOffset = 0; entrySize = currEntry.getSize(); if (currEntry.isGNULongNameEntry()) { // read in the name StringBuffer longName = new StringBuffer(); byte[] buf = new byte[SMALL_BUFFER_SIZE]; int length = 0; while ((length = read(buf)) >= 0) { longName.append(new String(buf, 0, length)); } getNextEntry(); if (currEntry == null) { // Bugzilla: 40334 // Malformed tar file - long entry name not followed by entry return null; } // remove trailing null terminator if (longName.length() > 0 && longName.charAt(longName.length() - 1) == 0) { longName.deleteCharAt(longName.length() - 1); } currEntry.setName(longName.toString()); } if (currEntry.isPaxHeader()){ // Process Pax headers paxHeaders(); } if (currEntry.isGNUSparse()){ // Process sparse files readGNUSparse(); } // If the size of the next element in the archive has changed // due to a new size being reported in the posix header // information, we update entrySize here so that it contains // the correct value. entrySize = currEntry.getSize(); return currEntry; }
src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
Compress-13
protected void setName(String name) { this.name = name; } protected void setName(String name) { if (name != null && getPlatform() == PLATFORM_FAT && name.indexOf("/") == -1) { name = name.replace('\\', '/'); } this.name = name; }
src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java
Compress-14
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } boolean allNUL = true; for (int i = start; i < end; i++){ if (buffer[i] != 0){ allNUL = false; break; } } if (allNUL) { return 0L; } // Skip leading spaces while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } // Must have trailing NUL or space byte trailer; trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } else { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, end-1, trailer)); } // May have additional NUL or space trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; } public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } // Skip leading spaces while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } // Must have trailing NUL or space byte trailer; trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } else { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, end-1, trailer)); } // May have additional NUL or space trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; }
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
Compress-15
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ZipArchiveEntry other = (ZipArchiveEntry) obj; String myName = getName(); String otherName = other.getName(); if (myName == null) { if (otherName != null) { return false; } } else if (!myName.equals(otherName)) { return false; } String myComment = getComment(); String otherComment = other.getComment(); if (myComment == null) { if (otherComment != null) { return false; } } else if (!myComment.equals(otherComment)) { return false; } return getTime() == other.getTime() && getInternalAttributes() == other.getInternalAttributes() && getPlatform() == other.getPlatform() && getExternalAttributes() == other.getExternalAttributes() && getMethod() == other.getMethod() && getSize() == other.getSize() && getCrc() == other.getCrc() && getCompressedSize() == other.getCompressedSize() && Arrays.equals(getCentralDirectoryExtra(), other.getCentralDirectoryExtra()) && Arrays.equals(getLocalFileDataExtra(), other.getLocalFileDataExtra()) && gpb.equals(other.gpb); } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ZipArchiveEntry other = (ZipArchiveEntry) obj; String myName = getName(); String otherName = other.getName(); if (myName == null) { if (otherName != null) { return false; } } else if (!myName.equals(otherName)) { return false; } String myComment = getComment(); String otherComment = other.getComment(); if (myComment == null) { myComment = ""; } if (otherComment == null) { otherComment = ""; } return getTime() == other.getTime() && myComment.equals(otherComment) && getInternalAttributes() == other.getInternalAttributes() && getPlatform() == other.getPlatform() && getExternalAttributes() == other.getExternalAttributes() && getMethod() == other.getMethod() && getSize() == other.getSize() && getCrc() == other.getCrc() && getCompressedSize() == other.getCompressedSize() && Arrays.equals(getCentralDirectoryExtra(), other.getCentralDirectoryExtra()) && Arrays.equals(getLocalFileDataExtra(), other.getLocalFileDataExtra()) && gpb.equals(other.gpb); }
src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java
Compress-16
public ArchiveInputStream createArchiveInputStream(final InputStream in) throws ArchiveException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } final byte[] signature = new byte[12]; in.mark(signature.length); try { int signatureLength = in.read(signature); in.reset(); if (ZipArchiveInputStream.matches(signature, signatureLength)) { return new ZipArchiveInputStream(in); } else if (JarArchiveInputStream.matches(signature, signatureLength)) { return new JarArchiveInputStream(in); } else if (ArArchiveInputStream.matches(signature, signatureLength)) { return new ArArchiveInputStream(in); } else if (CpioArchiveInputStream.matches(signature, signatureLength)) { return new CpioArchiveInputStream(in); } // Dump needs a bigger buffer to check the signature; final byte[] dumpsig = new byte[32]; in.mark(dumpsig.length); signatureLength = in.read(dumpsig); in.reset(); if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) { return new DumpArchiveInputStream(in); } // Tar needs an even bigger buffer to check the signature; read the first block final byte[] tarheader = new byte[512]; in.mark(tarheader.length); signatureLength = in.read(tarheader); in.reset(); if (TarArchiveInputStream.matches(tarheader, signatureLength)) { return new TarArchiveInputStream(in); } // COMPRESS-117 - improve auto-recognition if (signatureLength >= 512) { try { TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader)); // COMPRESS-191 - verify the header checksum tais.getNextEntry(); return new TarArchiveInputStream(in); } catch (Exception e) { // NOPMD // can generate IllegalArgumentException as well // as IOException // autodetection, simply not a TAR // ignored } } } catch (IOException e) { throw new ArchiveException("Could not use reset and mark operations.", e); } throw new ArchiveException("No Archiver found for the stream signature"); } public ArchiveInputStream createArchiveInputStream(final InputStream in) throws ArchiveException { if (in == null) { throw new IllegalArgumentException("Stream must not be null."); } if (!in.markSupported()) { throw new IllegalArgumentException("Mark is not supported."); } final byte[] signature = new byte[12]; in.mark(signature.length); try { int signatureLength = in.read(signature); in.reset(); if (ZipArchiveInputStream.matches(signature, signatureLength)) { return new ZipArchiveInputStream(in); } else if (JarArchiveInputStream.matches(signature, signatureLength)) { return new JarArchiveInputStream(in); } else if (ArArchiveInputStream.matches(signature, signatureLength)) { return new ArArchiveInputStream(in); } else if (CpioArchiveInputStream.matches(signature, signatureLength)) { return new CpioArchiveInputStream(in); } // Dump needs a bigger buffer to check the signature; final byte[] dumpsig = new byte[32]; in.mark(dumpsig.length); signatureLength = in.read(dumpsig); in.reset(); if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) { return new DumpArchiveInputStream(in); } // Tar needs an even bigger buffer to check the signature; read the first block final byte[] tarheader = new byte[512]; in.mark(tarheader.length); signatureLength = in.read(tarheader); in.reset(); if (TarArchiveInputStream.matches(tarheader, signatureLength)) { return new TarArchiveInputStream(in); } // COMPRESS-117 - improve auto-recognition if (signatureLength >= 512) { try { TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader)); // COMPRESS-191 - verify the header checksum if (tais.getNextTarEntry().isCheckSumOK()) { return new TarArchiveInputStream(in); } } catch (Exception e) { // NOPMD // can generate IllegalArgumentException as well // as IOException // autodetection, simply not a TAR // ignored } } } catch (IOException e) { throw new ArchiveException("Could not use reset and mark operations.", e); } throw new ArchiveException("No Archiver found for the stream signature"); }
src/main/java/org/apache/commons/compress/archivers/ArchiveStreamFactory.java
Compress-17
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } // Skip leading spaces while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } // Must have trailing NUL or space byte trailer; trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } else { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, end-1, trailer)); } // May have additional NULs or spaces trailer = buffer[end - 1]; if (trailer == 0 || trailer == ' '){ end--; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; } public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } // Skip leading spaces while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } // Must have trailing NUL or space byte trailer; trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } else { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, end-1, trailer)); } // May have additional NULs or spaces trailer = buffer[end - 1]; while (start < end - 1 && (trailer == 0 || trailer == ' ')) { end--; trailer = buffer[end - 1]; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; }
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
Compress-18
void writePaxHeaders(String entryName, Map<String, String> headers) throws IOException { String name = "./PaxHeaders.X/" + stripTo7Bits(entryName); // TarEntry's constructor would think this is a directory // and not allow any data to be written if (name.length() >= TarConstants.NAMELEN) { name = name.substring(0, TarConstants.NAMELEN - 1); } TarArchiveEntry pex = new TarArchiveEntry(name, TarConstants.LF_PAX_EXTENDED_HEADER_LC); StringWriter w = new StringWriter(); for (Map.Entry<String, String> h : headers.entrySet()) { String key = h.getKey(); String value = h.getValue(); int len = key.length() + value.length() + 3 /* blank, equals and newline */ + 2 /* guess 9 < actual length < 100 */; String line = len + " " + key + "=" + value + "\n"; int actualLength = line.getBytes(CharsetNames.UTF_8).length; while (len != actualLength) { // Adjust for cases where length < 10 or > 100 // or where UTF-8 encoding isn't a single octet // per character. // Must be in loop as size may go from 99 to 100 in // first pass so we'd need a second. len = actualLength; line = len + " " + key + "=" + value + "\n"; actualLength = line.getBytes(CharsetNames.UTF_8).length; } w.write(line); } byte[] data = w.toString().getBytes(CharsetNames.UTF_8); pex.setSize(data.length); putArchiveEntry(pex); write(data); closeArchiveEntry(); } void writePaxHeaders(String entryName, Map<String, String> headers) throws IOException { String name = "./PaxHeaders.X/" + stripTo7Bits(entryName); while (name.endsWith("/")) { // TarEntry's constructor would think this is a directory // and not allow any data to be written name = name.substring(0, name.length() - 1); } if (name.length() >= TarConstants.NAMELEN) { name = name.substring(0, TarConstants.NAMELEN - 1); } TarArchiveEntry pex = new TarArchiveEntry(name, TarConstants.LF_PAX_EXTENDED_HEADER_LC); StringWriter w = new StringWriter(); for (Map.Entry<String, String> h : headers.entrySet()) { String key = h.getKey(); String value = h.getValue(); int len = key.length() + value.length() + 3 /* blank, equals and newline */ + 2 /* guess 9 < actual length < 100 */; String line = len + " " + key + "=" + value + "\n"; int actualLength = line.getBytes(CharsetNames.UTF_8).length; while (len != actualLength) { // Adjust for cases where length < 10 or > 100 // or where UTF-8 encoding isn't a single octet // per character. // Must be in loop as size may go from 99 to 100 in // first pass so we'd need a second. len = actualLength; line = len + " " + key + "=" + value + "\n"; actualLength = line.getBytes(CharsetNames.UTF_8).length; } w.write(line); } byte[] data = w.toString().getBytes(CharsetNames.UTF_8); pex.setSize(data.length); putArchiveEntry(pex); write(data); closeArchiveEntry(); }
src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveOutputStream.java
Compress-19
public void reparseCentralDirectoryData(boolean hasUncompressedSize, boolean hasCompressedSize, boolean hasRelativeHeaderOffset, boolean hasDiskStart) throws ZipException { if (rawCentralDirectoryData != null) { int expectedLength = (hasUncompressedSize ? DWORD : 0) + (hasCompressedSize ? DWORD : 0) + (hasRelativeHeaderOffset ? DWORD : 0) + (hasDiskStart ? WORD : 0); if (rawCentralDirectoryData.length != expectedLength) { throw new ZipException("central directory zip64 extended" + " information extra field's length" + " doesn't match central directory" + " data. Expected length " + expectedLength + " but is " + rawCentralDirectoryData.length); } int offset = 0; if (hasUncompressedSize) { size = new ZipEightByteInteger(rawCentralDirectoryData, offset); offset += DWORD; } if (hasCompressedSize) { compressedSize = new ZipEightByteInteger(rawCentralDirectoryData, offset); offset += DWORD; } if (hasRelativeHeaderOffset) { relativeHeaderOffset = new ZipEightByteInteger(rawCentralDirectoryData, offset); offset += DWORD; } if (hasDiskStart) { diskStart = new ZipLong(rawCentralDirectoryData, offset); offset += WORD; } } } public void reparseCentralDirectoryData(boolean hasUncompressedSize, boolean hasCompressedSize, boolean hasRelativeHeaderOffset, boolean hasDiskStart) throws ZipException { if (rawCentralDirectoryData != null) { int expectedLength = (hasUncompressedSize ? DWORD : 0) + (hasCompressedSize ? DWORD : 0) + (hasRelativeHeaderOffset ? DWORD : 0) + (hasDiskStart ? WORD : 0); if (rawCentralDirectoryData.length < expectedLength) { throw new ZipException("central directory zip64 extended" + " information extra field's length" + " doesn't match central directory" + " data. Expected length " + expectedLength + " but is " + rawCentralDirectoryData.length); } int offset = 0; if (hasUncompressedSize) { size = new ZipEightByteInteger(rawCentralDirectoryData, offset); offset += DWORD; } if (hasCompressedSize) { compressedSize = new ZipEightByteInteger(rawCentralDirectoryData, offset); offset += DWORD; } if (hasRelativeHeaderOffset) { relativeHeaderOffset = new ZipEightByteInteger(rawCentralDirectoryData, offset); offset += DWORD; } if (hasDiskStart) { diskStart = new ZipLong(rawCentralDirectoryData, offset); offset += WORD; } } }
src/main/java/org/apache/commons/compress/archivers/zip/Zip64ExtendedInformationExtraField.java
Compress-21
private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException { int cache = 0; int shift = 7; for (int i = 0; i < length; i++) { cache |= ((bits.get(i) ? 1 : 0) << shift); --shift; if (shift == 0) { header.write(cache); shift = 7; cache = 0; } } if (length > 0 && shift > 0) { header.write(cache); } } private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException { int cache = 0; int shift = 7; for (int i = 0; i < length; i++) { cache |= ((bits.get(i) ? 1 : 0) << shift); if (--shift < 0) { header.write(cache); shift = 7; cache = 0; } } if (shift != 7) { header.write(cache); } }
src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFile.java
Compress-23
InputStream decode(final InputStream in, final Coder coder, byte[] password) throws IOException { byte propsByte = coder.properties[0]; long dictSize = coder.properties[1]; for (int i = 1; i < 4; i++) { dictSize |= (coder.properties[i + 1] << (8 * i)); } if (dictSize > LZMAInputStream.DICT_SIZE_MAX) { throw new IOException("Dictionary larger than 4GiB maximum size"); } return new LZMAInputStream(in, -1, propsByte, (int) dictSize); } InputStream decode(final InputStream in, final Coder coder, byte[] password) throws IOException { byte propsByte = coder.properties[0]; long dictSize = coder.properties[1]; for (int i = 1; i < 4; i++) { dictSize |= (coder.properties[i + 1] & 0xffl) << (8 * i); } if (dictSize > LZMAInputStream.DICT_SIZE_MAX) { throw new IOException("Dictionary larger than 4GiB maximum size"); } return new LZMAInputStream(in, -1, propsByte, (int) dictSize); }
src/main/java/org/apache/commons/compress/archivers/sevenz/Coders.java
Compress-24
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } // Skip leading spaces while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } // Trim all trailing NULs and spaces. // The ustar and POSIX tar specs require a trailing NUL or // space but some implementations use the extra digit for big // sizes/uids/gids ... byte trailer = buffer[end - 1]; if (trailer == 0 || trailer == ' '){ end--; } else { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, end-1, trailer)); } trailer = buffer[end - 1]; while (start < end - 1 && (trailer == 0 || trailer == ' ')) { end--; trailer = buffer[end - 1]; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; } public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } // Skip leading spaces while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } // Trim all trailing NULs and spaces. // The ustar and POSIX tar specs require a trailing NUL or // space but some implementations use the extra digit for big // sizes/uids/gids ... byte trailer = buffer[end - 1]; while (start < end && (trailer == 0 || trailer == ' ')) { end--; trailer = buffer[end - 1]; } if (start == end) { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, trailer)); } for ( ;start < end; start++) { final byte currentByte = buffer[start]; // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; }
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
Compress-25
public ZipArchiveInputStream(InputStream inputStream, String encoding, boolean useUnicodeExtraFields, boolean allowStoredEntriesWithDataDescriptor) { zipEncoding = ZipEncodingHelper.getZipEncoding(encoding); this.useUnicodeExtraFields = useUnicodeExtraFields; in = new PushbackInputStream(inputStream, buf.capacity()); this.allowStoredEntriesWithDataDescriptor = allowStoredEntriesWithDataDescriptor; // haven't read anything so far } public ZipArchiveInputStream(InputStream inputStream, String encoding, boolean useUnicodeExtraFields, boolean allowStoredEntriesWithDataDescriptor) { zipEncoding = ZipEncodingHelper.getZipEncoding(encoding); this.useUnicodeExtraFields = useUnicodeExtraFields; in = new PushbackInputStream(inputStream, buf.capacity()); this.allowStoredEntriesWithDataDescriptor = allowStoredEntriesWithDataDescriptor; // haven't read anything so far buf.limit(0); }
src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java
Compress-26
public static long skip(InputStream input, long numToSkip) throws IOException { long available = numToSkip; while (numToSkip > 0) { long skipped = input.skip(numToSkip); if (skipped == 0) { break; } numToSkip -= skipped; } return available - numToSkip; } public static long skip(InputStream input, long numToSkip) throws IOException { long available = numToSkip; while (numToSkip > 0) { long skipped = input.skip(numToSkip); if (skipped == 0) { break; } numToSkip -= skipped; } if (numToSkip > 0) { byte[] skipBuf = new byte[SKIP_BUF_SIZE]; while (numToSkip > 0) { int read = readFully(input, skipBuf, 0, (int) Math.min(numToSkip, SKIP_BUF_SIZE)); if (read < 1) { break; } numToSkip -= read; } } return available - numToSkip; }
src/main/java/org/apache/commons/compress/utils/IOUtils.java
Compress-27
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } // Skip leading spaces while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } // Trim all trailing NULs and spaces. // The ustar and POSIX tar specs require a trailing NUL or // space but some implementations use the extra digit for big // sizes/uids/gids ... byte trailer = buffer[end - 1]; while (start < end && (trailer == 0 || trailer == ' ')) { end--; trailer = buffer[end - 1]; } if (start == end) { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, trailer)); } for ( ;start < end; start++) { final byte currentByte = buffer[start]; // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; } public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } // Skip leading spaces while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } // Trim all trailing NULs and spaces. // The ustar and POSIX tar specs require a trailing NUL or // space but some implementations use the extra digit for big // sizes/uids/gids ... byte trailer = buffer[end - 1]; while (start < end && (trailer == 0 || trailer == ' ')) { end--; trailer = buffer[end - 1]; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; }
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
Compress-28
public int read(byte[] buf, int offset, int numToRead) throws IOException { int totalRead = 0; if (hasHitEOF || entryOffset >= entrySize) { return -1; } if (currEntry == null) { throw new IllegalStateException("No current tar entry"); } numToRead = Math.min(numToRead, available()); totalRead = is.read(buf, offset, numToRead); count(totalRead); if (totalRead == -1) { hasHitEOF = true; } else { entryOffset += totalRead; } return totalRead; } public int read(byte[] buf, int offset, int numToRead) throws IOException { int totalRead = 0; if (hasHitEOF || entryOffset >= entrySize) { return -1; } if (currEntry == null) { throw new IllegalStateException("No current tar entry"); } numToRead = Math.min(numToRead, available()); totalRead = is.read(buf, offset, numToRead); if (totalRead == -1) { if (numToRead > 0) { throw new IOException("Truncated TAR archive"); } hasHitEOF = true; } else { count(totalRead); entryOffset += totalRead; } return totalRead; }
src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
Compress-30
public int read(final byte[] dest, final int offs, final int len) throws IOException { if (offs < 0) { throw new IndexOutOfBoundsException("offs(" + offs + ") < 0."); } if (len < 0) { throw new IndexOutOfBoundsException("len(" + len + ") < 0."); } if (offs + len > dest.length) { throw new IndexOutOfBoundsException("offs(" + offs + ") + len(" + len + ") > dest.length(" + dest.length + ")."); } if (this.in == null) { throw new IOException("stream closed"); } final int hi = offs + len; int destOffs = offs; int b; while (destOffs < hi && ((b = read0()) >= 0)) { dest[destOffs++] = (byte) b; count(1); } int c = (destOffs == offs) ? -1 : (destOffs - offs); return c; } public int read(final byte[] dest, final int offs, final int len) throws IOException { if (offs < 0) { throw new IndexOutOfBoundsException("offs(" + offs + ") < 0."); } if (len < 0) { throw new IndexOutOfBoundsException("len(" + len + ") < 0."); } if (offs + len > dest.length) { throw new IndexOutOfBoundsException("offs(" + offs + ") + len(" + len + ") > dest.length(" + dest.length + ")."); } if (this.in == null) { throw new IOException("stream closed"); } if (len == 0) { return 0; } final int hi = offs + len; int destOffs = offs; int b; while (destOffs < hi && ((b = read0()) >= 0)) { dest[destOffs++] = (byte) b; count(1); } int c = (destOffs == offs) ? -1 : (destOffs - offs); return c; }
src/main/java/org/apache/commons/compress/compressors/bzip2/BZip2CompressorInputStream.java
Compress-31
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } // Skip leading spaces while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } // Trim all trailing NULs and spaces. // The ustar and POSIX tar specs require a trailing NUL or // space but some implementations use the extra digit for big // sizes/uids/gids ... byte trailer = buffer[end - 1]; while (start < end && (trailer == 0 || trailer == ' ')) { end--; trailer = buffer[end - 1]; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; if (currentByte == 0) { break; } // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; } public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } if (buffer[start] == 0) { return 0L; } // Skip leading spaces while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } // Trim all trailing NULs and spaces. // The ustar and POSIX tar specs require a trailing NUL or // space but some implementations use the extra digit for big // sizes/uids/gids ... byte trailer = buffer[end - 1]; while (start < end && (trailer == 0 || trailer == ' ')) { end--; trailer = buffer[end - 1]; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; }
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
Compress-32
private void applyPaxHeadersToCurrentEntry(Map<String, String> headers) { /* * The following headers are defined for Pax. * atime, ctime, charset: cannot use these without changing TarArchiveEntry fields * mtime * comment * gid, gname * linkpath * size * uid,uname * SCHILY.devminor, SCHILY.devmajor: don't have setters/getters for those */ for (Entry<String, String> ent : headers.entrySet()){ String key = ent.getKey(); String val = ent.getValue(); if ("path".equals(key)){ currEntry.setName(val); } else if ("linkpath".equals(key)){ currEntry.setLinkName(val); } else if ("gid".equals(key)){ currEntry.setGroupId(Integer.parseInt(val)); } else if ("gname".equals(key)){ currEntry.setGroupName(val); } else if ("uid".equals(key)){ currEntry.setUserId(Integer.parseInt(val)); } else if ("uname".equals(key)){ currEntry.setUserName(val); } else if ("size".equals(key)){ currEntry.setSize(Long.parseLong(val)); } else if ("mtime".equals(key)){ currEntry.setModTime((long) (Double.parseDouble(val) * 1000)); } else if ("SCHILY.devminor".equals(key)){ currEntry.setDevMinor(Integer.parseInt(val)); } else if ("SCHILY.devmajor".equals(key)){ currEntry.setDevMajor(Integer.parseInt(val)); } } } private void applyPaxHeadersToCurrentEntry(Map<String, String> headers) { /* * The following headers are defined for Pax. * atime, ctime, charset: cannot use these without changing TarArchiveEntry fields * mtime * comment * gid, gname * linkpath * size * uid,uname * SCHILY.devminor, SCHILY.devmajor: don't have setters/getters for those */ for (Entry<String, String> ent : headers.entrySet()){ String key = ent.getKey(); String val = ent.getValue(); if ("path".equals(key)){ currEntry.setName(val); } else if ("linkpath".equals(key)){ currEntry.setLinkName(val); } else if ("gid".equals(key)){ currEntry.setGroupId(Long.parseLong(val)); } else if ("gname".equals(key)){ currEntry.setGroupName(val); } else if ("uid".equals(key)){ currEntry.setUserId(Long.parseLong(val)); } else if ("uname".equals(key)){ currEntry.setUserName(val); } else if ("size".equals(key)){ currEntry.setSize(Long.parseLong(val)); } else if ("mtime".equals(key)){ currEntry.setModTime((long) (Double.parseDouble(val) * 1000)); } else if ("SCHILY.devminor".equals(key)){ currEntry.setDevMinor(Integer.parseInt(val)); } else if ("SCHILY.devmajor".equals(key)){ currEntry.setDevMajor(Integer.parseInt(val)); } } }
src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
Compress-35
public static boolean verifyCheckSum(byte[] header) { long storedSum = 0; long unsignedSum = 0; long signedSum = 0; int digits = 0; for (int i = 0; i < header.length; i++) { byte b = header[i]; if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET + CHKSUMLEN) { if ('0' <= b && b <= '7' && digits++ < 6) { storedSum = storedSum * 8 + b - '0'; } else if (digits > 0) { digits = 6; } b = ' '; } unsignedSum += 0xff & b; signedSum += b; } return storedSum == unsignedSum || storedSum == signedSum; } public static boolean verifyCheckSum(byte[] header) { long storedSum = parseOctal(header, CHKSUM_OFFSET, CHKSUMLEN); long unsignedSum = 0; long signedSum = 0; int digits = 0; for (int i = 0; i < header.length; i++) { byte b = header[i]; if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET + CHKSUMLEN) { b = ' '; } unsignedSum += 0xff & b; signedSum += b; } return storedSum == unsignedSum || storedSum == signedSum; }
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
Compress-36
private InputStream getCurrentStream() throws IOException { if (deferredBlockStreams.isEmpty()) { throw new IllegalStateException("No current 7z entry (call getNextEntry() first)."); } while (deferredBlockStreams.size() > 1) { // In solid compression mode we need to decompress all leading folder' // streams to get access to an entry. We defer this until really needed // so that entire blocks can be skipped without wasting time for decompression. final InputStream stream = deferredBlockStreams.remove(0); IOUtils.skip(stream, Long.MAX_VALUE); stream.close(); } return deferredBlockStreams.get(0); } private InputStream getCurrentStream() throws IOException { if (archive.files[currentEntryIndex].getSize() == 0) { return new ByteArrayInputStream(new byte[0]); } if (deferredBlockStreams.isEmpty()) { throw new IllegalStateException("No current 7z entry (call getNextEntry() first)."); } while (deferredBlockStreams.size() > 1) { // In solid compression mode we need to decompress all leading folder' // streams to get access to an entry. We defer this until really needed // so that entire blocks can be skipped without wasting time for decompression. final InputStream stream = deferredBlockStreams.remove(0); IOUtils.skip(stream, Long.MAX_VALUE); stream.close(); } return deferredBlockStreams.get(0); }
src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java
Compress-37
Map<String, String> parsePaxHeaders(final InputStream i) throws IOException { final Map<String, String> headers = new HashMap<String, String>(globalPaxHeaders); // Format is "length keyword=value\n"; while(true){ // get length int ch; int len = 0; int read = 0; while((ch = i.read()) != -1) { read++; if (ch == ' '){ // Get keyword final ByteArrayOutputStream coll = new ByteArrayOutputStream(); while((ch = i.read()) != -1) { read++; if (ch == '='){ // end of keyword final String keyword = coll.toString(CharsetNames.UTF_8); // Get rest of entry final int restLen = len - read; if (restLen == 1) { // only NL headers.remove(keyword); } else { final byte[] rest = new byte[restLen]; final int got = IOUtils.readFully(i, rest); if (got != restLen) { throw new IOException("Failed to read " + "Paxheader. Expected " + restLen + " bytes, read " + got); } // Drop trailing NL final String value = new String(rest, 0, restLen - 1, CharsetNames.UTF_8); headers.put(keyword, value); } break; } coll.write((byte) ch); } break; // Processed single header } len *= 10; len += ch - '0'; } if (ch == -1){ // EOF break; } } return headers; } Map<String, String> parsePaxHeaders(final InputStream i) throws IOException { final Map<String, String> headers = new HashMap<String, String>(globalPaxHeaders); // Format is "length keyword=value\n"; while(true){ // get length int ch; int len = 0; int read = 0; while((ch = i.read()) != -1) { read++; if (ch == '\n') { // blank line in header break; } else if (ch == ' '){ // End of length string // Get keyword final ByteArrayOutputStream coll = new ByteArrayOutputStream(); while((ch = i.read()) != -1) { read++; if (ch == '='){ // end of keyword final String keyword = coll.toString(CharsetNames.UTF_8); // Get rest of entry final int restLen = len - read; if (restLen == 1) { // only NL headers.remove(keyword); } else { final byte[] rest = new byte[restLen]; final int got = IOUtils.readFully(i, rest); if (got != restLen) { throw new IOException("Failed to read " + "Paxheader. Expected " + restLen + " bytes, read " + got); } // Drop trailing NL final String value = new String(rest, 0, restLen - 1, CharsetNames.UTF_8); headers.put(keyword, value); } break; } coll.write((byte) ch); } break; // Processed single header } len *= 10; len += ch - '0'; } if (ch == -1){ // EOF break; } } return headers; }
src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
Compress-38
public boolean isDirectory() { if (file != null) { return file.isDirectory(); } if (linkFlag == LF_DIR) { return true; } if (getName().endsWith("/")) { return true; } return false; } public boolean isDirectory() { if (file != null) { return file.isDirectory(); } if (linkFlag == LF_DIR) { return true; } if (!isPaxHeader() && !isGlobalPaxHeader() && getName().endsWith("/")) { return true; } return false; }
src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveEntry.java
Compress-40
public long readBits(final int count) throws IOException { if (count < 0 || count > MAXIMUM_CACHE_SIZE) { throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE); } while (bitsCachedSize < count) { final long nextByte = in.read(); if (nextByte < 0) { return nextByte; } if (byteOrder == ByteOrder.LITTLE_ENDIAN) { bitsCached |= (nextByte << bitsCachedSize); } else { bitsCached <<= 8; bitsCached |= nextByte; } bitsCachedSize += 8; } // bitsCachedSize >= 57 and left-shifting it 8 bits would cause an overflow final long bitsOut; if (byteOrder == ByteOrder.LITTLE_ENDIAN) { bitsOut = (bitsCached & MASKS[count]); bitsCached >>>= count; } else { bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count]; } bitsCachedSize -= count; return bitsOut; } public long readBits(final int count) throws IOException { if (count < 0 || count > MAXIMUM_CACHE_SIZE) { throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE); } while (bitsCachedSize < count && bitsCachedSize < 57) { final long nextByte = in.read(); if (nextByte < 0) { return nextByte; } if (byteOrder == ByteOrder.LITTLE_ENDIAN) { bitsCached |= (nextByte << bitsCachedSize); } else { bitsCached <<= 8; bitsCached |= nextByte; } bitsCachedSize += 8; } int overflowBits = 0; long overflow = 0l; if (bitsCachedSize < count) { // bitsCachedSize >= 57 and left-shifting it 8 bits would cause an overflow int bitsToAddCount = count - bitsCachedSize; overflowBits = 8 - bitsToAddCount; final long nextByte = in.read(); if (nextByte < 0) { return nextByte; } if (byteOrder == ByteOrder.LITTLE_ENDIAN) { long bitsToAdd = nextByte & MASKS[bitsToAddCount]; bitsCached |= (bitsToAdd << bitsCachedSize); overflow = (nextByte >>> bitsToAddCount) & MASKS[overflowBits]; } else { bitsCached <<= bitsToAddCount; long bitsToAdd = (nextByte >>> (overflowBits)) & MASKS[bitsToAddCount]; bitsCached |= bitsToAdd; overflow = nextByte & MASKS[overflowBits]; } bitsCachedSize = count; } final long bitsOut; if (overflowBits == 0) { if (byteOrder == ByteOrder.LITTLE_ENDIAN) { bitsOut = (bitsCached & MASKS[count]); bitsCached >>>= count; } else { bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count]; } bitsCachedSize -= count; } else { bitsOut = bitsCached & MASKS[count]; bitsCached = overflow; bitsCachedSize = overflowBits; } return bitsOut; }
src/main/java/org/apache/commons/compress/utils/BitInputStream.java
Compress-41
public ZipArchiveEntry getNextZipEntry() throws IOException { boolean firstEntry = true; if (closed || hitCentralDirectory) { return null; } if (current != null) { closeEntry(); firstEntry = false; } try { if (firstEntry) { // split archives have a special signature before the // first local file header - look for it and fail with // the appropriate error message if this is a split // archive. readFirstLocalFileHeader(LFH_BUF); } else { readFully(LFH_BUF); } } catch (final EOFException e) { return null; } final ZipLong sig = new ZipLong(LFH_BUF); if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG)) { hitCentralDirectory = true; skipRemainderOfArchive(); } if (!sig.equals(ZipLong.LFH_SIG)) { return null; } int off = WORD; current = new CurrentEntry(); final int versionMadeBy = ZipShort.getValue(LFH_BUF, off); off += SHORT; current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK); final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(LFH_BUF, off); final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames(); final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding; current.hasDataDescriptor = gpFlag.usesDataDescriptor(); current.entry.setGeneralPurposeBit(gpFlag); off += SHORT; current.entry.setMethod(ZipShort.getValue(LFH_BUF, off)); off += SHORT; final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(LFH_BUF, off)); current.entry.setTime(time); off += WORD; ZipLong size = null, cSize = null; if (!current.hasDataDescriptor) { current.entry.setCrc(ZipLong.getValue(LFH_BUF, off)); off += WORD; cSize = new ZipLong(LFH_BUF, off); off += WORD; size = new ZipLong(LFH_BUF, off); off += WORD; } else { off += 3 * WORD; } final int fileNameLen = ZipShort.getValue(LFH_BUF, off); off += SHORT; final int extraLen = ZipShort.getValue(LFH_BUF, off); off += SHORT; final byte[] fileName = new byte[fileNameLen]; readFully(fileName); current.entry.setName(entryEncoding.decode(fileName), fileName); final byte[] extraData = new byte[extraLen]; readFully(extraData); current.entry.setExtra(extraData); if (!hasUTF8Flag && useUnicodeExtraFields) { ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null); } processZip64Extra(size, cSize); if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) { if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()) { current.in = new UnshrinkingInputStream(new BoundedInputStream(in, current.entry.getCompressedSize())); } else if (current.entry.getMethod() == ZipMethod.IMPLODING.getCode()) { current.in = new ExplodingInputStream( current.entry.getGeneralPurposeBit().getSlidingDictionarySize(), current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(), new BoundedInputStream(in, current.entry.getCompressedSize())); } else if (current.entry.getMethod() == ZipMethod.BZIP2.getCode()) { current.in = new BZip2CompressorInputStream(new BoundedInputStream(in, current.entry.getCompressedSize())); } } entriesRead++; return current.entry; } public ZipArchiveEntry getNextZipEntry() throws IOException { boolean firstEntry = true; if (closed || hitCentralDirectory) { return null; } if (current != null) { closeEntry(); firstEntry = false; } try { if (firstEntry) { // split archives have a special signature before the // first local file header - look for it and fail with // the appropriate error message if this is a split // archive. readFirstLocalFileHeader(LFH_BUF); } else { readFully(LFH_BUF); } } catch (final EOFException e) { return null; } final ZipLong sig = new ZipLong(LFH_BUF); if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG)) { hitCentralDirectory = true; skipRemainderOfArchive(); return null; } if (!sig.equals(ZipLong.LFH_SIG)) { throw new ZipException(String.format("Unexpected record signature: 0X%X", sig.getValue())); } int off = WORD; current = new CurrentEntry(); final int versionMadeBy = ZipShort.getValue(LFH_BUF, off); off += SHORT; current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK); final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(LFH_BUF, off); final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames(); final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding; current.hasDataDescriptor = gpFlag.usesDataDescriptor(); current.entry.setGeneralPurposeBit(gpFlag); off += SHORT; current.entry.setMethod(ZipShort.getValue(LFH_BUF, off)); off += SHORT; final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(LFH_BUF, off)); current.entry.setTime(time); off += WORD; ZipLong size = null, cSize = null; if (!current.hasDataDescriptor) { current.entry.setCrc(ZipLong.getValue(LFH_BUF, off)); off += WORD; cSize = new ZipLong(LFH_BUF, off); off += WORD; size = new ZipLong(LFH_BUF, off); off += WORD; } else { off += 3 * WORD; } final int fileNameLen = ZipShort.getValue(LFH_BUF, off); off += SHORT; final int extraLen = ZipShort.getValue(LFH_BUF, off); off += SHORT; final byte[] fileName = new byte[fileNameLen]; readFully(fileName); current.entry.setName(entryEncoding.decode(fileName), fileName); final byte[] extraData = new byte[extraLen]; readFully(extraData); current.entry.setExtra(extraData); if (!hasUTF8Flag && useUnicodeExtraFields) { ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null); } processZip64Extra(size, cSize); if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) { if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()) { current.in = new UnshrinkingInputStream(new BoundedInputStream(in, current.entry.getCompressedSize())); } else if (current.entry.getMethod() == ZipMethod.IMPLODING.getCode()) { current.in = new ExplodingInputStream( current.entry.getGeneralPurposeBit().getSlidingDictionarySize(), current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(), new BoundedInputStream(in, current.entry.getCompressedSize())); } else if (current.entry.getMethod() == ZipMethod.BZIP2.getCode()) { current.in = new BZip2CompressorInputStream(new BoundedInputStream(in, current.entry.getCompressedSize())); } } entriesRead++; return current.entry; }
src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java
Compress-44
public ChecksumCalculatingInputStream(final Checksum checksum, final InputStream in) { this.checksum = checksum; this.in = in; } public ChecksumCalculatingInputStream(final Checksum checksum, final InputStream in) { if ( checksum == null ){ throw new NullPointerException("Parameter checksum must not be null"); } if ( in == null ){ throw new NullPointerException("Parameter in must not be null"); } this.checksum = checksum; this.in = in; }
src/main/java/org/apache/commons/compress/utils/ChecksumCalculatingInputStream.java
Compress-45
public static int formatLongOctalOrBinaryBytes( final long value, final byte[] buf, final int offset, final int length) { // Check whether we are dealing with UID/GID or SIZE field final long maxAsOctalChar = length == TarConstants.UIDLEN ? TarConstants.MAXID : TarConstants.MAXSIZE; final boolean negative = value < 0; if (!negative && value <= maxAsOctalChar) { // OK to store as octal chars return formatLongOctalBytes(value, buf, offset, length); } if (length < 9) { formatLongBinary(value, buf, offset, length, negative); } formatBigIntegerBinary(value, buf, offset, length, negative); buf[offset] = (byte) (negative ? 0xff : 0x80); return offset + length; } public static int formatLongOctalOrBinaryBytes( final long value, final byte[] buf, final int offset, final int length) { // Check whether we are dealing with UID/GID or SIZE field final long maxAsOctalChar = length == TarConstants.UIDLEN ? TarConstants.MAXID : TarConstants.MAXSIZE; final boolean negative = value < 0; if (!negative && value <= maxAsOctalChar) { // OK to store as octal chars return formatLongOctalBytes(value, buf, offset, length); } if (length < 9) { formatLongBinary(value, buf, offset, length, negative); } else { formatBigIntegerBinary(value, buf, offset, length, negative); } buf[offset] = (byte) (negative ? 0xff : 0x80); return offset + length; }
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
Compress-46
private static ZipLong unixTimeToZipLong(long l) { final long TWO_TO_32 = 0x100000000L; if (l >= TWO_TO_32) { throw new IllegalArgumentException("X5455 timestamps must fit in a signed 32 bit integer: " + l); } return new ZipLong(l); } private static ZipLong unixTimeToZipLong(long l) { if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { throw new IllegalArgumentException("X5455 timestamps must fit in a signed 32 bit integer: " + l); } return new ZipLong(l); }
src/main/java/org/apache/commons/compress/archivers/zip/X5455_ExtendedTimestamp.java
Compress-5
public int read(byte[] buffer, int start, int length) throws IOException { if (closed) { throw new IOException("The stream is closed"); } if (inf.finished() || current == null) { return -1; } // avoid int overflow, check null buffer if (start <= buffer.length && length >= 0 && start >= 0 && buffer.length - start >= length) { if (current.getMethod() == ZipArchiveOutputStream.STORED) { int csize = (int) current.getSize(); if (readBytesOfEntry >= csize) { return -1; } if (offsetInBuffer >= lengthOfLastRead) { offsetInBuffer = 0; if ((lengthOfLastRead = in.read(buf)) == -1) { return -1; } count(lengthOfLastRead); bytesReadFromStream += lengthOfLastRead; } int toRead = length > lengthOfLastRead ? lengthOfLastRead - offsetInBuffer : length; if ((csize - readBytesOfEntry) < toRead) { toRead = csize - readBytesOfEntry; } System.arraycopy(buf, offsetInBuffer, buffer, start, toRead); offsetInBuffer += toRead; readBytesOfEntry += toRead; crc.update(buffer, start, toRead); return toRead; } if (inf.needsInput()) { fill(); if (lengthOfLastRead > 0) { bytesReadFromStream += lengthOfLastRead; } } int read = 0; try { read = inf.inflate(buffer, start, length); } catch (DataFormatException e) { throw new ZipException(e.getMessage()); } if (read == 0 && inf.finished()) { return -1; } crc.update(buffer, start, read); return read; } throw new ArrayIndexOutOfBoundsException(); } public int read(byte[] buffer, int start, int length) throws IOException { if (closed) { throw new IOException("The stream is closed"); } if (inf.finished() || current == null) { return -1; } // avoid int overflow, check null buffer if (start <= buffer.length && length >= 0 && start >= 0 && buffer.length - start >= length) { if (current.getMethod() == ZipArchiveOutputStream.STORED) { int csize = (int) current.getSize(); if (readBytesOfEntry >= csize) { return -1; } if (offsetInBuffer >= lengthOfLastRead) { offsetInBuffer = 0; if ((lengthOfLastRead = in.read(buf)) == -1) { return -1; } count(lengthOfLastRead); bytesReadFromStream += lengthOfLastRead; } int toRead = length > lengthOfLastRead ? lengthOfLastRead - offsetInBuffer : length; if ((csize - readBytesOfEntry) < toRead) { toRead = csize - readBytesOfEntry; } System.arraycopy(buf, offsetInBuffer, buffer, start, toRead); offsetInBuffer += toRead; readBytesOfEntry += toRead; crc.update(buffer, start, toRead); return toRead; } if (inf.needsInput()) { fill(); if (lengthOfLastRead > 0) { bytesReadFromStream += lengthOfLastRead; } } int read = 0; try { read = inf.inflate(buffer, start, length); } catch (DataFormatException e) { throw new ZipException(e.getMessage()); } if (read == 0) { if (inf.finished()) { return -1; } else if (lengthOfLastRead == -1) { throw new IOException("Truncated ZIP file"); } } crc.update(buffer, start, read); return read; } throw new ArrayIndexOutOfBoundsException(); }
src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveInputStream.java
Compress-7
public static String parseName(byte[] buffer, final int offset, final int length) { StringBuffer result = new StringBuffer(length); int end = offset + length; for (int i = offset; i < end; ++i) { if (buffer[i] == 0) { break; } result.append((char) buffer[i]); } return result.toString(); } public static String parseName(byte[] buffer, final int offset, final int length) { StringBuffer result = new StringBuffer(length); int end = offset + length; for (int i = offset; i < end; ++i) { byte b = buffer[i]; if (b == 0) { // Trailing null break; } result.append((char) (b & 0xFF)); // Allow for sign-extension } return result.toString(); }
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
Compress-8
public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; boolean stillPadding = true; int end = offset + length; int start = offset; for (int i = start; i < end; i++){ final byte currentByte = buffer[i]; if (currentByte == 0) { break; } // Skip leading spaces if (currentByte == (byte) ' ' || currentByte == '0') { if (stillPadding) { continue; } if (currentByte == (byte) ' ') { break; } } // Must have trailing NUL or space // May have additional NUL or space stillPadding = false; // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; } public static long parseOctal(final byte[] buffer, final int offset, final int length) { long result = 0; int end = offset + length; int start = offset; if (length < 2){ throw new IllegalArgumentException("Length "+length+" must be at least 2"); } boolean allNUL = true; for (int i = start; i < end; i++){ if (buffer[i] != 0){ allNUL = false; break; } } if (allNUL) { return 0L; } // Skip leading spaces while (start < end){ if (buffer[start] == ' '){ start++; } else { break; } } // Must have trailing NUL or space byte trailer; trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } else { throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, end-1, trailer)); } // May have additional NUL or space trailer = buffer[end-1]; if (trailer == 0 || trailer == ' '){ end--; } for ( ;start < end; start++) { final byte currentByte = buffer[start]; // CheckStyle:MagicNumber OFF if (currentByte < '0' || currentByte > '7'){ throw new IllegalArgumentException( exceptionMessage(buffer, offset, length, start, currentByte)); } result = (result << 3) + (currentByte - '0'); // convert from ASCII // CheckStyle:MagicNumber ON } return result; }
src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
Csv-1
public int read() throws IOException { int current = super.read(); if (current == '\n') { lineCounter++; } lastChar = current; return lastChar; } public int read() throws IOException { int current = super.read(); if (current == '\r' || (current == '\n' && lastChar != '\r')) { lineCounter++; } lastChar = current; return lastChar; }
src/main/java/org/apache/commons/csv/ExtendedBufferedReader.java
Csv-10
public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException { Assertions.notNull(out, "out"); Assertions.notNull(format, "format"); this.out = out; this.format = format; this.format.validate(); // TODO: Is it a good idea to do this here instead of on the first call to a print method? // It seems a pain to have to track whether the header has already been printed or not. } public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException { Assertions.notNull(out, "out"); Assertions.notNull(format, "format"); this.out = out; this.format = format; this.format.validate(); // TODO: Is it a good idea to do this here instead of on the first call to a print method? // It seems a pain to have to track whether the header has already been printed or not. if (format.getHeader() != null) { this.printRecord((Object[]) format.getHeader()); } }
src/main/java/org/apache/commons/csv/CSVPrinter.java
Csv-11
private Map<String, Integer> initializeHeader() throws IOException { Map<String, Integer> hdrMap = null; final String[] formatHeader = this.format.getHeader(); if (formatHeader != null) { hdrMap = new LinkedHashMap<String, Integer>(); String[] headerRecord = null; if (formatHeader.length == 0) { // read the header from the first line of the file final CSVRecord nextRecord = this.nextRecord(); if (nextRecord != null) { headerRecord = nextRecord.values(); } } else { if (this.format.getSkipHeaderRecord()) { this.nextRecord(); } headerRecord = formatHeader; } // build the name to index mappings if (headerRecord != null) { for (int i = 0; i < headerRecord.length; i++) { final String header = headerRecord[i]; final boolean containsHeader = hdrMap.containsKey(header); final boolean emptyHeader = header.trim().isEmpty(); if (containsHeader && (!emptyHeader || (emptyHeader && !this.format.getIgnoreEmptyHeaders()))) { throw new IllegalArgumentException("The header contains a duplicate name: \"" + header + "\" in " + Arrays.toString(headerRecord)); } hdrMap.put(header, Integer.valueOf(i)); } } } return hdrMap; } private Map<String, Integer> initializeHeader() throws IOException { Map<String, Integer> hdrMap = null; final String[] formatHeader = this.format.getHeader(); if (formatHeader != null) { hdrMap = new LinkedHashMap<String, Integer>(); String[] headerRecord = null; if (formatHeader.length == 0) { // read the header from the first line of the file final CSVRecord nextRecord = this.nextRecord(); if (nextRecord != null) { headerRecord = nextRecord.values(); } } else { if (this.format.getSkipHeaderRecord()) { this.nextRecord(); } headerRecord = formatHeader; } // build the name to index mappings if (headerRecord != null) { for (int i = 0; i < headerRecord.length; i++) { final String header = headerRecord[i]; final boolean containsHeader = hdrMap.containsKey(header); final boolean emptyHeader = header == null || header.trim().isEmpty(); if (containsHeader && (!emptyHeader || (emptyHeader && !this.format.getIgnoreEmptyHeaders()))) { throw new IllegalArgumentException("The header contains a duplicate name: \"" + header + "\" in " + Arrays.toString(headerRecord)); } hdrMap.put(header, Integer.valueOf(i)); } } } return hdrMap; }
src/main/java/org/apache/commons/csv/CSVParser.java
Csv-14
private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len, final Appendable out, final boolean newRecord) throws IOException { boolean quote = false; int start = offset; int pos = offset; final int end = offset + len; final char delimChar = getDelimiter(); final char quoteChar = getQuoteCharacter().charValue(); QuoteMode quoteModePolicy = getQuoteMode(); if (quoteModePolicy == null) { quoteModePolicy = QuoteMode.MINIMAL; } switch (quoteModePolicy) { case ALL: quote = true; break; case NON_NUMERIC: quote = !(object instanceof Number); break; case NONE: // Use the existing escaping code printAndEscape(value, offset, len, out); return; case MINIMAL: if (len <= 0) { // always quote an empty token that is the first // on the line, as it may be the only thing on the // line. If it were not quoted in that case, // an empty line has no tokens. if (newRecord) { quote = true; } } else { char c = value.charAt(pos); // RFC4180 (https://tools.ietf.org/html/rfc4180) TEXTDATA = %x20-21 / %x23-2B / %x2D-7E if (newRecord && (c < '0' || c > '9' && c < 'A' || c > 'Z' && c < 'a' || c > 'z')) { quote = true; } else if (c <= COMMENT) { // Some other chars at the start of a value caused the parser to fail, so for now // encapsulate if we start in anything less than '#'. We are being conservative // by including the default comment char too. quote = true; } else { while (pos < end) { c = value.charAt(pos); if (c == LF || c == CR || c == quoteChar || c == delimChar) { quote = true; break; } pos++; } if (!quote) { pos = end - 1; c = value.charAt(pos); // Some other chars at the end caused the parser to fail, so for now // encapsulate if we end in anything less than ' ' if (c <= SP) { quote = true; } } } } if (!quote) { // no encapsulation needed - write out the original value out.append(value, start, end); return; } break; default: throw new IllegalStateException("Unexpected Quote value: " + quoteModePolicy); } if (!quote) { // no encapsulation needed - write out the original value out.append(value, start, end); return; } // we hit something that needed encapsulation out.append(quoteChar); // Pick up where we left off: pos should be positioned on the first character that caused // the need for encapsulation. while (pos < end) { final char c = value.charAt(pos); if (c == quoteChar) { // write out the chunk up until this point // add 1 to the length to write out the encapsulator also out.append(value, start, pos + 1); // put the next starting position on the encapsulator so we will // write it out again with the next string (effectively doubling it) start = pos; } pos++; } // write the last segment out.append(value, start, pos); out.append(quoteChar); } private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len, final Appendable out, final boolean newRecord) throws IOException { boolean quote = false; int start = offset; int pos = offset; final int end = offset + len; final char delimChar = getDelimiter(); final char quoteChar = getQuoteCharacter().charValue(); QuoteMode quoteModePolicy = getQuoteMode(); if (quoteModePolicy == null) { quoteModePolicy = QuoteMode.MINIMAL; } switch (quoteModePolicy) { case ALL: quote = true; break; case NON_NUMERIC: quote = !(object instanceof Number); break; case NONE: // Use the existing escaping code printAndEscape(value, offset, len, out); return; case MINIMAL: if (len <= 0) { // always quote an empty token that is the first // on the line, as it may be the only thing on the // line. If it were not quoted in that case, // an empty line has no tokens. if (newRecord) { quote = true; } } else { char c = value.charAt(pos); // RFC4180 (https://tools.ietf.org/html/rfc4180) TEXTDATA = %x20-21 / %x23-2B / %x2D-7E if (newRecord && (c < 0x20 || c > 0x21 && c < 0x23 || c > 0x2B && c < 0x2D || c > 0x7E)) { quote = true; } else if (c <= COMMENT) { // Some other chars at the start of a value caused the parser to fail, so for now // encapsulate if we start in anything less than '#'. We are being conservative // by including the default comment char too. quote = true; } else { while (pos < end) { c = value.charAt(pos); if (c == LF || c == CR || c == quoteChar || c == delimChar) { quote = true; break; } pos++; } if (!quote) { pos = end - 1; c = value.charAt(pos); // Some other chars at the end caused the parser to fail, so for now // encapsulate if we end in anything less than ' ' if (c <= SP) { quote = true; } } } } if (!quote) { // no encapsulation needed - write out the original value out.append(value, start, end); return; } break; default: throw new IllegalStateException("Unexpected Quote value: " + quoteModePolicy); } if (!quote) { // no encapsulation needed - write out the original value out.append(value, start, end); return; } // we hit something that needed encapsulation out.append(quoteChar); // Pick up where we left off: pos should be positioned on the first character that caused // the need for encapsulation. while (pos < end) { final char c = value.charAt(pos); if (c == quoteChar) { // write out the chunk up until this point // add 1 to the length to write out the encapsulator also out.append(value, start, pos + 1); // put the next starting position on the encapsulator so we will // write it out again with the next string (effectively doubling it) start = pos; } pos++; } // write the last segment out.append(value, start, pos); out.append(quoteChar); }
src/main/java/org/apache/commons/csv/CSVFormat.java
Csv-15
private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len, final Appendable out, final boolean newRecord) throws IOException { boolean quote = false; int start = offset; int pos = offset; final int end = offset + len; final char delimChar = getDelimiter(); final char quoteChar = getQuoteCharacter().charValue(); QuoteMode quoteModePolicy = getQuoteMode(); if (quoteModePolicy == null) { quoteModePolicy = QuoteMode.MINIMAL; } switch (quoteModePolicy) { case ALL: case ALL_NON_NULL: quote = true; break; case NON_NUMERIC: quote = !(object instanceof Number); break; case NONE: // Use the existing escaping code printAndEscape(value, offset, len, out); return; case MINIMAL: if (len <= 0) { // always quote an empty token that is the first // on the line, as it may be the only thing on the // line. If it were not quoted in that case, // an empty line has no tokens. if (newRecord) { quote = true; } } else { char c = value.charAt(pos); if (newRecord && (c < 0x20 || c > 0x21 && c < 0x23 || c > 0x2B && c < 0x2D || c > 0x7E)) { quote = true; } else if (c <= COMMENT) { // Some other chars at the start of a value caused the parser to fail, so for now // encapsulate if we start in anything less than '#'. We are being conservative // by including the default comment char too. quote = true; } else { while (pos < end) { c = value.charAt(pos); if (c == LF || c == CR || c == quoteChar || c == delimChar) { quote = true; break; } pos++; } if (!quote) { pos = end - 1; c = value.charAt(pos); // Some other chars at the end caused the parser to fail, so for now // encapsulate if we end in anything less than ' ' if (c <= SP) { quote = true; } } } } if (!quote) { // no encapsulation needed - write out the original value out.append(value, start, end); return; } break; default: throw new IllegalStateException("Unexpected Quote value: " + quoteModePolicy); } if (!quote) { // no encapsulation needed - write out the original value out.append(value, start, end); return; } // we hit something that needed encapsulation out.append(quoteChar); // Pick up where we left off: pos should be positioned on the first character that caused // the need for encapsulation. while (pos < end) { final char c = value.charAt(pos); if (c == quoteChar) { // write out the chunk up until this point // add 1 to the length to write out the encapsulator also out.append(value, start, pos + 1); // put the next starting position on the encapsulator so we will // write it out again with the next string (effectively doubling it) start = pos; } pos++; } // write the last segment out.append(value, start, pos); out.append(quoteChar); } private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len, final Appendable out, final boolean newRecord) throws IOException { boolean quote = false; int start = offset; int pos = offset; final int end = offset + len; final char delimChar = getDelimiter(); final char quoteChar = getQuoteCharacter().charValue(); QuoteMode quoteModePolicy = getQuoteMode(); if (quoteModePolicy == null) { quoteModePolicy = QuoteMode.MINIMAL; } switch (quoteModePolicy) { case ALL: case ALL_NON_NULL: quote = true; break; case NON_NUMERIC: quote = !(object instanceof Number); break; case NONE: // Use the existing escaping code printAndEscape(value, offset, len, out); return; case MINIMAL: if (len <= 0) { // always quote an empty token that is the first // on the line, as it may be the only thing on the // line. If it were not quoted in that case, // an empty line has no tokens. if (newRecord) { quote = true; } } else { char c = value.charAt(pos); if (c <= COMMENT) { // Some other chars at the start of a value caused the parser to fail, so for now // encapsulate if we start in anything less than '#'. We are being conservative // by including the default comment char too. quote = true; } else { while (pos < end) { c = value.charAt(pos); if (c == LF || c == CR || c == quoteChar || c == delimChar) { quote = true; break; } pos++; } if (!quote) { pos = end - 1; c = value.charAt(pos); // Some other chars at the end caused the parser to fail, so for now // encapsulate if we end in anything less than ' ' if (c <= SP) { quote = true; } } } } if (!quote) { // no encapsulation needed - write out the original value out.append(value, start, end); return; } break; default: throw new IllegalStateException("Unexpected Quote value: " + quoteModePolicy); } if (!quote) { // no encapsulation needed - write out the original value out.append(value, start, end); return; } // we hit something that needed encapsulation out.append(quoteChar); // Pick up where we left off: pos should be positioned on the first character that caused // the need for encapsulation. while (pos < end) { final char c = value.charAt(pos); if (c == quoteChar) { // write out the chunk up until this point // add 1 to the length to write out the encapsulator also out.append(value, start, pos + 1); // put the next starting position on the encapsulator so we will // write it out again with the next string (effectively doubling it) start = pos; } pos++; } // write the last segment out.append(value, start, pos); out.append(quoteChar); }
src/main/java/org/apache/commons/csv/CSVFormat.java
Csv-2
public String get(final String name) { if (mapping == null) { throw new IllegalStateException( "No header mapping was specified, the record values can't be accessed by name"); } final Integer index = mapping.get(name); return index != null ? values[index.intValue()] : null; } public String get(final String name) { if (mapping == null) { throw new IllegalStateException( "No header mapping was specified, the record values can't be accessed by name"); } final Integer index = mapping.get(name); try { return index != null ? values[index.intValue()] : null; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException( String.format( "Index for header '%s' is %d but CSVRecord only has %d values!", name, index.intValue(), values.length)); } }
src/main/java/org/apache/commons/csv/CSVRecord.java
Csv-3
int readEscape() throws IOException { // the escape char has just been read (normally a backslash) final int c = in.read(); switch (c) { case 'r': return CR; case 'n': return LF; case 't': return TAB; case 'b': return BACKSPACE; case 'f': return FF; case CR: case LF: case FF: // TODO is this correct? case TAB: // TODO is this correct? Do tabs need to be escaped? case BACKSPACE: // TODO is this correct? return c; case END_OF_STREAM: throw new IOException("EOF whilst processing escape sequence"); default: // Now check for meta-characters return c; // indicate unexpected char - available from in.getLastChar() } } int readEscape() throws IOException { // the escape char has just been read (normally a backslash) final int c = in.read(); switch (c) { case 'r': return CR; case 'n': return LF; case 't': return TAB; case 'b': return BACKSPACE; case 'f': return FF; case CR: case LF: case FF: // TODO is this correct? case TAB: // TODO is this correct? Do tabs need to be escaped? case BACKSPACE: // TODO is this correct? return c; case END_OF_STREAM: throw new IOException("EOF whilst processing escape sequence"); default: // Now check for meta-characters if (isDelimiter(c) || isEscape(c) || isQuoteChar(c) || isCommentStart(c)) { return c; } // indicate unexpected char - available from in.getLastChar() return END_OF_STREAM; } }
src/main/java/org/apache/commons/csv/Lexer.java
Csv-4
public Map<String, Integer> getHeaderMap() { return new LinkedHashMap<String, Integer>(this.headerMap); } public Map<String, Integer> getHeaderMap() { return this.headerMap == null ? null : new LinkedHashMap<String, Integer>(this.headerMap); }
src/main/java/org/apache/commons/csv/CSVParser.java
Csv-5
public void println() throws IOException { final String recordSeparator = format.getRecordSeparator(); out.append(recordSeparator); newRecord = true; } public void println() throws IOException { final String recordSeparator = format.getRecordSeparator(); if (recordSeparator != null) { out.append(recordSeparator); } newRecord = true; }
src/main/java/org/apache/commons/csv/CSVPrinter.java
Csv-6
<M extends Map<String, String>> M putIn(final M map) { for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); map.put(entry.getKey(), values[col]); } return map; } <M extends Map<String, String>> M putIn(final M map) { for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); if (col < values.length) { map.put(entry.getKey(), values[col]); } } return map; }
src/main/java/org/apache/commons/csv/CSVRecord.java
Csv-9
<M extends Map<String, String>> M putIn(final M map) { for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); if (col < values.length) { map.put(entry.getKey(), values[col]); } } return map; } <M extends Map<String, String>> M putIn(final M map) { if (mapping == null) { return map; } for (final Entry<String, Integer> entry : mapping.entrySet()) { final int col = entry.getValue().intValue(); if (col < values.length) { map.put(entry.getKey(), values[col]); } } return map; }
src/main/java/org/apache/commons/csv/CSVRecord.java