/*
Function to validate AST structures
968130
function runValidator(param, paramName) {
  if (!validator(param)) {
    console.log('Error message from validator: ' + validator.errors[0].message);
    console.log('Error message from validator: ', validator.errors[0]);
    throw new error.MalformedAstError(
      paramName +
        ' must be well-defined and follow the AST schema. ' +
        'Object: ' +
        JSON.stringify(param)
    );
  }
}
378346
function(val, ctx, partials, inverted, start, end, tags) {
      var pass;

      if (isArray(val) && val.length === 0) {
        return false;
      }

      if (typeof val == 'function') {
        val = this.ls(val, ctx, partials, inverted, start, end, tags);
      }

      pass = (val === '') || !!val;

      if (!inverted && pass && ctx) {
        ctx.push((typeof val == 'object') ? val : ctx[ctx.length - 1]);
      }

      return pass;
    }
613729
function validateFileset(fileset, setter) {
    if (Array.isArray(fileset)) {
        async.each(fileset, function(path, callback) {
            if (typeof path === 'string') {
                callback();
            } else {
                callback(util.format('Invalid path: %s', path));
            }
        }, function(err) {
            if (err) {
                console.log(chalk.red(err));
            } else {
                setter(fileset);
            }
        });
    } else {
        console.log(chalk.red('Fileset is not an array: %j'), fileset);
    }
}
607069
function hoistDeclarations(ast) {
        var sequences = {
            TemplateLiteral: function (x) {
                return x.expressions;
            },
            NewExpression: function (x) {
                return x.arguments;
            },
            CallExpression: function (x) {
                return x.arguments;
            },
            SequenceExpression: function (x) {
                return x.expressions;
            },
            ArrayExpression: function (x) {
                return x.elements;
            },
            ObjectExpression: function (oe) {
                return oe.properties.map(function (p) {
                    return p.value;
                });
            }
        };
        /* Identify SequenceExpressions, Parameter lists and VariableDeclarators that contain assigments and split them up
        to ensure the correct evaluation order */
        function containsAssign(ast) {
            return contains(ast, function (n) {
                return n.type === 'AssignmentExpression';
            });
        }
        
        treeWalk(ast, function (node, descend, path) {
            var i;
            descend();
            // Ensure assigments are evaluated before any await expressions, eg:
            // f(a=1, b = await a) --> a=1; f(a,b=await a)
            function moveAssignments(dest) {
                if (assignments.length) {
                    dest.argument = {
                        type: 'SequenceExpression',
                        expressions: assignments.map(function (a) {
                            var b = cloneNode(a);
                            coerce(a, a.left);
                            return b;
                        }).concat(dest.argument)
                    };
                    assignments = [];
                }
            }
            
            if (node.type in sequences && !node.$hoisted) {
                var expr = sequences[node.type](node);
                var assignments = [];
                var path;
                for (i = 0; i < expr.length; i++) {
                    if (examine(expr[i]).isScope) 
                        continue;
                    if (path = containsAwait(expr[i])) 
                        moveAssignments(path[0].self);
                    if (!containsAwait(expr.slice(i + 1))) 
                        break;
                    if (path = containsAssign(expr[i])) 
                        assignments.push(path[0].self);
                }
            } else if (node.type === 'VariableDeclaration') {
                // If any of the VariableDeclarators contain an initial value and are followed by a VariableDeclarator
                // containing an await, split them up into multiple statements
                for (i = node.declarations.length - 1; i > 0; i--) {
                    if (node.declarations[i] && node.declarations[i].init && containsAwait(node.declarations[i].init)) {
                        var insert = {
                            type: 'VariableDeclaration',
                            kind: node.kind,
                            declarations: node.declarations.splice(i)
                        };
                        var ref = path[0];
                        if ('index' in ref) {
                            ref.parent[ref.field].splice(ref.index + 1, 0, insert);
                        } else 
                            throw new Error("VariableDeclaration not in a block");
                    }
                }
            }
        });
        /* Hoist declarations */
        function isFreeVariable(kinds) {
            return function (n, path) {
                if (n.type === 'VariableDeclaration' && (n.kind = n.kind || 'var') && kinds.indexOf(n.kind) >= 0) {
                    var p = path[0];
                    // Don't hoist the LHS of for (var/let/const _ of/in ... ; ;){}
                    if (p.field == "left" && (p.parent.type === 'ForInStatement' || p.parent.type === 'ForOfStatement')) 
                        return false;
                    // Don't hoist the LHS of for (let/const _ = ... ; ;){}
                    if (p.field == "init" && p.parent.type === 'ForStatement' && (n.kind === "const" || n.kind === "let")) 
                        return false;
                    return true;
                }
            };
        }
        
        function isHoistableFunction(n, path) {
            // YES: We're a named function, but not a continuation
            if (n.type === 'FunctionDeclaration' && n.id) {
                return examine(n).isAsync || !n.$continuation;
            }
            // No, we're not a hoistable function
            return false;
        }
        
        checkConstsNotAssigned(ast);
        var inStrictBody = false;
        treeWalk(ast, function (node, descend, path) {
            var prevScope = inStrictBody;
            inStrictBody = inStrictBody || isStrict(node);
            if (examine(node).isBlockStatement) {
                if (containsAwait(node)) {
                    // For this scope/block, find all the hoistable functions, vars and directives
                	    var isVarScope = !path[0].parent || examine(path[0].parent).isScope  ; 
                	    var isLoopScope = path[0].parent && examine(path[0].parent).isLoop ;
                    var isScope = isVarScope || isLoopScope ;
                    /* 'const' is highly problematic. In early version of Chrome (Node 0.10, 4.x, 5.x) non-standard behaviour:
                     *
                     * Node             scope           multiple-decls
                     * v0.1x            function        SyntaxError
                     * v0.1x strict     SyntaxError     SyntaxError
                     * 4/5.x            function        SyntaxError
                     * 4/5.x strict     block           ok (SyntaxError on duplicate in block)
                     * 6.x  (as 4/5.x strict)
                     *
                     * To make these non-standard behaviours work, we treat a single declaration of a const identifier as requiring function scope (which works everywhere),
                     * declare as a 'var' and initialize inline.
                     * We treat multiple declarations as block-scoped, and let the engine work it out. To make consts blocked-scope, we use 'const' where possible (i.e. before
                     * any await expressions), or declare as 'let' after an await. This breaks in non-strict mode in Node 4/5, as 'let' requires strict mode.
                     *
                     * In summary, what this means is:
                     * - const's with a single declaration in the current scope (NOT block) should be hoisted to function level, and defined as 'var'
                     * - const's with duplicate declarations in the current scope (NOT block) should be hoisted to block level, and defined as 'let'
                     */
                    var directives, consts, vars, lets, functions;
                    if (isScope) {
                        consts = scopedNodes(node, isFreeVariable(['const']), false);
                        var names = {}, duplicates = {};
                        // Work out which const identifiers are duplicates
                        // Ones that are only declared once can simply be treated as vars, whereas
                        // identifiers that are declared multiple times have block-scope and are
                        // only valid in node 6 or in strict mode on node 4/5. 
                        // In strict mode or ES6-a-like targets always assume the correct ES6 semantics (block scope)
                        consts.forEach(function (d) {
                            d[0].self.declarations.forEach(function (e) {
                                getDeclNames(e.id).forEach(function (n) {
                                    if (inStrictBody || looksLikeES6 || names[n] || duplicates[n]) {
                                    	   looksLikeES6 = true ;
                                        delete names[n];
                                        duplicates[n] = e;
                                    } else {
                                        names[n] = e;
                                    }
                                });
                            });
                        });
                        // Change all the declarations into assignments, since consts are always initialized
                        consts.forEach(function (d) {
                            for (var depth = 0;depth < d.length; depth++) 
                                if (examine(d[depth].parent).isBlockStatement) 
                                break;
                            var ref = d[depth];
                            ref.append({
                                type: 'ExpressionStatement',
                                expression: {
                                    type: 'SequenceExpression',
                                    expressions: d[0].self.declarations.map(function (d) {
                                        var a = {
                                            type: 'AssignmentExpression',
                                            operator: '=',
                                            left: d.id,
                                            right: d.init
                                        };
                                        d.init = null;
                                        return a;
                                    })
                                }
                            });
                            var ids = getDeclNames(d[0].self.declarations);
                            var decls = ids.filter(function (name) {
                                return name in duplicates;
                            });
                            if (decls.length) {
                                d[0].append({
                                    type: 'VariableDeclaration',
                                    kind: 'let',
                                    declarations: decls.map(function (name) {
                                        return {
                                            type: 'VariableDeclarator',
                                            id: ident(name)
                                        };
                                    })
                                });
                            }
                            d[0].self.kind = 'var';
                            decls = ids.filter(function (name) {
                                return name in names;
                            });
                            if (decls.length) {
                                d[0].self.declarations = decls.map(function (name) {
                                    return {
                                        type: 'VariableDeclarator',
                                        id: ident(name)
                                    };
                                });
                            } else {
                                ref.remove();
                            }
                        });
                        if (isVarScope && !isLoopScope) vars = scopedNodes(node, isFreeVariable(['var']), ['isScope']);
                        lets = [];
                    } else {
                        lets = scopedNodes(node, isFreeVariable(['const']), true);
                    }
                    lets = lets.concat(scopedNodes(node, isFreeVariable(['let']), true));
                    directives = scopedNodes(node, function (n) {
                        return examine(n).isDirective;
                    }, true);
                    functions = scopedNodes(node, isHoistableFunction, inStrictBody);
                    vars = vars ? extractVars(vars, 'var') : {
                        duplicates: {},
                        decls: []
                    };
                    lets = lets ? extractVars(lets, 'let') : {
                        duplicates: {},
                        decls: []
                    };
                    Object.keys(vars.duplicates).forEach(function (id) {
                        logger(where(vars.duplicates[id]) + "Duplicate declaration '" + printNode(vars.duplicates[id]) + "'");
                    });
                    Object.keys(lets.duplicates).forEach(function (id) {
                        logger(where(lets.duplicates[id]) + "Duplicate declaration '" + printNode(lets.duplicates[id]) + "'");
                    });
                    functions = functions.map(function (path) {
                        var ref = path[0], symName;
                        // What is the name of this function (could be async, so check the expression if necessary),
                        // and should we remove and hoist, or reference and hoist?
                        if (examine(ref.self).isAsync) {
                            symName = ref.self.id.name;
                            // If we're actually a top-level async FunctionExpression, redeclare as a FunctionDeclaration
                            if (examine(ref.parent).isBlockStatement) {
                                ref.self.type = 'FunctionDeclaration';
                                ref.remove();
                                return ref.self;
                            }
                            // We're an async FunctionExpression
                            return ref.replace(ident(symName));
                        }
                        // We're just a vanilla FunctionDeclaration or FunctionExpression
                        symName = ref.self.id.name;
                        var movedFn = ref.self.type === 'FunctionDeclaration' ? ref.remove() : ref.replace(ident(symName));
                        return movedFn;
                    });
                    directives = directives.map(function (path) {
                        var ref = path[0];
                        return ref.remove();
                    });
                    if (directives.length || vars.decls.length || lets.decls.length || functions.length) {
                        node.body = directives.concat(vars.decls).concat(lets.decls).concat(functions).concat(node.body);
                    }
                }
                inStrictBody = prevScope;
            }
            // Labeled breaks need to be treated as loops that always exit early, if they contain awaits
            if (node.type === 'LabeledStatement' && node.body.type === 'BlockStatement' && containsAwait(node.body)) {
                if (contains(node.body, function (m) {
                    return m.type === 'BreakStatement' && m.label && m.label.name == node.label.name;
                })) {
                    node.body.body.push({
                        type: 'BreakStatement'
                    });
                    node.body = {
                        type: 'DoWhileStatement',
                        test: literal(0),
                        body: node.body
                    };
                }
            }
            descend();
            // It makes life easier if labeled loops have the label to hand, so we simply reference them here with a hidden $label
            // and keep a record of how nested the for loop is (since it's transformed top to bottom and counting during
            // transformation is therefore not possible
            if (node.type === 'ForOfStatement' || node.type === 'ForInStatement' || examine(node).isLoop) {
                var depth = 0;
                for (var n = 0;n < path.length; n++) 
                    if (path[n].self.type === 'ForOfStatement' || path[n].self.type === 'ForInStatement' || examine(path[n].self).isLoop) 
                    depth += 1;
                 else if (examine(path[n].self).isFunction) 
                    break;
                node.$depth = depth;
                if (path[0].parent.type === 'LabeledStatement') {
                    node.$label = path[0].parent.label;
                } else {
                    node.$label = null;
                }
            }
            return true;
        });
        return ast;
    }
