同步操作将从 Gitee 极速下载/Cppcheck 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
"""cppcheckdataThis is a Python module that helps you access Cppcheck dump data.License: No restrictions, use this as you need."""import argparseimport jsonimport sysfrom xml.etree import ElementTreefrom fnmatch import fnmatchclass Directive:"""Directive class. Contains information about each preprocessor directive in the source code.Attributes:str The directive line, with all C or C++ comments removedfile Name of (possibly included) file where directive is definedlinenr Line number in (possibly included) file where directive is definedTo iterate through all directives use such code:@codedata = cppcheckdata.parsedump(...)for cfg in data.configurations:for directive in cfg.directives:print(directive.str)@endcode"""str = Nonefile = Nonelinenr = Nonecolumn = 0def __init__(self, element):self.str = element.get('str')self.file = element.get('file')self.linenr = int(element.get('linenr'))def __repr__(self):attrs = ["str", "file", "linenr"]return "{}({})".format("Directive",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))class ValueType:"""ValueType class. Contains (promoted) type information for each node in the AST."""type = Nonesign = Nonebits = 0constness = 0pointer = 0typeScopeId = NonetypeScope = NoneoriginalTypeName = Nonedef __init__(self, element):self.type = element.get('valueType-type')self.sign = element.get('valueType-sign')bits = element.get('valueType-bits')if bits:self.bits = int(bits)self.typeScopeId = element.get('valueType-typeScope')self.originalTypeName = element.get('valueType-originalTypeName')constness = element.get('valueType-constness')if constness:self.constness = int(constness)else:self.constness = 0pointer = element.get('valueType-pointer')if pointer:self.pointer = int(pointer)else:self.pointer = 0def __repr__(self):attrs = ["type", "sign", "bits", "typeScopeId", "originalTypeName","constness", "constness", "pointer"]return "{}({})".format("ValueType",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))def setId(self, IdMap):self.typeScope = IdMap[self.typeScopeId]def isIntegral(self):return self.type in {'bool', 'char', 'short', 'int', 'long', 'long long'}def isFloat(self):return self.type in {'float', 'double', 'long double'}def isEnum(self):return self.typeScope and self.typeScope.type == "Enum"class Token:"""Token class. Contains information about each token in the source code.The CppcheckData.tokenlist is a list of Token itemsC++ class: http://cppcheck.net/devinfo/doxyoutput/classToken.htmlAttributes:str Token stringnext Next token in tokenlist. For last token, next is None.previous Previous token in tokenlist. For first token, previous is None.link Linked token in tokenlist. Each '(', '[' and '{' are linked to thecorresponding '}', ']' and ')'. For templates, the '<' is linked tothe corresponding '>'.scope Scope information for this token. See the Scope class.isName Is this token a symbol nameisNumber Is this token a number, for example 123, 12.34isInt Is this token a int value such as 1234isFloat Is this token a int value such as 12.34isString Is this token a string literal such as "hello"strlen string length for string literalisChar Is this token a char literal such as 'x'isOp Is this token a operatorisArithmeticalOp Is this token a arithmetic operatorisAssignmentOp Is this token a assignment operatorisComparisonOp Is this token a comparison operatorisLogicalOp Is this token a logical operator: && ||isUnsigned Is this token a unsigned typeisSigned Is this token a signed typeisExpandedMacro Is this token a expanded macro tokenvarId varId for token, each variable has a unique non-zero idvariable Variable information for this token. See the Variable class.function If this token points at a function call, this attribute has the Functioninformation. See the Function class.values Possible values of tokenvalueType type informationtypeScope type scope (token->type()->classScope)astParent ast parentastOperand1 ast operand1astOperand2 ast operand2file file namelinenr line numbercolumn columnTo iterate through all tokens use such code:@codedata = cppcheckdata.parsedump(...)for cfg in data.configurations:code = ''for token in cfg.tokenlist:code = code + token.str + ' 'print(code)@endcode"""Id = Nonestr = Nonenext = Noneprevious = NonelinkId = Nonelink = NonescopeId = Nonescope = NoneisName = FalseisNumber = FalseisInt = FalseisFloat = FalseisString = Falsestrlen = NoneisChar = FalseisOp = FalseisArithmeticalOp = FalseisAssignmentOp = FalseisComparisonOp = FalseisLogicalOp = FalseisUnsigned = FalseisSigned = FalseisExpandedMacro = FalsevarId = NonevariableId = Nonevariable = NonefunctionId = Nonefunction = NonevaluesId = Nonevalues = NonevalueType = NonetypeScopeId = NonetypeScope = NoneastParentId = NoneastParent = NoneastOperand1Id = NoneastOperand1 = NoneastOperand2Id = NoneastOperand2 = Nonefile = Nonelinenr = Nonecolumn = Nonedef __init__(self, element):self.Id = element.get('id')self.str = element.get('str')self.next = Noneself.previous = Noneself.scopeId = element.get('scope')self.scope = Nonetype = element.get('type')if type == 'name':self.isName = Trueif element.get('isUnsigned'):self.isUnsigned = Trueif element.get('isSigned'):self.isSigned = Trueelif type == 'number':self.isNumber = Trueif element.get('isInt'):self.isInt = Trueelif element.get('isFloat'):self.isFloat = Trueelif type == 'string':self.isString = Trueself.strlen = int(element.get('strlen'))elif type == 'char':self.isChar = Trueelif type == 'op':self.isOp = Trueif element.get('isArithmeticalOp'):self.isArithmeticalOp = Trueelif element.get('isAssignmentOp'):self.isAssignmentOp = Trueelif element.get('isComparisonOp'):self.isComparisonOp = Trueelif element.get('isLogicalOp'):self.isLogicalOp = Trueif element.get('isExpandedMacro'):self.isExpandedMacro = Trueself.linkId = element.get('link')self.link = Noneif element.get('varId'):self.varId = int(element.get('varId'))self.variableId = element.get('variable')self.variable = Noneself.functionId = element.get('function')self.function = Noneself.valuesId = element.get('values')self.values = Noneif element.get('valueType-type'):self.valueType = ValueType(element)else:self.valueType = Noneself.typeScopeId = element.get('type-scope')self.typeScope = Noneself.astParentId = element.get('astParent')self.astParent = Noneself.astOperand1Id = element.get('astOperand1')self.astOperand1 = Noneself.astOperand2Id = element.get('astOperand2')self.astOperand2 = Noneself.file = element.get('file')self.linenr = int(element.get('linenr'))self.column = int(element.get('column'))def __repr__(self):attrs = ["Id", "str", "scopeId", "isName", "isUnsigned", "isSigned","isNumber", "isInt", "isFloat", "isString", "strlen","isChar", "isOp", "isArithmeticalOp", "isComparisonOp","isLogicalOp", "isExpandedMacro", "linkId", "varId","variableId", "functionId", "valuesId", "valueType","typeScopeId", "astParentId", "astOperand1Id", "file","linenr", "column"]return "{}({})".format("Token",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))def setId(self, IdMap):self.scope = IdMap[self.scopeId]self.link = IdMap[self.linkId]self.variable = IdMap[self.variableId]self.function = IdMap[self.functionId]self.values = IdMap[self.valuesId]self.typeScope = IdMap[self.typeScopeId]self.astParent = IdMap[self.astParentId]self.astOperand1 = IdMap[self.astOperand1Id]self.astOperand2 = IdMap[self.astOperand2Id]if self.valueType:self.valueType.setId(IdMap)def getValue(self, v):"""Get value if it existsReturns None if it doesn't exist"""if not self.values:return Nonefor value in self.values:if value.intvalue == v:return valuereturn Noneclass Scope:"""Scope. Information about global scope, function scopes, class scopes, inner scopes, etc.C++ class: http://cppcheck.net/devinfo/doxyoutput/classScope.htmlAttributesbodyStart The { Token for this scopebodyEnd The } Token for this scopeclassName Name of this scope.For a function scope, this is the function name;For a class scope, this is the class name.function If this scope belongs at a function call, this attributehas the Function information. See the Function class.type Type of scope: Global, Function, Class, If, While"""Id = NonebodyStartId = NonebodyStart = NonebodyEndId = NonebodyEnd = NoneclassName = NonefunctionId = Nonefunction = NonenestedInId = NonenestedIn = Nonetype = NoneisExecutable = Nonedef __init__(self, element):self.Id = element.get('id')self.className = element.get('className')self.functionId = element.get('function')self.function = Noneself.bodyStartId = element.get('bodyStart')self.bodyStart = Noneself.bodyEndId = element.get('bodyEnd')self.bodyEnd = Noneself.nestedInId = element.get('nestedIn')self.nestedIn = Noneself.type = element.get('type')self.isExecutable = (self.type in ('Function', 'If', 'Else', 'For', 'While', 'Do','Switch', 'Try', 'Catch', 'Unconditional', 'Lambda'))def __repr__(self):attrs = ["Id", "className", "functionId", "bodyStartId", "bodyEndId","nestedInId", "nestedIn", "type", "isExecutable"]return "{}({})".format("Scope",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))def setId(self, IdMap):self.bodyStart = IdMap[self.bodyStartId]self.bodyEnd = IdMap[self.bodyEndId]self.nestedIn = IdMap[self.nestedInId]self.function = IdMap[self.functionId]class Function:"""Information about a functionC++ class:http://cppcheck.net/devinfo/doxyoutput/classFunction.htmlAttributesargument Argument listtokenDef Token in function definitionisVirtual Is this function is virtualisImplicitlyVirtual Is this function is virtual this in the base classesisStatic Is this function is static"""Id = Noneargument = NoneargumentId = NonetokenDef = NonetokenDefId = Nonename = Nonetype = NoneisVirtual = NoneisImplicitlyVirtual = NoneisStatic = NonenestedIn = Nonedef __init__(self, element, nestedIn):self.Id = element.get('id')self.tokenDefId = element.get('tokenDef')self.name = element.get('name')self.type = element.get('type')isVirtual = element.get('isVirtual')self.isVirtual = (isVirtual and isVirtual == 'true')isImplicitlyVirtual = element.get('isImplicitlyVirtual')self.isImplicitlyVirtual = (isImplicitlyVirtual and isImplicitlyVirtual == 'true')isStatic = element.get('isStatic')self.isStatic = (isStatic and isStatic == 'true')self.nestedIn = nestedInself.argument = {}self.argumentId = {}def __repr__(self):attrs = ["Id", "tokenDefId", "name", "type", "isVirtual","isImplicitlyVirtual", "isStatic", "argumentId"]return "{}({})".format("Function",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))def setId(self, IdMap):for argnr, argid in self.argumentId.items():self.argument[argnr] = IdMap[argid]self.tokenDef = IdMap[self.tokenDefId]class Variable:"""Information about a variableC++ class:http://cppcheck.net/devinfo/doxyoutput/classVariable.htmlAttributes:nameToken Name token in variable declarationtypeStartToken Start token of variable declarationtypeEndToken End token of variable declarationaccess Global/Local/Namespace/Public/Protected/Public/Throw/Argumentscope Variable scopeisArgument Is this variable a function argument?isArray Is this variable an array?isClass Is this variable a class or struct?isConst Is this variable a const variable?isGlobal Is this variable a global variable?isExtern Is this variable an extern variable?isLocal Is this variable a local variable?isPointer Is this variable a pointerisReference Is this variable a referenceisStatic Is this variable static?constness Variable constness (same encoding as ValueType::constness)"""Id = NonenameTokenId = NonenameToken = NonetypeStartTokenId = NonetypeStartToken = NonetypeEndTokenId = NonetypeEndToken = Noneaccess = NonescopeId = Nonescope = NoneisArgument = FalseisArray = FalseisClass = FalseisConst = FalseisExtern = FalseisGlobal = FalseisLocal = FalseisPointer = FalseisReference = FalseisStatic = Falseconstness = 0def __init__(self, element):self.Id = element.get('id')self.nameTokenId = element.get('nameToken')self.nameToken = Noneself.typeStartTokenId = element.get('typeStartToken')self.typeStartToken = Noneself.typeEndTokenId = element.get('typeEndToken')self.typeEndToken = Noneself.access = element.get('access')self.scopeId = element.get('scope')self.scope = Noneself.isArgument = element.get('isArgument') == 'true'self.isArray = element.get('isArray') == 'true'self.isClass = element.get('isClass') == 'true'self.isConst = element.get('isConst') == 'true'self.isGlobal = element.get('access') == 'Global'self.isExtern = element.get('isExtern') == 'true'self.isLocal = element.get('isLocal') == 'true'self.isPointer = element.get('isPointer') == 'true'self.isReference = element.get('isReference') == 'true'self.isStatic = element.get('isStatic') == 'true'self.constness = element.get('constness')if self.constness:self.constness = int(self.constness)def __repr__(self):attrs = ["Id", "nameTokenId", "typeStartTokenId", "typeEndTokenId","access", "scopeId", "isArgument", "isArray", "isClass","isConst", "isGlobal", "isExtern", "isLocal", "isPointer","isReference", "isStatic", "constness", ]return "{}({})".format("Variable",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))def setId(self, IdMap):self.nameToken = IdMap[self.nameTokenId]self.typeStartToken = IdMap[self.typeStartTokenId]self.typeEndToken = IdMap[self.typeEndTokenId]self.scope = IdMap[self.scopeId]class Value:"""Value classAttributes:intvalue integer valuetokvalue token valuefloatvalue float valuecontainerSize container sizecondition condition where this Value comes fromvalueKind 'known' or 'possible'inconclusive Is value inconclusive?"""intvalue = Nonetokvalue = Nonefloatvalue = NonecontainerSize = Nonecondition = NonevalueKind = Noneinconclusive = Falsedef isKnown(self):return self.valueKind and self.valueKind == 'known'def isPossible(self):return self.valueKind and self.valueKind == 'possible'def __init__(self, element):self.intvalue = element.get('intvalue')if self.intvalue:self.intvalue = int(self.intvalue)self.tokvalue = element.get('tokvalue')self.floatvalue = element.get('floatvalue')self.containerSize = element.get('container-size')self.condition = element.get('condition-line')if self.condition:self.condition = int(self.condition)if element.get('known'):self.valueKind = 'known'elif element.get('possible'):self.valueKind = 'possible'if element.get('inconclusive'):self.inconclusive = Truedef __repr__(self):attrs = ["intvalue", "tokvalue", "floatvalue", "containerSize","condition", "valueKind", "inconclusive"]return "{}({})".format("Value",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))class ValueFlow:"""ValueFlow::Value classEach possible value has a ValueFlow::Value item.Each ValueFlow::Value either has a intvalue or tokvalueC++ class:http://cppcheck.net/devinfo/doxyoutput/classValueFlow_1_1Value.htmlAttributes:values Possible values"""Id = Nonevalues = Nonedef __init__(self, element):self.Id = element.get('id')self.values = []def __repr__(self):attrs = ["Id", "values"]return "{}({})".format("ValueFlow",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))class Suppression:"""Suppression classThis class contains a suppression entry to suppress a warning.AttributeserrorId The id string of the error to suppress, can be a wildcardfileName The name of the file to suppress warnings for, can include wildcardslineNumber The number of the line to suppress warnings from, can be 0 to represent any linesymbolName The name of the symbol to match warnings for, can include wildcards"""errorId = NonefileName = NonelineNumber = NonesymbolName = Nonedef __init__(self, element):self.errorId = element.get('errorId')self.fileName = element.get('fileName')self.lineNumber = element.get('lineNumber')self.symbolName = element.get('symbolName')def __repr__(self):attrs = ['errorId' , "fileName", "lineNumber", "symbolName"]return "{}({})".format("Suppression",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))def isMatch(self, file, line, message, errorId):if ((self.fileName is None or fnmatch(file, self.fileName))and (self.lineNumber is None or line == self.lineNumber)and (self.symbolName is None or fnmatch(message, '*'+self.symbolName+'*'))and fnmatch(errorId, self.errorId)):return Trueelse:return Falseclass Configuration:"""Configuration classThis class contains the directives, tokens, scopes, functions,variables, value flows, and suppressions for one configuration.Attributes:name Name of the configuration, "" for defaultdirectives List of Directive itemstokenlist List of Token itemsscopes List of Scope itemsfunctions List of Function itemsvariables List of Variable itemsvalueflow List of ValueFlow valuesstandards List of Standards values"""name = ''directives = []tokenlist = []scopes = []functions = []variables = []valueflow = []standards = Nonedef __init__(self, name):self.name = nameself.directives = []self.tokenlist = []self.scopes = []self.functions = []self.variables = []self.valueflow = []self.standards = Standards()def set_tokens_links(self):"""Set next/previous links between tokens."""prev = Nonefor token in self.tokenlist:token.previous = previf prev:prev.next = tokenprev = tokendef set_id_map(self, arguments):IdMap = {None: None, '0': None, '00000000': None, '0000000000000000': None}for token in self.tokenlist:IdMap[token.Id] = tokenfor scope in self.scopes:IdMap[scope.Id] = scopefor function in self.functions:IdMap[function.Id] = functionfor variable in self.variables:IdMap[variable.Id] = variablefor variable in arguments:IdMap[variable.Id] = variablefor values in self.valueflow:IdMap[values.Id] = values.valuesfor token in self.tokenlist:token.setId(IdMap)for scope in self.scopes:scope.setId(IdMap)for function in self.functions:function.setId(IdMap)for variable in self.variables:variable.setId(IdMap)for variable in arguments:variable.setId(IdMap)def setIdMap(self, functions_arguments):"""Set relationships between objects stored in this configuration.:param functions_arguments: List of Variable objects which are function arguments"""self.set_tokens_links()self.set_id_map(functions_arguments)class Platform:"""Platform classThis class contains type sizesAttributes:name Name of the platformchar_bit CHAR_BIT valueshort_bit SHORT_BIT valueint_bit INT_BIT valuelong_bit LONG_BIT valuelong_long_bit LONG_LONG_BIT valuepointer_bit POINTER_BIT value"""name = ''char_bit = 0short_bit = 0int_bit = 0long_bit = 0long_long_bit = 0pointer_bit = 0def __init__(self, platformnode):self.name = platformnode.get('name')self.char_bit = int(platformnode.get('char_bit'))self.short_bit = int(platformnode.get('short_bit'))self.int_bit = int(platformnode.get('int_bit'))self.long_bit = int(platformnode.get('long_bit'))self.long_long_bit = int(platformnode.get('long_long_bit'))self.pointer_bit = int(platformnode.get('pointer_bit'))def __repr__(self):attrs = ["name", "char_bit", "short_bit", "int_bit","long_bit", "long_long_bit", "pointer_bit"]return "{}({})".format("Platform",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))class Standards:"""Standards classThis class contains versions of standards that were used for the cppcheckAttributes:c C Standard usedcpp C++ Standard usedposix If Posix was used"""c = ""cpp = ""posix = Falsedef set_c(self, node):self.c = node.get("version")def set_cpp(self, node):self.cpp = node.get("version")def set_posix(self, node):self.posix = node.get("posix") is not Nonedef __repr__(self):attrs = ["c", "cpp", "posix"]return "{}({})".format("Standards",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))class CppcheckData:"""Class that makes cppcheck dump data availableContains a list of Configuration instancesAttributes:filename Path to Cppcheck dump filerawTokens List of rawToken elementssuppressions List of SuppressionsTo iterate through all configurations use such code:@codedata = cppcheckdata.parsedump(...)for cfg in data.configurations:print('cfg: ' + cfg.name)@endcodeTo iterate through all tokens in each configuration use such code:@codedata = cppcheckdata.parsedump(...)for cfg in data.configurations:print('cfg: ' + cfg.name)code = ''for token in cfg.tokenlist:code = code + token.str + ' 'print(' ' + code)@endcodeTo iterate through all scopes (functions, types, etc) use such code:@codedata = cppcheckdata.parsedump(...)for cfg in data.configurations:print('cfg: ' + cfg.name)for scope in cfg.scopes:print(' type:' + scope.type + ' name:' + scope.className)@endcode"""rawTokens = []platform = Nonesuppressions = []def __init__(self, filename):""":param filename: Path to Cppcheck dump file"""self.filename = filenamefiles = [] # source files for elements occurred in this configurationplatform_done = Falserawtokens_done = Falsesuppressions_done = False# Parse general configuration options from <dumps> node# We intentionally don't clean node resources here because we# want to serialize in memory only small part of the XML tree.for event, node in ElementTree.iterparse(self.filename, events=('start', 'end')):if platform_done and rawtokens_done and suppressions_done:breakif node.tag == 'platform' and event == 'start':self.platform = Platform(node)platform_done = Trueelif node.tag == 'rawtokens' and event == 'end':for rawtokens_node in node:if rawtokens_node.tag == 'file':files.append(rawtokens_node.get('name'))elif rawtokens_node.tag == 'tok':tok = Token(rawtokens_node)tok.file = files[int(rawtokens_node.get('fileIndex'))]self.rawTokens.append(tok)rawtokens_done = Trueelif node.tag == 'suppressions' and event == 'end':for suppressions_node in node:self.suppressions.append(Suppression(suppressions_node))suppressions_done = True# Set links between rawTokens.for i in range(len(self.rawTokens)-1):self.rawTokens[i+1].previous = self.rawTokens[i]self.rawTokens[i].next = self.rawTokens[i+1]@propertydef configurations(self):"""Return the list of all available Configuration objects."""return list(self.iterconfigurations())def iterconfigurations(self):"""Create and return iterator for the available Configuration objects.The iterator loops over all Configurations in the dump file tree, in document order."""cfg = Nonecfg_arguments = [] # function arguments for Configuration node initializationcfg_function = Nonecfg_valueflow = None# Scopes contains <varlist> with all occurred variables. Some of them# appearaed in <variables> node for this configuration.# Others are arguments of functions.# They have similar tag <var> but doesn't contain any attributes. So we# set set a special state when iterate <varlist> node to prevent# overriding of cfg.variables list with empty values.iter_varlist = False# Use iterable objects to traverse XML tree for dump files incrementally.# Iterative approach is required to avoid large memory consumption.# Calling .clear() is necessary to let the element be garbage collected.for event, node in ElementTree.iterparse(self.filename, events=('start', 'end')):# Serialize new configuration nodeif node.tag == 'dump':if event == 'start':cfg = Configuration(node.get('cfg'))continueelif event == 'end':cfg.setIdMap(cfg_arguments)yield cfgcfg = Nonecfg_arguments = []# Parse standardselif node.tag == "standards" and event == 'start':continueelif node.tag == 'c' and event == 'start':cfg.standards.set_c(node)elif node.tag == 'cpp' and event == 'start':cfg.standards.set_cpp(node)elif node.tag == 'posix' and event == 'start':cfg.standards.set_posix(node)# Parse directives listelif node.tag == 'directive' and event == 'start':cfg.directives.append(Directive(node))# Parse tokenselif node.tag == 'tokenlist' and event == 'start':continueelif node.tag == 'token' and event == 'start':cfg.tokenlist.append(Token(node))# Parse scopeselif node.tag == 'scopes' and event == 'start':continueelif node.tag == 'scope' and event == 'start':cfg.scopes.append(Scope(node))elif node.tag == 'varlist':if event == 'start':iter_varlist = Trueelif event == 'end':iter_varlist = False# Parse functionselif node.tag == 'functionList' and event == 'start':continueelif node.tag == 'function':if event == 'start':cfg_function = Function(node, cfg.scopes[-1])continueelif event == 'end':cfg.functions.append(cfg_function)cfg_function = None# Parse function argumentselif node.tag == 'arg' and event == 'start':arg_nr = int(node.get('nr'))arg_variable_id = node.get('variable')cfg_function.argumentId[arg_nr] = arg_variable_id# Parse variableselif node.tag == 'var' and event == 'start':var = Variable(node)if var.nameTokenId:cfg.variables.append(var)elif not iter_varlist:cfg_arguments.append(var)# Parse valueflows (list of values)elif node.tag == 'valueflow' and event == 'start':continueelif node.tag == 'values':if event == 'start':cfg_valueflow = ValueFlow(node)continueelif event == 'end':cfg.valueflow.append(cfg_valueflow)cfg_valueflow = None# Parse valueselif node.tag == 'value' and event == 'start':cfg_valueflow.values.append(Value(node))# Remove links to the sibling nodesnode.clear()def __repr__(self):attrs = ["configurations", "platform"]return "{}({})".format("CppcheckData",", ".join(("{}={}".format(a, repr(getattr(self, a))) for a in attrs)))# Get function argumentsdef getArgumentsRecursive(tok, arguments):if tok is None:returnif tok.str == ',':getArgumentsRecursive(tok.astOperand1, arguments)getArgumentsRecursive(tok.astOperand2, arguments)else:arguments.append(tok)def getArguments(ftok):if (not ftok.isName) or (ftok.next is None) or ftok.next.str != '(':return Noneargs = []getArgumentsRecursive(ftok.next.astOperand2, args)return argsdef parsedump(filename):"""parse a cppcheck dump file"""return CppcheckData(filename)def astIsFloat(token):"""Check if type of ast node is float/double"""if not token:return Falseif token.str == '.':return astIsFloat(token.astOperand2)if token.str in '+-*/%':return astIsFloat(token.astOperand1) or astIsFloat(token.astOperand2)if not token.variable:# float literal?if token.str[0].isdigit():for c in token.str:if c == 'f' or c == '.' or c == 'E':return Truereturn FalsetypeToken = token.variable.typeStartTokenendToken = token.variable.typeEndTokenwhile typeToken != endToken:if typeToken.str == 'float' or typeToken.str == 'double':return TruetypeToken = typeToken.nextif typeToken.str == 'float' or typeToken.str == 'double':return Truereturn Falseclass CppCheckFormatter(argparse.HelpFormatter):"""Properly formats multiline argument helps"""def _split_lines(self, text, width):# this is the RawTextHelpFormatter._split_linesif text.startswith('R|'):return text[2:].splitlines()return argparse.HelpFormatter._split_lines(self, text, width)def ArgumentParser():"""Returns an argparse argument parser with an already-addedargument definition for -t/--template"""parser = argparse.ArgumentParser(formatter_class=CppCheckFormatter)parser.add_argument('-t', '--template', metavar='<text>',default='{callstack}: ({severity}) {message}',help="R|Format the error messages. E.g.\n""'{file}:{line},{severity},{id},{message}' or\n""'{file}({line}):({severity}) {message}' or\n""'{callstack} {message}'\n""Pre-defined templates: gcc, vs, edit")parser.add_argument("dumpfile", nargs='*',help="Path of dump files from cppcheck.")parser.add_argument("--cli",help="Addon is executed from Cppcheck",action="store_true")parser.add_argument("-q", "--quiet",help='do not print "Checking ..." lines',action="store_true")return parserdef simpleMatch(token, pattern):for p in pattern.split(' '):if not token or token.str != p:return Falsetoken = token.nextreturn Truedef reportError(location, severity, message, addon, errorId, extra=''):if '--cli' in sys.argv:msg = { 'file': location.file,'linenr': location.linenr,'column': location.column,'severity': severity,'message': message,'addon': addon,'errorId': errorId,'extra': extra}sys.stdout.write(json.dumps(msg) + '\n')else:loc = '[%s:%i]' % (location.file, location.linenr)if len(extra) > 0:message += ' (' + extra + ')'sys.stderr.write('%s (%s) %s [%s-%s]\n' % (loc, severity, message, addon, errorId))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。