Create scanner for language

@param language for sensor
@param conf settings for sensor
@param visitors visitors AST checks and visitors to use
@return scanner for the given parameters
346449
@SafeVarargs
  public static AstScanner<Grammar> create(CxxLanguage language, CxxConfiguration conf,
    SquidAstVisitor<Grammar>... visitors) {
    final SquidAstVisitorContextImpl<Grammar> context
      = new SquidAstVisitorContextImpl<>(new SourceProject("Cxx Project"));
    final Parser<Grammar> parser = CxxParser.create(context, conf, language);

    AstScanner.Builder<Grammar> builder = AstScanner.<Grammar>builder(context).setBaseParser(parser);

    /* Metrics */
    builder.withMetrics(CxxMetric.values());

    /* Files */
    builder.setFilesMetric(CxxMetric.FILES);

    /* Comments */
    builder.setCommentAnalyser(
      new CommentAnalyser() {
      @Override
      public boolean isBlank(String line) {
        for (int i = 0; i < line.length(); i++) {
          if (Character.isLetterOrDigit(line.charAt(i))) {
            return false;
          }
        }
        return true;
      }

      @Override
      public String getContents(String comment) {
        final int HEADER_LEN = 2;
        return "/*".equals(comment.substring(0, HEADER_LEN))
          ? comment.substring(HEADER_LEN, comment.length() - HEADER_LEN)
          : comment.substring(HEADER_LEN);
      }
    });

    /* Functions */
    builder.withSquidAstVisitor(new SourceCodeBuilderVisitor<>((SourceCode parentSourceCode, AstNode astNode) -> {
      StringBuilder sb = new StringBuilder(512);
      for (Token token : astNode.getFirstDescendant(CxxGrammarImpl.declaratorId).getTokens()) {
        sb.append(token.getValue());
      }
      String functionName = sb.toString();
      sb.setLength(0);
      // todo: check if working with nested-namespace-definition
      AstNode namespace = astNode.getFirstAncestor(CxxGrammarImpl.namedNamespaceDefinition);
      while (namespace != null) {
        if (sb.length() > 0) {
          sb.insert(0, "::");
        }
        sb.insert(0, namespace.getFirstDescendant(GenericTokenType.IDENTIFIER).getTokenValue());
        // todo: check if working with nested-namespace-definition
        namespace = namespace.getFirstAncestor(CxxGrammarImpl.namedNamespaceDefinition);
      }
      String namespaceName = sb.length() > 0 ? sb.toString() + "::" : "";
      SourceFunction function = new SourceFunction(intersectingConcatenate(namespaceName, functionName)
        + ":" + astNode.getToken().getLine());
      function.setStartAtLine(astNode.getTokenLine());
      return function;
    }, CxxGrammarImpl.functionDefinition));

    builder.withSquidAstVisitor(CounterVisitor.<Grammar>builder()
      .setMetricDef(CxxMetric.FUNCTIONS)
      .subscribeTo(CxxGrammarImpl.functionDefinition)
      .build());

    /* Classes */
    builder.withSquidAstVisitor(new SourceCodeBuilderVisitor<>((SourceCode parentSourceCode, AstNode astNode) -> {
      AstNode classNameAst = astNode.getFirstDescendant(CxxGrammarImpl.className);
      String className = classNameAst == null ? "" : classNameAst.getFirstChild().getTokenValue();
      SourceClass cls = new SourceClass(className + ":" + astNode.getToken().getLine(), className);
      cls.setStartAtLine(astNode.getTokenLine());
      return cls;
    }, CxxGrammarImpl.classSpecifier));

    builder.withSquidAstVisitor(CounterVisitor.<Grammar>builder()
      .setMetricDef(CxxMetric.CLASSES)
      .subscribeTo(CxxGrammarImpl.classSpecifier)
      .build());

    /* Metrics */
    builder.withSquidAstVisitor(new LinesVisitor<>(CxxMetric.LINES));
    builder.withSquidAstVisitor(new CxxLinesOfCodeVisitor<>(CxxMetric.LINES_OF_CODE));
    builder.withSquidAstVisitor(new CxxLinesOfCodeInFunctionBodyVisitor<>());
    builder.withSquidAstVisitor(new CxxPublicApiVisitor<>(language));

    builder.withSquidAstVisitor(CommentsVisitor.<Grammar>builder().withCommentMetric(CxxMetric.COMMENT_LINES)
      .withNoSonar(true)
      .withIgnoreHeaderComment(conf.getIgnoreHeaderComments())
      .build());

    /* Statements */
    builder.withSquidAstVisitor(CounterVisitor.<Grammar>builder()
      .setMetricDef(CxxMetric.STATEMENTS)
      .subscribeTo(CxxGrammarImpl.statement)
      .build());

    builder.withSquidAstVisitor(new CxxCyclomaticComplexityVisitor<Grammar>(ComplexityVisitor.<Grammar>builder()
      .setMetricDef(CxxMetric.COMPLEXITY)
      .subscribeTo(CxxComplexityConstants.getCyclomaticComplexityTypes())
      .build()));

    builder.withSquidAstVisitor(new CxxCognitiveComplexityVisitor<>());

    builder.withSquidAstVisitor(new CxxFunctionComplexityVisitor<>(language));
    builder.withSquidAstVisitor(new CxxFunctionSizeVisitor<>(language));

    // to emit a 'new file' event to the internals of the plugin
    builder.withSquidAstVisitor(new CxxFileVisitor<>());

    // log syntax errors
    builder.withSquidAstVisitor(new CxxParseErrorLoggerVisitor<>());

    /* External visitors (typically Check ones) */
    for (SquidAstVisitor<Grammar> visitor : visitors) {
      if (visitor instanceof CxxCharsetAwareVisitor) {
        ((CxxCharsetAwareVisitor) visitor).setCharset(conf.getCharset());
      }
      builder.withSquidAstVisitor(visitor);
    }

    return builder.build();
  }