553020
function rule( context ) {
	/**
	* FUNCTION: validateLiteral( node )
	*	Validates a regular expression literal.
	*
	* @param {Node} node - AST node
	* @returns {Void}
	*/
	function validateLiteral( node ) {
		var token = context.getTokens( node )[ 0 ];
		if (
			token.type === 'RegularExpression' &&
			!safe( token.value )
		) {
			context.report( node, 'Unsafe regular expression' );
		}
	} // end FUNCTION validateLiteral()

	/**
	* FUNCTION: validateExpression( node )
	*	Validates a regular expression creating using the `RegExp` constructor.
	*
	* @param {Node} node - AST node
	* @returns {Void}
	*/
	function validateExpression( node ) {
		var args,
			len,
			re,
			i;

		if ( node.callee.name === 'RegExp' ) {
			len = node.arguments.length;
			args = new Array( node.arguments.length );
			for ( i = 0; i < len; i++ ) {
				// NOTE: we only support literals ATM. Otherwise, we may need to walk and implement an entire tree.
				if ( node.arguments[ i ].type !== 'Literal' ) {
					return;
				}
				args[ i ] = node.arguments[ i ].value;
			}
			re = RegExp.apply( null, args );
			if ( !safe( re ) ) {
				context.report( node, 'Unsafe regular expression' );
			}
		}
	} // end FUNCTION validateExpression()

	return {
		'Literal': validateLiteral,
		'NewExpression': validateExpression,
		'CallExpression': validateExpression
	};
}
1210580
function validate(cmd, args, info) {
  AbstractCommand.prototype.validate.apply(this, arguments);
  var op = ('' + args[0]).toLowerCase();
  if(op !== BITOP.AND && op !== BITOP.OR
    && op !== BITOP.XOR && op !== BITOP.NOT) {
    throw CommandSyntax;
  }
  if(op === BITOP.NOT && args.length !== 3) {
    throw BitopNot;
  }
  args[0] = op;
}
659714
function validate(templateTags, attrs) {
            const valueTokens = attrs
                .map(attr => attr.valueToken)
                .filter(t => Boolean(t))
            for (const templateTag of templateTags) {
                if (
                    valueTokens.some(
                        valueToken =>
                            valueToken.range[0] <= templateTag.range[0] &&
                            templateTag.range[1] <= valueToken.range[1]
                    )
                ) {
                    continue
                }
                const isInterpolate =
                    templateTag.type === "MicroTemplateInterpolate" ||
                    templateTag.type === "MicroTemplateEscape"
                if (isInterpolate ? arrowInterpolateTag : arrowEvaluateTag) {
                    continue
                }
                context.report({
                    node: templateTag,
                    messageId: isInterpolate
                        ? "unexpectedInterpolate"
                        : "unexpectedEvaluate",
                })
            }
        }
