Search in sources :

Example 1 with CFLintScanException

use of com.cflint.exception.CFLintScanException in project CFLint by cflint.

the class CFLint method process.

private void process(final CFScriptStatement expression, final Context context) {
    if (expression == null) {
        return;
    }
    if (expression != null && expression.getToken() != null) {
        final List<Object> checkItem = Arrays.asList(expression, expression.getToken());
        if (processed.contains(checkItem)) {
            if (!quiet) {
                System.err.println("Attempt to process expression twice aborted.  This may be a parsing bug in " + context.getFilename() + " : " + (expression.getToken() != null ? expression.getToken().getLine() : ""));
            }
            return;
        }
        processed.add(checkItem);
    }
    final Element elem = context.getElement();
    try {
        if (expression instanceof CFCompoundStatement) {
            scanExpression(expression, context, elem);
            for (final CFScriptStatement statement : ((CFCompoundStatement) expression).getStatements()) {
                process(statement, context);
            }
        } else if (expression instanceof CFExpressionStatement) {
            scanExpression(expression, context, elem);
            registerRuleOverrides(context, (CFExpressionStatement) expression);
            process(((CFExpressionStatement) expression).getExpression(), elem, context);
        } else if (expression instanceof CFPropertyStatement) {
            try {
                final CFPropertyStatement propertyStatement = (CFPropertyStatement) expression;
                CFExpression value = propertyStatement.getPropertyName();
                if (value == null) {
                    for (final Entry<CFIdentifier, CFExpression> entry : propertyStatement.getAttributes().entrySet()) {
                        if (CF.NAME.equalsIgnoreCase(entry.getKey().getName())) {
                            value = entry.getValue();
                        }
                    }
                }
                if (value != null) {
                    final String name = value.Decompile(0);
                    handler.addVariable(name.substring(1, name.length() - 1));
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }
            scanExpression(expression, context, elem);
        } else if (expression instanceof CFCompDeclStatement) {
            final CFCompDeclStatement compDeclStatement = (CFCompDeclStatement) expression;
            final Context componentContext = context.subContext(null);
            componentContext.setInComponent(true);
            componentContext.setContextType(ContextType.COMPONENT);
            for (final Entry<CFExpression, CFExpression> entry : compDeclStatement.getAttributes().entrySet()) {
                if (entry.getKey() != null && entry.getKey().Decompile(0).equalsIgnoreCase(CF.NAME)) {
                    componentContext.setComponentName(entry.getValue().Decompile(0));
                }
            }
            // Register any overrides from multi-line comments.
            registerRuleOverrides(componentContext, expression.getToken());
            // do startComponent notifications
            doStructureStart(elem, componentContext, expression.getClass());
            scanExpression(compDeclStatement, componentContext, elem);
            // process the component declaration
            if (compDeclStatement.getBody() instanceof CFCompoundStatement) {
                // Process property expressions first
                for (final CFScriptStatement subscript : compDeclStatement.getBody().decomposeScript()) {
                    if (subscript instanceof CFPropertyStatement) {
                        process(subscript, componentContext);
                    }
                }
                for (final CFScriptStatement subscript : compDeclStatement.getBody().decomposeScript()) {
                    if (!(subscript instanceof CFPropertyStatement)) {
                        process(subscript, componentContext);
                    }
                }
            } else {
                process(compDeclStatement.getBody(), componentContext);
            }
            // do endComponent notifications
            for (final CFLintStructureListener structurePlugin : getStructureListeners(extensions)) {
                try {
                    structurePlugin.endComponent(componentContext, bugs);
                    for (final ContextMessage message : componentContext.getMessages()) {
                        reportRule(elem, null, componentContext, (CFLintScanner) structurePlugin, message);
                    }
                    componentContext.getMessages().clear();
                } catch (final Exception e) {
                    printException(e);
                    final ContextMessage cm = new ContextMessage(PARSE_ERROR, null, null, context.startLine());
                    reportRule(currentElement, null, context, null, cm);
                }
            }
        } else if (expression instanceof CFForStatement) {
            scanExpression(expression, context, elem);
            process(((CFForStatement) expression).getInit(), elem, context);
            process(((CFForStatement) expression).getCond(), elem, context);
            process(((CFForStatement) expression).getNext(), elem, context);
            process(((CFForStatement) expression).getBody(), context);
        } else if (expression instanceof CFWhileStatement) {
            scanExpression(expression, context, elem);
            process(((CFWhileStatement) expression).getCond(), elem, context);
            process(((CFWhileStatement) expression).getBody(), context);
        } else if (expression instanceof CFForInStatement) {
            scanExpression(expression, context, elem);
            final Context forInitContext = context.subContext(elem);
            forInitContext.setInAssignmentExpression(true);
            process(((CFForInStatement) expression).getVariable(), elem, forInitContext);
            process(((CFForInStatement) expression).getStructure(), elem, context);
            process(((CFForInStatement) expression).getBody(), context);
        } else if (expression instanceof CFIfStatement) {
            scanExpression(expression, context, elem);
            final CFIfStatement cfif = (CFIfStatement) expression;
            process(cfif.getCond(), elem, context);
            process(cfif.getThenStatement(), context);
            process(cfif.getElseStatement(), context);
        } else if (expression instanceof CFSwitchStatement) {
            scanExpression(expression, context, elem);
            final CFSwitchStatement cfswitch = (CFSwitchStatement) expression;
            process(cfswitch.getVariable(), elem, context);
            for (final CFCase _case : cfswitch.getCases()) {
                process(_case, context);
            }
        } else if (expression instanceof CFCase) {
            scanExpression(expression, context, elem);
            final CFCase cfcase = (CFCase) expression;
            for (final CFScriptStatement cfstatement : cfcase.getStatements()) {
                process(cfstatement, context);
            }
        } else if (expression instanceof CFTryCatchStatement) {
            scanExpression(expression, context, elem);
            final CFTryCatchStatement cftry = (CFTryCatchStatement) expression;
            process(cftry.getBody(), context);
            for (final CFCatchStatement stmt : cftry.getCatchStatements()) {
                handler.push(CF.CFCATCH);
                if (stmt.getVariable() != null && stmt.getVariable().getName() != null) {
                    handler.addVariable(stmt.getVariable().getName());
                }
                process(stmt.getCatchBody(), context);
                handler.pop();
            }
            process(cftry.getFinallyStatement(), context);
        } else if (expression instanceof CFReturnStatement) {
            scanExpression(expression, context, elem);
            final CFReturnStatement cfreturn = (CFReturnStatement) expression;
            final CFExpression subExpression = cfreturn.getExpression();
            process(subExpression, elem, context);
        } else if (expression instanceof CFFuncDeclStatement) {
            final CFFuncDeclStatement function = (CFFuncDeclStatement) expression;
            final Context functionContext = context.subContext(null);
            functionContext.setContextType(ContextType.FUNCTION);
            functionContext.setFunctionInfo(function);
            registerRuleOverrides(functionContext, function.getToken());
            handler.push(CF.FUNCTION);
            for (final CFFunctionParameter param : function.getFormals()) {
                handler.addArgument(param.getName());
            }
            doStructureStart(elem, functionContext, CFFuncDeclStatement.class);
            scanExpression(expression, functionContext, elem);
            final Context functionBodyContext = functionContext.subContext(null);
            process(function.getBody(), functionBodyContext);
            for (final CFLintStructureListener structurePlugin : getStructureListeners(extensions)) {
                try {
                    structurePlugin.endFunction(functionContext, bugs);
                    for (final ContextMessage message : functionContext.getMessages()) {
                        reportRule(elem, null, functionContext, (CFLintScanner) structurePlugin, message);
                    }
                    functionContext.getMessages().clear();
                } catch (final Exception e) {
                    printException(e);
                    final ContextMessage cm = new ContextMessage(PARSE_ERROR, null, null, context.startLine());
                    reportRule(currentElement, null, context, null, cm);
                }
            }
            handler.pop();
        } else if (expression instanceof CFIncludeStatement) {
            scanExpression(expression, context, elem);
            final CFExpression includeExpr = ((CFIncludeStatement) expression).getTemplate();
            if (includeExpr instanceof CFStringExpression) {
                final List<CFExpression> subExpressions = ((CFStringExpression) includeExpr).getSubExpressions();
                if (subExpressions.size() == 1 && subExpressions.get(0) instanceof CFLiteral) {
                    final String path = ((CFLiteral) subExpressions.get(0)).getVal();
                    final File include = new File(new File(context.getFilename()).getParentFile(), path);
                    if (include.exists() || strictInclude) {
                        try {
                            if (includeFileStack.contains(include)) {
                                if (!quiet) {
                                    System.err.println("Terminated a recursive call to include file " + include);
                                }
                            } else {
                                includeFileStack.push(include);
                                process(FileUtil.loadFile(include), context.getFilename());
                                includeFileStack.pop();
                            }
                        } catch (final CFLintScanException ex) {
                            if (!quiet) {
                                System.err.println("Invalid include file " + context.getFilename());
                            }
                            final int line = context.startLine();
                            final ContextMessage cm = new ContextMessage(PARSE_ERROR, null, null, line);
                            reportRule(currentElement, "Invalid include file " + expression.getClass(), context, null, cm);
                        }
                    }
                } else if (strictInclude) {
                    if (!quiet) {
                        System.err.println("Unable to resolve template value " + context.getFilename());
                    }
                    final int line = context.startLine();
                    final ContextMessage cm = new ContextMessage(PARSE_ERROR, null, null, line);
                    reportRule(currentElement, "Unable to resolve template value " + expression.getClass(), context, null, cm);
                }
            }
        } else {
            scanExpression(expression, context, elem);
            for (CFScriptStatement childExpression : expression.decomposeScript()) {
                process(childExpression, context);
            }
        }
    } catch (final StackOverflowError soe) {
        if (!quiet) {
            System.err.println("Stack overflow in " + context.getFilename());
        }
        final int line = context.startLine();
        final ContextMessage cm = new ContextMessage(PARSE_ERROR, null, null, line);
        reportRule(currentElement, "Stack overflow on " + expression.getClass(), context, null, cm);
    }
    // Process any messages added by downstream parsing.
    for (final ContextMessage message : context.getMessages()) {
        reportRule(elem, null, context, message.getSource(), message);
    }
    context.getMessages().clear();
}
Also used : CFWhileStatement(cfml.parsing.cfscript.script.CFWhileStatement) CFFuncDeclStatement(cfml.parsing.cfscript.script.CFFuncDeclStatement) CFReturnStatement(cfml.parsing.cfscript.script.CFReturnStatement) CFLintScanException(com.cflint.exception.CFLintScanException) Element(net.htmlparser.jericho.Element) CFFunctionParameter(cfml.parsing.cfscript.script.CFFunctionParameter) CFPropertyStatement(cfml.parsing.cfscript.script.CFPropertyStatement) CFIdentifier(cfml.parsing.cfscript.CFIdentifier) CFExpression(cfml.parsing.cfscript.CFExpression) CFForStatement(cfml.parsing.cfscript.script.CFForStatement) Entry(java.util.Map.Entry) CFLiteral(cfml.parsing.cfscript.CFLiteral) List(java.util.List) ArrayList(java.util.ArrayList) CFIncludeStatement(cfml.parsing.cfscript.script.CFIncludeStatement) Context(com.cflint.plugins.Context) CFCompoundStatement(cfml.parsing.cfscript.script.CFCompoundStatement) CFLintScanner(com.cflint.plugins.CFLintScanner) CFCompDeclStatement(cfml.parsing.cfscript.script.CFCompDeclStatement) ParseException(cfml.parsing.reporting.ParseException) IOException(java.io.IOException) CFLintScanException(com.cflint.exception.CFLintScanException) CFIfStatement(cfml.parsing.cfscript.script.CFIfStatement) CFTryCatchStatement(cfml.parsing.cfscript.script.CFTryCatchStatement) CFForInStatement(cfml.parsing.cfscript.script.CFForInStatement) ContextMessage(com.cflint.plugins.Context.ContextMessage) CFStringExpression(cfml.parsing.cfscript.CFStringExpression) CFScriptStatement(cfml.parsing.cfscript.script.CFScriptStatement) CFSwitchStatement(cfml.parsing.cfscript.script.CFSwitchStatement) CFCatchStatement(cfml.parsing.cfscript.script.CFCatchStatement) CFCase(cfml.parsing.cfscript.script.CFCase) CFExpressionStatement(cfml.parsing.cfscript.script.CFExpressionStatement) File(java.io.File) CFLintStructureListener(com.cflint.plugins.CFLintStructureListener)

Example 2 with CFLintScanException

use of com.cflint.exception.CFLintScanException in project CFLint by cflint.

the class CFLint method process.

/**
 * @param expression
 *            CF expression
 * @param elem
 *            Jericho HTML element
 * @param oldcontext
 *            The previous context
 */
private void process(final CFExpression expression, final Element elem, final Context oldcontext) {
    if (expression != null) {
        final Context context = oldcontext.subContext(elem);
        for (final CFLintScanner plugin : extensions) {
            try {
                plugin.expression(expression, context, bugs);
                for (final ContextMessage message : context.getMessages()) {
                    reportRule(elem, expression, context, plugin, message);
                }
                context.getMessages().clear();
            } catch (final Exception e) {
                printException(e);
                reportRule(elem, expression, context, plugin, PLUGIN_ERROR);
            }
        }
        // Handle a few expression types in a special fashion.
        if (expression instanceof CFVarDeclExpression) {
            handler.addVariable(((CFVarDeclExpression) expression).getName());
        }
        // CFIdentifier should not decompose
        if (expression.getClass().equals(CFIdentifier.class)) {
            final String name = ((CFIdentifier) expression).getName();
            handler.checkVariable(name);
        }
        if (expression instanceof CFStructElementExpression) {
            final Context assignmentContext = context.subContext(elem);
            assignmentContext.setInStructKeyExpression(true);
            handler.push(CF.STRUCT);
            process(((CFStructElementExpression) expression).getKey(), elem, assignmentContext);
            handler.pop();
            process(((CFStructElementExpression) expression).getValue(), elem, context);
        } else if (expression instanceof CFVarDeclExpression) {
            final Context assignmentContext = context.subContext(elem);
            assignmentContext.setInAssignmentExpression(true);
            process(((CFVarDeclExpression) expression).getVar(), elem, assignmentContext);
            // Right hand side is handled below. Left hand side gets a
            // special context.
            process(((CFVarDeclExpression) expression).getInit(), elem, context);
        // Only process function call expressions
        } else if (expression instanceof CFAssignmentExpression && !(expression instanceof CFTernaryExpression)) {
            final Context assignmentContext = context.subContext(elem);
            assignmentContext.setInAssignmentExpression(true);
            process(((CFAssignmentExpression) expression).getLeft(), elem, assignmentContext);
            // Right hand side is handled below. Left hand side gets a
            // special context.
            process(((CFAssignmentExpression) expression).getRight(), elem, context);
        // Only process function call expressions
        } else if (expression instanceof CFFullVarExpression) {
            final CFFullVarExpression fullVarExpression = (CFFullVarExpression) expression;
            if (context.isInAssignmentExpression() && new CFScopes().isScoped(fullVarExpression, "local") && fullVarExpression.getExpressions().size() > 1) {
                handler.addVariable(fullVarExpression.getExpressions().get(1).Decompile(0));
            }
            final Context subContext = context.subContext(context.getElement());
            subContext.setInAssignmentExpression(false);
            for (final CFExpression expr : fullVarExpression.getExpressions()) {
                if (expr instanceof CFFunctionExpression) {
                    process(expr, elem, subContext);
                } else if (expr instanceof CFMember) {
                    process(((CFMember) expr).getExpression(), elem, subContext);
                } else if (expr instanceof CFArrayExpression) {
                    final CFArrayExpression aryExpr = (CFArrayExpression) expr;
                    if (!aryExpr.getElements().isEmpty()) {
                        process(aryExpr.getElements().get(0), elem, subContext);
                    }
                }
            }
        } else if (expression instanceof CFFunctionExpression && tagInfo.isTag(((CFFunctionExpression) expression).getFunctionName())) {
            final CFFunctionExpression functionExpr = (CFFunctionExpression) expression;
            final StringBuilder sb = new StringBuilder();
            sb.append("<").append(functionExpr.getFunctionName()).append(" ");
            for (final CFExpression expr : functionExpr.getArgs()) {
                if (expr instanceof CFAssignmentExpression) {
                    final CFAssignmentExpression assignExpr = (CFAssignmentExpression) expr;
                    sb.append(assignExpr.getLeft().Decompile(0)).append("=").append(assignExpr.getRight().Decompile(0)).append(" ");
                }
            }
            sb.append("/>");
            final CFMLSource source = new CFMLSource(sb.toString());
            try {
                processStack(source.getChildElements(), " ", context.subContextCFML(source.getChildElements().size() > 0 ? source.getChildElements().get(0) : null, expression));
            } catch (CFLintScanException e) {
            }
            if (functionExpr.getBody() != null) {
                process(functionExpr.getBody(), context);
            }
        } else if (!(expression instanceof CFNewExpression)) {
            // EXCEPT CFNewExpressions.
            for (final CFExpression child : expression.decomposeExpression()) {
                process(child, elem, context.subContextInAssignment(false));
            }
        } else {
            // Process only the right hand side of new expressions
            final CFNewExpression newExpr = (CFNewExpression) expression;
            for (final CFExpression child : (List<CFExpression>) newExpr.getArgs()) {
                if (child instanceof CFAssignmentExpression) {
                    process(((CFAssignmentExpression) child).getRight(), elem, context.subContextInAssignment(false));
                }
            }
        }
    }
}
Also used : Context(com.cflint.plugins.Context) CFStructElementExpression(cfml.parsing.cfscript.CFStructElementExpression) CFMLSource(cfml.parsing.CFMLSource) CFNewExpression(cfml.parsing.cfscript.CFNewExpression) CFFunctionExpression(cfml.parsing.cfscript.CFFunctionExpression) CFLintScanException(com.cflint.exception.CFLintScanException) CFLintScanner(com.cflint.plugins.CFLintScanner) CFAssignmentExpression(cfml.parsing.cfscript.CFAssignmentExpression) CFIdentifier(cfml.parsing.cfscript.CFIdentifier) ParseException(cfml.parsing.reporting.ParseException) IOException(java.io.IOException) CFLintScanException(com.cflint.exception.CFLintScanException) CFScopes(com.cflint.plugins.core.CFScopes) CFArrayExpression(cfml.parsing.cfscript.CFArrayExpression) CFExpression(cfml.parsing.cfscript.CFExpression) ContextMessage(com.cflint.plugins.Context.ContextMessage) CFMember(cfml.parsing.cfscript.CFMember) CFVarDeclExpression(cfml.parsing.cfscript.CFVarDeclExpression) CFTernaryExpression(cfml.parsing.cfscript.CFTernaryExpression) CFFullVarExpression(cfml.parsing.cfscript.CFFullVarExpression)

Example 3 with CFLintScanException

use of com.cflint.exception.CFLintScanException in project CFLint by cflint.

the class CFLint method process.

public void process(final String src, final String filename) throws CFLintScanException {
    try {
        fireStartedProcessing(filename);
        lineOffsets = null;
        if (src == null || src.trim().length() == 0) {
            final Context context = new Context(filename, null, null, false, handler, configuration);
            reportRule(null, null, context, null, new ContextMessage(AVOID_EMPTY_FILES, null));
        } else {
            lineOffsets = getLineOffsets(src.split("\n"));
            final CFMLSource cfmlSource = new CFMLSource(src.contains("<!---") ? CommentReformatting.wrap(src) : src);
            final ParserTag firstTag = getFirstTagQuietly(cfmlSource);
            final List<Element> elements = new ArrayList<>();
            if (firstTag != null) {
                elements.addAll(cfmlSource.getChildElements());
            }
            if (isComponentOrInterfaceScript(src, elements)) {
                // Check if pure cfscript
                final CFScriptStatement scriptStatement = cfmlParser.parseScript(src);
                final Context context = new Context(filename, null, null, false, handler, scriptStatement == null ? null : scriptStatement.getTokens(), configuration);
                process(scriptStatement, context);
            } else {
                processStack(elements, " ", filename, null);
            }
        }
        fireFinishedProcessing(filename);
    } catch (final Exception e) {
        throw new CFLintScanException(e);
    }
}
Also used : Context(com.cflint.plugins.Context) ContextMessage(com.cflint.plugins.Context.ContextMessage) CFMLSource(cfml.parsing.CFMLSource) CFScriptStatement(cfml.parsing.cfscript.script.CFScriptStatement) CFLintScanException(com.cflint.exception.CFLintScanException) ParserTag(cfml.parsing.ParserTag) Element(net.htmlparser.jericho.Element) ArrayList(java.util.ArrayList) ParseException(cfml.parsing.reporting.ParseException) IOException(java.io.IOException) CFLintScanException(com.cflint.exception.CFLintScanException)

Example 4 with CFLintScanException

use of com.cflint.exception.CFLintScanException in project CFLint by cflint.

the class CFLint method process.

private void process(final Element elem, final String space, final Context context) throws CFLintScanException {
    if (skipToPosition > elem.getBegin()) {
        return;
    } else {
        skipToPosition = 0;
    }
    try {
        currentElement = elem;
        if (elem.getName().equalsIgnoreCase(CF.CFCOMPONENT)) {
            final Context componentContext = context.subContext(elem);
            componentContext.setInComponent(true);
            // elem.getAttributeValue(CF.DISPLAYNAME)
            componentContext.setComponentName(context.getFilename().replaceAll(".[cC][fF][cC]", "").replaceAll("^.*[/\\\\]", ""));
            componentContext.setContextType(ContextType.COMPONENT);
            handler.push(CF.COMPONENT);
            doStructureStart(elem, componentContext, CFCompDeclStatement.class);
        } else if (elem.getName().equalsIgnoreCase(CF.CFFUNCTION)) {
            final Context functionContext = context.subContext(elem);
            functionContext.setFunctionName(elem.getAttributeValue(CF.NAME));
            functionContext.setContextType(ContextType.FUNCTION);
            handler.push(CF.FUNCTION);
            doStructureStart(elem, functionContext, CFFuncDeclStatement.class);
        } else if (elem.getName().equalsIgnoreCase(CF.CFLOOP) && elem.getAttributeValue(CF.QUERY) != null) {
            // Give a cfloop for query its own context and set the column
            // names as variables if they are available
            final Context loopContext = context.subContext(elem);
            loopContext.setContextType(ContextType.QUERY_LOOP);
            handler.push(CF.CFLOOP);
            final String qryName = elem.getAttributeValue(CF.QUERY);
            handler.addVariables(handler.getQueryColumns(qryName));
            doStructureStart(elem, loopContext, CFFuncDeclStatement.class);
        }
        if (elem.getName().equalsIgnoreCase(CF.CFSET) || elem.getName().equalsIgnoreCase(CF.CFIF) || elem.getName().equalsIgnoreCase(CF.CFELSEIF) || elem.getName().equalsIgnoreCase(CF.CFRETURN)) {
            scanElement(elem, context);
            final Pattern p = Pattern.compile("<\\w+\\s(.*[^/])/?>", Pattern.MULTILINE | Pattern.DOTALL);
            final String expr = elem.getFirstStartTag().toString();
            final Matcher m = p.matcher(expr);
            if (m.matches()) {
                final String cfscript = m.group(1).trim();
                if (!cfscript.isEmpty()) {
                    try {
                        final CFExpression expression = cfmlParser.parseCFMLExpression(cfscript, this);
                        if (expression != null) {
                            process(expression, elem, context);
                        }
                    } catch (final Exception npe) {
                        printException(npe, elem);
                        final ContextMessage cm = new ContextMessage(PARSE_ERROR, null, null, context.startLine(), elem.getBegin());
                        reportRule(currentElement, null, context, null, cm);
                    }
                }
            }
            processStack(elem.getChildElements(), space + " ", context);
        } else if (elem.getName().equalsIgnoreCase(CF.CFARGUMENT) || elem.getName().equalsIgnoreCase(CF.CFDOCUMENTSECTION)) {
            scanElement(elem, context);
            final String name = elem.getAttributeValue(CF.NAME);
            if (name != null) {
                handler.addArgument(name);
            }
            processStack(elem.getChildElements(), space + " ", context);
        } else if (elem.getName().equalsIgnoreCase(CF.CFSCRIPT)) {
            scanElement(elem, context);
            String cfscript = elem.getContent().toString();
            if (elem.getEndTag() == null) {
                // Hack to fetch the entire cfscript text, if cfscript is a
                // word in the content somewhere, and causes
                // the jericho parser to fail
                EndTag nextTag = elem.getSource().getNextEndTag(elem.getBegin());
                while (nextTag != null && !nextTag.getName().equalsIgnoreCase(elem.getName())) {
                    nextTag = elem.getSource().getNextEndTag(nextTag.getEnd());
                }
                if (nextTag.getName().equalsIgnoreCase(elem.getName())) {
                    cfscript = elem.getSource().subSequence(elem.getStartTag().getEnd(), nextTag.getBegin()).toString();
                    skipToPosition = nextTag.getEnd();
                }
            }
            final CFScriptStatement scriptStatement;
            try {
                scriptStatement = cfmlParser.parseScript(cfscript);
            } catch (Exception e) {
                throw new CFLintScanException(e);
            }
            final Context subcontext = context.subContext(elem, scriptStatement == null ? null : scriptStatement.getTokens());
            process(scriptStatement, subcontext);
            processStack(elem.getChildElements(), space + " ", context);
        } else if (elem.getName().equalsIgnoreCase(CF.CFFUNCTION)) {
            final Context functionContext = context.subContext(elem);
            functionContext.setFunctionName(elem.getAttributeValue(CF.NAME));
            functionContext.setContextType(ContextType.FUNCTION);
            scanElement(elem, functionContext);
            processStack(elem.getChildElements(), space + " ", functionContext);
            // Process any messages added by downstream parsing.
            for (final ContextMessage message : functionContext.getMessages()) {
                reportRule(elem, null, functionContext, message.getSource(), message);
            }
            functionContext.getMessages().clear();
            for (final CFLintStructureListener structurePlugin : getStructureListeners(extensions)) {
                try {
                    structurePlugin.endFunction(functionContext, bugs);
                    for (final ContextMessage message : functionContext.getMessages()) {
                        reportRule(elem, null, functionContext, (CFLintScanner) structurePlugin, message);
                    }
                    functionContext.getMessages().clear();
                } catch (final Exception e) {
                    printException(e);
                    final ContextMessage cm = new ContextMessage(PARSE_ERROR, null, null, context.startLine());
                    reportRule(currentElement, null, context, null, cm);
                }
            }
            handler.pop();
        } else if (elem.getName().equalsIgnoreCase(CF.CFCOMPONENT)) {
            final Context componentContext = context.subContext(elem);
            componentContext.setInComponent(true);
            // elem.getAttributeValue(CF.DISPLAYNAME)
            componentContext.setComponentName(context.getFilename().replaceAll(".[cC][fF][cC]", "").replaceAll("^.*[/\\\\]", ""));
            componentContext.setContextType(ContextType.COMPONENT);
            scanElement(elem, componentContext);
            processStack(elem.getChildElements(), space + " ", componentContext);
            for (final CFLintStructureListener structurePlugin : getStructureListeners(extensions)) {
                try {
                    structurePlugin.endComponent(componentContext, bugs);
                    for (final ContextMessage message : componentContext.getMessages()) {
                        reportRule(elem, null, componentContext, (CFLintScanner) structurePlugin, message);
                    }
                    componentContext.getMessages().clear();
                } catch (final Exception e) {
                    printException(e);
                    final ContextMessage cm = new ContextMessage(PARSE_ERROR, null, null, context.startLine());
                    reportRule(currentElement, null, context, null, cm);
                }
            }
            handler.pop();
        } else if (elem.getName().equalsIgnoreCase(CF.CFQUERY)) {
            scanElement(elem, context);
            for (final Entry<String, CFExpression> expression : unpackTagExpressions(elem).entrySet()) {
                if (expression != null) {
                    process(expression.getValue(), elem, context);
                }
            }
            final List<Element> list = elem.getAllElements();
            processStack(list.subList(1, list.size()), space + " ", context);
            // Save any columns from the cfquery
            final String qryName = elem.getAttributeValue(CF.NAME);
            if (qryName != null && qryName.trim().length() > 0) {
                final String qryText = elem.getTextExtractor().toString().toUpperCase();
                final Matcher m = Pattern.compile(".*SELECT\\s(\\w+(\\s*,\\s*\\w+)+)\\s+FROM\\s+.*").matcher(qryText);
                final List<String> cols = new ArrayList<>();
                if (m.matches()) {
                    cols.addAll(Arrays.asList(m.group(1).trim().split("\\s*,\\s*")));
                    handler.addQueryColumnSet(qryName, cols);
                }
            }
        } else if (elem.getName().equalsIgnoreCase(CF.CFQUERYPARAM)) {
            scanElement(elem, context);
            for (final Entry<String, CFExpression> expression : unpackTagExpressions(elem).entrySet()) {
                if (expression != null) {
                    process(expression.getValue(), elem, context);
                }
            }
        } else if (elem.getName().equalsIgnoreCase(CF.CFINCLUDE)) {
            scanElement(elem, context);
            final String path = elem.getAttributeValue(CF.TEMPLATE);
            final File include = new File(new File(context.getFilename()).getParentFile(), path);
            if (strictInclude || include.exists()) {
                if (includeFileStack.contains(include)) {
                    if (!quiet) {
                        System.err.println("Terminated a recursive call to include file " + include);
                    }
                } else {
                    includeFileStack.push(include);
                    process(FileUtil.loadFile(include), context.getFilename());
                    includeFileStack.pop();
                }
            }
        } else if (elem.getName().equalsIgnoreCase(CF.CFLOOP) && elem.getAttributeValue(CF.QUERY) != null) {
            scanElement(elem, context);
            processStack(elem.getChildElements(), space + " ", context);
            handler.pop();
        } else if (elem.getName().equalsIgnoreCase(CF.CFCATCH)) {
            scanElement(elem, context);
            handler.push(CF.CFCATCH);
            if (elem.getAttributeValue("name") != null) {
                handler.addVariable(elem.getAttributeValue("name"));
            }
            processStack(elem.getChildElements(), space + " ", context);
            handler.pop();
        } else {
            scanElement(elem, context);
            for (final Entry<String, CFExpression> expression : unpackTagExpressions(elem).entrySet()) {
                if (expression != null) {
                    process(expression.getValue(), elem, tagInfo.isAssignmentAttribute(elem, expression.getKey()) ? context.subContextInAssignment() : context);
                }
            }
            processStack(elem.getChildElements(), space + " ", context);
        }
        // Process any messages added by downstream parsing.
        for (final ContextMessage message : context.getMessages()) {
            reportRule(elem, null, context, message.getSource(), message);
        }
        context.getMessages().clear();
    } catch (final NullPointerException npe) {
        printException(npe);
        final ContextMessage cm = new ContextMessage(PARSE_ERROR, null, null, context.startLine());
        reportRule(currentElement, null, context, null, cm);
    }
}
Also used : Context(com.cflint.plugins.Context) CFFuncDeclStatement(cfml.parsing.cfscript.script.CFFuncDeclStatement) Pattern(java.util.regex.Pattern) EndTag(net.htmlparser.jericho.EndTag) Matcher(java.util.regex.Matcher) CFLintScanException(com.cflint.exception.CFLintScanException) CFLintScanner(com.cflint.plugins.CFLintScanner) ParseException(cfml.parsing.reporting.ParseException) IOException(java.io.IOException) CFLintScanException(com.cflint.exception.CFLintScanException) CFExpression(cfml.parsing.cfscript.CFExpression) Entry(java.util.Map.Entry) ContextMessage(com.cflint.plugins.Context.ContextMessage) CFScriptStatement(cfml.parsing.cfscript.script.CFScriptStatement) List(java.util.List) ArrayList(java.util.ArrayList) File(java.io.File) CFLintStructureListener(com.cflint.plugins.CFLintStructureListener)

Example 5 with CFLintScanException

use of com.cflint.exception.CFLintScanException in project CFLint by cflint.

the class CFLintCLI method execute.

private void execute(final CFLintConfiguration cfLintConfig) throws IOException, TransformerException, MarshallerException, JAXBException, CFLintScanException, CFLintConfigurationException {
    final CFLintAPI api = new CFLintAPI(cfLintConfig);
    api.setVerbose(verbose);
    api.setLogError(logerror);
    api.setQuiet(quiet);
    api.setDebug(debug);
    api.setStrictInclude(strictInclude);
    api.setEnvironmentName(environmentName);
    if (extensions != null && extensions.trim().length() > 0) {
        try {
            api.setExtensions(Arrays.asList(extensions.trim().split(",")));
        } catch (final Exception e) {
            if (!quiet) {
                System.err.println("Unable to use extensions (" + extensions + "), using default instead. " + e.getMessage());
            }
        }
    }
    api.setFilterFile(filterFile);
    CFLintResult lintResult = null;
    if (stdIn) {
        final StringWriter source = new StringWriter();
        IOUtils.copy(new InputStreamReader(System.in), source);
        lintResult = api.scan(source.toString(), stdInFile);
    } else {
        lintResult = api.scan(folder);
    }
    if (xmlOutput) {
        try (final Writer xmlwriter = stdOut ? new OutputStreamWriter(System.out) : createXMLWriter(xmlOutFile, StandardCharsets.UTF_8)) {
            if (FINDBUGS.equalsIgnoreCase(xmlstyle)) {
                if (verbose) {
                    display("Writing XML (style: findbugs)" + (stdOut ? "." : " to " + xmlOutFile));
                }
                lintResult.writeFindBugsXml(xmlwriter);
            } else {
                if (verbose) {
                    display("Writing XML" + (stdOut ? "." : " to " + xmlOutFile));
                }
                lintResult.writeXml(xmlwriter);
            }
        }
    }
    if (textOutput) {
        try (final Writer textwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(textOutFile)) {
            if (verbose) {
                display("Writing text" + (stdOut ? "." : " to " + textOutFile));
            }
            lintResult.writeText(textwriter);
        }
    }
    if (htmlOutput) {
        try (final Writer htmlwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(htmlOutFile)) {
            if (verbose) {
                display("Writing HTML (style: " + htmlStyle + ")" + (stdOut ? "." : " to " + htmlOutFile));
            }
            lintResult.writeHTML(htmlStyle, htmlwriter);
        }
    }
    if (jsonOutput) {
        try (final Writer jsonwriter = stdOut ? new OutputStreamWriter(System.out) : new FileWriter(jsonOutFile)) {
            if (verbose) {
                display("Writing JSON" + (stdOut ? "." : " to " + jsonOutFile));
            }
            lintResult.writeJSON(jsonwriter);
        }
    }
    if (verbose) {
        display("Total files scanned: " + lintResult.getStats().getFileCount());
        display("Total LOC scanned: " + lintResult.getStats().getTotalLines());
    }
}
Also used : CFLintAPI(com.cflint.api.CFLintAPI) StringWriter(java.io.StringWriter) InputStreamReader(java.io.InputStreamReader) FileWriter(java.io.FileWriter) OutputStreamWriter(java.io.OutputStreamWriter) TransformerException(javax.xml.transform.TransformerException) CFLintConfigurationException(com.cflint.exception.CFLintConfigurationException) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) CFLintScanException(com.cflint.exception.CFLintScanException) MarshallerException(com.cflint.xml.MarshallerException) CFLintResult(com.cflint.api.CFLintResult) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter) StringWriter(java.io.StringWriter) FileWriter(java.io.FileWriter) Writer(java.io.Writer)