17628
public static MethodAnnotation fromVisitedMethod(PreorderVisitor visitor) {
        String className = visitor.getDottedClassName();
        MethodAnnotation result = new MethodAnnotation(className, visitor.getMethodName(), visitor.getMethodSig(), visitor
                .getMethod().isStatic());

        // Try to find the source lines for the method
        SourceLineAnnotation srcLines = SourceLineAnnotation.fromVisitedMethod(visitor);
        result.setSourceLines(srcLines);

        return result;
    }
898661
public org.teatrove.tea.compiler.Scanner createScanner(SourceReader sr, CompilationUnit unit)
    throws IOException {
        org.teatrove.tea.compiler.Scanner scanner = super.createScanner(sr, unit);
        CompileListener scannerListener = getScannerListener();
        if (scannerListener != null) {
            scanner.addCompileListener(scannerListener);
        }
        return scanner;
    }
151796
@Override
	public String toUriString() {
		StringBuilder uriBuilder = new StringBuilder();
		if (getScheme() != null) {
			uriBuilder.append(getScheme());
			uriBuilder.append(':');
		}
		if (this.userInfo != null || this.host != null) {
			uriBuilder.append("//");
			if (this.userInfo != null) {
				uriBuilder.append(this.userInfo);
				uriBuilder.append('@');
			}
			if (this.host != null) {
				uriBuilder.append(host);
			}
			if (getPort() != -1) {
				uriBuilder.append(':');
				uriBuilder.append(port);
			}
		}
		String path = getPath();
		if (StringUtils.hasLength(path)) {
			if (uriBuilder.length() != 0 && path.charAt(0) != PATH_DELIMITER) {
				uriBuilder.append(PATH_DELIMITER);
			}
			uriBuilder.append(path);
		}
		String query = getQuery();
		if (query != null) {
			uriBuilder.append('?');
			uriBuilder.append(query);
		}
		if (getFragment() != null) {
			uriBuilder.append('#');
			uriBuilder.append(getFragment());
		}
		return uriBuilder.toString();
	}
347
public final String apply(String input, Language inputLanguage) {
    if (input != null && Config.get(this.getClass(), inputLanguage, "apply").asBoolean(true)) {
      return performNormalization(input, inputLanguage);
    }
    return input;
  }