994896
function compileValidator( attributes ) {
	if ( !attributes || typeof attributes !== "object" || Array.isArray( attributes ) ) {
		throw new TypeError( "definition of attributes must be object" );
	}

	const attributeNames = Object.keys( attributes );
	const numAttributes = attributeNames.length;
	const validation = [];

	for ( let ai = 0; ai < numAttributes; ai++ ) {
		const attributeName = attributeNames[ai];
		const attribute = attributes[attributeName];

		const handler = Types.selectByName( attribute.type );

		const { args, body } = extractBody( handler.isValid );
		if ( args.length < 4 ) {
			throw new TypeError( `isValid() of ModelType for handling ${attribute.type} values must accept four arguments` );
		}

		validation[ai] = `
{
	const ${args[0]} = "${attributeName}";
	let ${args[1]} = __props["${attributeName}"];
	const ${args[2]} = __attrs["${attributeName}"];
	const ${args[3]} = __errors;

	{
		${body}
	}
}
		`;
	}

	// eslint-disable-next-line no-new-func
	return new Function( `
const __attrs = this.constructor.schema.attributes;
const __props = this.properties;
const __errors = [];

${validation.join( "" )}

return __errors;
` );
}
1111087
function validate(key, values) {
  if(this.arity > 0 && values.length !== this.arity) {
    throw new TypeDefError(
      util.format('bad arity for \'%s\', expected %s got %s',
        key, this.arity, values.length));
  }
  var types = Array.isArray(this.type) ? this.type : [this.type]
    , i
    , type
    , val
    , num
    , coerced = []
    , enumerable = false;

  for(i = 0;i < types.length;i++) {
    type = types[i];
    val = values[i];
    enumerable = Array.isArray(type);
    if(enumerable) {
      if(!~type.indexOf(val)) {
        throw new TypeDefError(
          util.format('enum error on key \'%s\', got \'%s\' expected one of %s',
            key, val, type.join(', ')));
      }
    }
    switch(type) {
      case ByteSize:
        val = ByteSize.parse(val);
        break;
      case Boolean:
        if(val !== YES && val !== NO) {
          throw new Error(
            util.format('argument must be \'%s\' or \'%s\'', YES, NO));
        }
        val = val === YES ? true : false;
        break;
      case String:
        // strings can be quoted
        val = val.replace(/^"/, '').replace(/"$/, '');
        break;
      case Number:
        num = parseInt(val);
        if(isNaN(num) || !/^-?[0-9]+$/.test(val)) {
          throw new TypeDefError(
            util.format('number expected for \'%s\', got %s', key, val));
        }
        val = num;
        break;
    }

    coerced[i] = val;
  }
  if(this.arity === 1 && !this.repeats) return coerced[0];
  return Array.isArray(this.type) ? coerced : coerced[0];
}
456035
function(F) {
        var validSet = [];
        for (var i = 0; i < F.length; i++) {
            if (F[i].isValid()) {
                validSet.push(F[i]);
            }
        }
        return validSet;
    }