Aggregations

CFLintScanException (com.cflint.exception.CFLintScanException)5 IOException (java.io.IOException)5 ParseException (cfml.parsing.reporting.ParseException)4 Context (com.cflint.plugins.Context)4 ContextMessage (com.cflint.plugins.Context.ContextMessage)4 CFExpression (cfml.parsing.cfscript.CFExpression)3 CFScriptStatement (cfml.parsing.cfscript.script.CFScriptStatement)3 CFLintScanner (com.cflint.plugins.CFLintScanner)3 CFMLSource (cfml.parsing.CFMLSource)2 CFIdentifier (cfml.parsing.cfscript.CFIdentifier)2 CFFuncDeclStatement (cfml.parsing.cfscript.script.CFFuncDeclStatement)2 CFLintStructureListener (com.cflint.plugins.CFLintStructureListener)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 ParserTag (cfml.parsing.ParserTag)1 CFArrayExpression (cfml.parsing.cfscript.CFArrayExpression)1 CFAssignmentExpression (cfml.parsing.cfscript.CFAssignmentExpression)1 CFFullVarExpression (cfml.parsing.cfscript.CFFullVarExpression)1 CFFunctionExpression (cfml.parsing.cfscript.CFFunctionExpression)1 CFLiteral (cfml.parsing.cfscript.CFLiteral)1