1149240
@Override
	public void accept(Visitor<OptimizerNode> visitor) {
		if (visitor.preVisit(this)) {
			if (getPredecessorNode() != null) {
				getPredecessorNode().accept(visitor);
			} else {
				throw new CompilerException();
			}
			visitor.postVisit(this);
		}
	}
411867
public final void setLang(final Languages pLang) {
    this.lang = pLang;
    if (this.itsId == null) {
      this.itsId = new IdLangPreferences();
    }
    this.itsId.setLang(this.lang);
  }
766347
public boolean supportsLanguage(Language language) {
    try {
      List<Class<? extends Rule>> relevantRuleClasses = new ArrayList<>();
      UserConfig config = new UserConfig();
      List<Rule> relevantRules = new ArrayList<>(language.getRelevantRules(JLanguageTool.getMessageBundle(),
          config, null, Collections.emptyList()));  //  empty UserConfig has to be added to prevent null pointer exception
      relevantRules.addAll(language.getRelevantLanguageModelCapableRules(JLanguageTool.getMessageBundle(), null,
        config, null, Collections.emptyList()));
      for (Rule relevantRule : relevantRules) {
        relevantRuleClasses.add(relevantRule.getClass());
      }
      return relevantRuleClasses.contains(this.getClass());
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
973202
@Override
    public AnnotationVisitor visitAnnotation(String targetMethodName, String annotationClassDescription) {
        if (tc.isDebugEnabled()) {
            Tr.debug(tc, MessageFormat.format("visitAnnotation [ {0} ] Annotation Class [ {1} ] Description [ 2 ]",
                                              getHashText(), targetMethodName, annotationClassDescription));
        }

        Type annotationType = Type.getType(annotationClassDescription);
        String annotationClassName = annotationType.getClassName();

        AnnotationInfoImpl newAnnotationInfo = new AnnotationInfoImpl(annotationClassName, infoStore);

        AnnotationValueImpl newAnnotationValue = new AnnotationValueImpl(newAnnotationInfo);

        storeAnnotationValue(targetMethodName, newAnnotationValue);

        return new InfoVisitor_Annotation.AnnotationInfoVisitor(newAnnotationInfo);
    }
325580
public void setLanguage(String language) {
	if (StringUtil.isEmpty(language)) return;
	this.language = Collection.validateLanguage(language);
    }
617139
public static void visit(Object instance, TypeToken<?> inspectType, Visitor firstVisitor, Visitor... moreVisitors) {

    try {
      List<Visitor> visitors = ImmutableList.<Visitor>builder().add(firstVisitor).add(moreVisitors).build();

      for (TypeToken<?> type : inspectType.getTypes().classes()) {
        if (Object.class.equals(type.getRawType())) {
          break;
        }

        for (Field field : type.getRawType().getDeclaredFields()) {
          if (!field.isAccessible()) {
            field.setAccessible(true);
          }
          for (Visitor visitor : visitors) {
            visitor.visit(instance, inspectType, type, field);
          }
        }

        for (Method method : type.getRawType().getDeclaredMethods()) {
          if (!method.isAccessible()) {
            method.setAccessible(true);
          }
          for (Visitor visitor : visitors) {
            visitor.visit(instance, inspectType, type, method);
          }
        }
      }
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }
639366
public <T> InjectorBuilder forEachElement(ElementVisitor<T> visitor) {
        Elements
            .getElements(module)
            .forEach(element -> element.acceptVisitor(visitor));
        return this;
    }
935556
public static Map<CxxMetricsFactory.Key, Metric<?>> generateMap(String langKey, String langPropertiesKey) {
    final String domain = langKey.toUpperCase(Locale.ENGLISH);

    final Map<CxxMetricsFactory.Key, Metric<?>> metrics = new HashMap<>();

    addPublicAPIMetrics(langPropertiesKey, domain, metrics);

    addSensorMetric(Key.CLANG_SA_SENSOR_ISSUES_KEY, "ClangSA issues", domain, langPropertiesKey, metrics);
    addSensorMetric(Key.CLANG_TIDY_SENSOR_ISSUES_KEY, "ClangTidy issues", domain, langPropertiesKey, metrics);
    addSensorMetric(Key.VC_SENSOR_ISSUES_KEY, "VC compiler issues", domain, langPropertiesKey, metrics);
    addSensorMetric(Key.GCC_SENSOR_ISSUES_KEY, "GCC compiler issues", domain, langPropertiesKey, metrics);
    addSensorMetric(Key.CPPCHECK_SENSOR_ISSUES_KEY, "CppCheck issues", domain, langPropertiesKey, metrics);
    addSensorMetric(Key.DRMEMORY_SENSOR_ISSUES_KEY, "DrMemory issues", domain, langPropertiesKey, metrics);
    addSensorMetric(Key.OTHER_SENSOR_ISSUES_KEY, "Other tools issues", domain, langPropertiesKey, metrics);
    addSensorMetric(Key.PCLINT_SENSOR_ISSUES_KEY, "PC-Lint issues", domain, langPropertiesKey, metrics);
    addSensorMetric(Key.RATS_SENSOR_ISSUES_KEY, "Rats issues", domain, langPropertiesKey, metrics);
    addSensorMetric(Key.SQUID_SENSOR_ISSUES_KEY, "Squid issues", domain, langPropertiesKey, metrics);
    addSensorMetric(Key.VALGRIND_SENSOR_KEY, "Valgrind issues", domain, langPropertiesKey, metrics);
    addSensorMetric(Key.VERAXX_SENSOR_KEY, "Vera issues", domain, langPropertiesKey, metrics);

    addFunctionComplexityMetrics(langPropertiesKey, metrics);
    addFunctonSizeMetrics(langPropertiesKey, metrics);

    return metrics;
  }
134324
public static void walk(final Type one, final Type two, final TypesVisitor visitor) {
        // Use possibly more specific generics (otherwise root class generics would be used as Object and this
        // way it could be used as upper bound)
        // Also, types could contain outer class generics declarations, which must be preserved
        // e.g. (Outer<String>.Inner field).getGenericType() == ParameterizedType with parametrized owner
        // Wrapped into ignore map for very specific case, when type is TypeVariable
        final Map<String, Type> oneKnownGenerics =
                new IgnoreGenericsMap(GenericsResolutionUtils.resolveGenerics(one, IGNORE_VARS));
        final Map<String, Type> twoKnownGenerics =
                new IgnoreGenericsMap(GenericsResolutionUtils.resolveGenerics(two, IGNORE_VARS));
        // Resolve variables mainly to simplify empty wildcards (? extends Object and ? super Object) to Object
        // Still have to pass map because of possibly declared outer class generics. Note that for all
        // types operations ignoring map could be used as we already replaced all variables. These generics
        // are required only for type context building (on some level to resolve comparable type)
        doWalk(GenericsUtils.resolveTypeVariables(one, oneKnownGenerics), oneKnownGenerics,
                GenericsUtils.resolveTypeVariables(two, twoKnownGenerics), twoKnownGenerics, visitor);
    }
1310399
@Nonnull
    public BugInstance addClassAndMethod(PreorderVisitor visitor) {
        addClass(visitor);
        XMethod m = visitor.getXMethod();
        addMethod(visitor);
        if (!MemberUtils.isUserGenerated(m)) {
            foundInAutogeneratedMethod();
        }
        return this;
    }
971434
public void traverse(JavacASTVisitor visitor) {
		switch (this.getKind()) {
		case COMPILATION_UNIT:
			visitor.visitCompilationUnit(this, (JCCompilationUnit) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitCompilationUnit(this, (JCCompilationUnit) get());
			break;
		case TYPE:
			visitor.visitType(this, (JCClassDecl) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitType(this, (JCClassDecl) get());
			break;
		case FIELD:
			visitor.visitField(this, (JCVariableDecl) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitField(this, (JCVariableDecl) get());
			break;
		case METHOD:
			visitor.visitMethod(this, (JCMethodDecl) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitMethod(this, (JCMethodDecl) get());
			break;
		case INITIALIZER:
			visitor.visitInitializer(this, (JCBlock) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitInitializer(this, (JCBlock) get());
			break;
		case ARGUMENT:
			JCMethodDecl parentMethod = (JCMethodDecl) up().get();
			visitor.visitMethodArgument(this, (JCVariableDecl) get(), parentMethod);
			ast.traverseChildren(visitor, this);
			visitor.endVisitMethodArgument(this, (JCVariableDecl) get(), parentMethod);
			break;
		case LOCAL:
			visitor.visitLocal(this, (JCVariableDecl) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitLocal(this, (JCVariableDecl) get());
			break;
		case STATEMENT:
			visitor.visitStatement(this, get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitStatement(this, get());
			break;
		case ANNOTATION:
			switch (up().getKind()) {
			case TYPE:
				visitor.visitAnnotationOnType((JCClassDecl) up().get(), this, (JCAnnotation) get());
				break;
			case FIELD:
				visitor.visitAnnotationOnField((JCVariableDecl) up().get(), this, (JCAnnotation) get());
				break;
			case METHOD:
				visitor.visitAnnotationOnMethod((JCMethodDecl) up().get(), this, (JCAnnotation) get());
				break;
			case ARGUMENT:
				JCVariableDecl argument = (JCVariableDecl) up().get();
				JCMethodDecl method = (JCMethodDecl) up().up().get();
				visitor.visitAnnotationOnMethodArgument(argument, method, this, (JCAnnotation) get());
				break;
			case LOCAL:
				visitor.visitAnnotationOnLocal((JCVariableDecl) up().get(), this, (JCAnnotation) get());
				break;
			case TYPE_USE:
				visitor.visitAnnotationOnTypeUse(up().get(), this, (JCAnnotation) get());
				break;
			default:
				throw new AssertionError("Annotion not expected as child of a " + up().getKind());
			}
			break;
		case TYPE_USE:
			visitor.visitTypeUse(this, get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitTypeUse(this, get());
			break;
		default:
			throw new AssertionError("Unexpected kind during node traversal: " + getKind());
		}
	}
14740
protected function visitorSetDebugSettings($visitors_category_id)
	{
	    $GLOBALS['visitors']['debug']['tag']          = false; 
	    $GLOBALS['visitors']['debug']['checks']       = false;
	    $GLOBALS['visitors']['debug']['referrer']     = false;
	    $GLOBALS['visitors']['debug']['searchengine'] = false;
	    
	    $objVisitors = \Database::getInstance()
                ->prepare("SELECT
                                visitors_expert_debug_tag,
                                visitors_expert_debug_checks,
                                visitors_expert_debug_referrer,
                                visitors_expert_debug_searchengine
                            FROM
                                tl_visitors
                            LEFT JOIN
                                tl_visitors_category ON (tl_visitors_category.id=tl_visitors.pid)
                            WHERE
                                pid=? AND published=?
                            ORDER BY tl_visitors.id, visitors_name")
                ->limit(1)
                ->execute($visitors_category_id,1);
	    while ($objVisitors->next())
	    {
	        $GLOBALS['visitors']['debug']['tag']          = (boolean)$objVisitors->visitors_expert_debug_tag;
	        $GLOBALS['visitors']['debug']['checks']       = (boolean)$objVisitors->visitors_expert_debug_checks;
	        $GLOBALS['visitors']['debug']['referrer']     = (boolean)$objVisitors->visitors_expert_debug_referrer;
	        $GLOBALS['visitors']['debug']['searchengine'] = (boolean)$objVisitors->visitors_expert_debug_searchengine;
	        ModuleVisitorLog::writeLog('## START ##', '## DEBUG ##', 'T'.(int)$GLOBALS['visitors']['debug']['tag'] .'#C'. (int)$GLOBALS['visitors']['debug']['checks'] .'#R'.(int) $GLOBALS['visitors']['debug']['referrer'] .'#S'.(int)$GLOBALS['visitors']['debug']['searchengine']);
	    }
	}