75193
function autoValidate(object) {
  const seq = (object) ? object.seq : undefined;
  const action = (object) ? object.action : undefined;

  const schema = identifySchema(object)

  if (schema) {
    const {error, value} = validate(object, schema);

    if (error) {
      return { isValid: false, seq, action, error };
    } else {
      return { isValid: true, seq, action, value };
    }
  } else {
    return { isValid: false, seq, action,
      error: new Error('No matching schema found.') };
  }
}
843563
protected void validateSingle(
        CmsUUID structureId,
        Map<String, String> sitePaths,
        String newSitePath,
        final AsyncCallback<String> errorCallback) {

        Map<String, String> newMap = new HashMap<String, String>(sitePaths);
        newMap.put("NEW", newSitePath); //$NON-NLS-1$
        AsyncCallback<Map<String, String>> callback = new AsyncCallback<Map<String, String>>() {

            public void onFailure(Throwable caught) {

                assert false; // should never happen
            }

            public void onSuccess(Map<String, String> result) {

                String newRes = result.get("NEW"); //$NON-NLS-1$
                errorCallback.onSuccess(newRes);
            }
        };
        validateAliases(structureId, newMap, callback);
    }
1275588
private boolean validFormat(final String s) {
        String[] args = ARGS_REGEX.split(s);
        if (noItems(args)) return false;
        if (args.length < 3) return false;

        // Check for the presence of a function name
        String name = args[0];
        if (name.isEmpty()) return false;
        if (!validFunction(name)) return false;

        // Check for the presence of a return type
        String returntype = args[args.length - 1];
        if (returntype.isEmpty()) return false;
        if (!validReturnType(returntype)) return false;

        // Check for zero or more arguments
        String arglist = args[1];
        if (arglist.isEmpty()) return true;

        // Split parameters on comma
        String[] argsplit = arglist.split(",");
        for (final String arg : argsplit) {
            if (!validParameter(arg)) return false;
        }
        return true;
    }
90681
async function validate(descriptor) {
  const {valid, errors} = await Package.load(descriptor)
  return {valid, errors}
}
260550
function validateAndMaskMode(value, def, callback) {
  if(typeof def === 'function') {
    callback = def;
    def = undefined;
  }

  if (isUint32(value)) {
    return value & FULL_READ_WRITE_EXEC_PERMISSIONS;
  }

  if (typeof value === 'number') {
    if (!Number.isInteger(value)) {
      callback(new Errors.EINVAL('mode not a valid an integer value', value));
      return false;
    } else {
      // 2 ** 32 === 4294967296
      callback(new Errors.EINVAL('mode not a valid an integer value', value));
      return false;
    }
  }

  if (typeof value === 'string') {
    if (!octalReg.test(value)) {
      callback(new Errors.EINVAL('mode not a valid octal string', value));
      return false;
    }
    var parsed = parseInt(value, 8);
    return parsed & FULL_READ_WRITE_EXEC_PERMISSIONS;
  }

  // TODO(BridgeAR): Only return `def` in case `value === null`
  if (def !== undefined) {
    return def;
  }

  callback(new Errors.EINVAL('mode not valid', value));
  return false;
}
1365328
function(node, name, data) {
  typeCheckString(key, 'key');
  typeCheckObject(data, 'data');
  typeCheckObject(node, 'node');
  runValidator(node, 'node');

  if (typeof node !== 'object') {
    throw new error.InvalidParameterError(
      'Parameter ast must be a well-defined JSON object.'
    );
  }
  if (validator(node)) {
    throw new error.MalformedAstError(
      'Parameter ast needs to be a JSON structure according to the schema.'
    );
  }
  if (typeof data !== 'object') {
    throw new error.InvalidParameterError(
      'Parameter data must be a well-defined JSON object.'
    );
  }
  if (typeof name !== 'string') {
    throw new error.InvalidParameterError('Parameter name must be a string.');
  }
  const newNode = Object.assign({}, node);
  if (newNode.properties) {
    newNode.properties[name] = data;
  }
  return newNode;
}
1132253
function validateArguments(parens, elements) {
            const leftParen = parens.leftParen;
            const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen);
            const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen);
            const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline);

            for (let i = 0; i <= elements.length - 2; i++) {
                const currentElement = elements[i];
                const nextElement = elements[i + 1];
                const hasNewLine = currentElement.loc.end.line !== nextElement.loc.start.line;

                if (!hasNewLine && needsNewlines) {
                    context.report({
                        node: currentElement,
                        messageId: "expectedBetween",
                        fix: fixer => fixer.insertTextBefore(nextElement, "\n")
                    });
                }
            }
        }