![]() |
Главная · Все пространства имен · Все классы · Основные классы · Классы по группам · Модули · Функции |
Файлы:
This example uses XQuery and the xmlpatterns command line utility to query C++ source code.
Suppose we want to analyze C++ source code to find coding standard violations and instances of bad or inefficient patterns. We can do it using the common searching and pattern matching utilities to process the C++ files (e.g., grep, sed, and awk). Now we can also use XQuery with the QtXmlPatterns module.
An extension to the g++ open source C++ compiler (GCC-XML) generates an XML description of C++ source code declarations. This XML description can then be processed by QtXmlPatterns using XQueries to navigate the XML description of the C++ source and produce a report. Consider the problem of finding mutable global variables:
Suppose we want to introduce threading to a C++ application that was originally written without threading. In a threaded program, mutable global variables can cause bugs, because one thread might change a global variable that other threads are reading, or two threads might try to set the same global variable. So when converting our program to use threading, one of the things we must do is protect the global variables to prevent the bugs described above. How can we use XQuery and GCC-XML to find the variables that need protecting?
Consider the declarations in this hypothetical C++ application:
1. int mutablePrimitive1;
2. int mutablePrimitive2;
3. const int constPrimitive1 = 4;
4. const int constPrimitive2 = 3;
5.
6. class ComplexClass
7. {
8. public:
9. ComplexClass();
10. ComplexClass(const ComplexClass &);
11. ~ComplexClass();
12. };
13.
14. ComplexClass mutableComplex1;
15. ComplexClass mutableComplex2;
16. const ComplexClass constComplex1;
17. const ComplexClass constComplex2;
18.
19. int main()
20. {
22. int localVariable;
23. localVariable = 0;
24. return localVariable;
25. }
Submitting this C++ source to GCC-XML produces this XML description:
<GCC_XML>
<Namespace id=_1 name=:: members=_3 _4 _5 _6 _7 _8 _9 _10 _11 _12 _13 _14 _15 mangled=_Z2::/>
<Namespace id=_2 name=std context=_1 members= mangled=_Z3std/>
<Function id=_3 name=_GLOBAL__D_globals.cppwVRo3a returns=_16 context=_1 location=f0:14 file=f0 line=14 endline=14/>
<Function id=_4 name=_GLOBAL__I_globals.cppwVRo3a returns=_16 context=_1 location=f0:14 file=f0 line=14 endline=14/>
<Function id=_5 name=__static_initialization_and_destruction_0 returns=_16 context=_1 mangled=_Z41__static_initialization_and_destruction_0ii location=f0:23 file=f0 line=23 endline=14>
<Argument name=__initialize_p type=_17/>
<Argument name=__priority type=_17/>
</Function>
<Function id=_6 name=main returns=_17 context=_1 location=f0:20 file=f0 line=20 endline=24/>
<Variable id=_7 name=constComplex2 type=_11c context=_1 location=f0:17 file=f0 line=17/>
<Variable id=_8 name=constComplex1 type=_11c context=_1 location=f0:16 file=f0 line=16/>
<Variable id=_9 name=mutableComplex2 type=_11 context=_1 location=f0:15 file=f0 line=15/>
<Variable id=_10 name=mutableComplex1 type=_11 context=_1 location=f0:14 file=f0 line=14/>
<Class id=_11 name=ComplexClass context=_1 mangled=12ComplexClass location=f0:7 file=f0 line=7 members=_19 _20 _21 bases=/>
<Variable id=_12 name=constPrimitive2 type=_17c init=3 context=_1 location=f0:4 file=f0 line=4/>
<Variable id=_13 name=constPrimitive1 type=_17c init=4 context=_1 location=f0:3 file=f0 line=3/>
<Variable id=_14 name=mutablePrimitive2 type=_17 context=_1 location=f0:2 file=f0 line=2/>
<Variable id=_15 name=mutablePrimitive1 type=_17 context=_1 location=f0:1 file=f0 line=1/>
<FundamentalType id=_16 name=void/>
<FundamentalType id=_17 name=int/>
<CvQualifiedType id=_11c type=_11 const=1/>
<Constructor id=_19 name=ComplexClass context=_11 mangled=_ZN12ComplexClassC1Ev *INTERNAL* location=f0:9 file=f0 line=9 extern=1/>
<Constructor id=_20 name=ComplexClass context=_11 mangled=_ZN12ComplexClassC1ERKS_ *INTERNAL* location=f0:10 file=f0 line=10 extern=1>
<Argument type=_23/>
</Constructor>
<Destructor id=_21 name=ComplexClass context=_11 mangled=_ZN12ComplexClassD1Ev *INTERNAL* location=f0:11 file=f0 line=11 extern=1>
</Destructor>
<CvQualifiedType id=_17c type=_17 const=1/>
<ReferenceType id=_23 type=_11c/>
<File id=f0 name=globals.cpp/>
</GCC_XML>
We need an XQuery to find the global variables in the XML description. Here is our XQuery source. We walk through it in XQuery Code Walk-Through.
(:
Этот XQuery загружает файл GCC-XML и сообщает содержимое всех
глобальных переменных исходного файла исходных кодов C++. Чтобы запустить запрос,
используйте командную строку:
xmlpatterns reportGlobals.xq -param fileToOpen=globals.gccxml -output globals.html
fileToOpen=globals.gccxml назначает имя файла globals.gccxml
переменной fileToOpen описанной и используемой ниже.
:)
declare variable as xs:anyURI external;
declare variable as document-node() := doc();
(:
Эта функция определяет является ли typeId сложным типом,
например, QString. Мы просто проверяем не является ли он классом. Если быть точным,
то мы должны проверять есть ли у класса несинтезированный
конструктор. Мы принимаем как изменяемые, так и постоянные типы.
:)
declare function local:isComplexType( as xs:string) as xs:boolean
{
exists(/GCC_XML/Class[@id = ])
или
exists(/GCC_XML/Class[@id = /GCC_XML/CvQualifiedType[@id = ]/@type])
};
(:
Эта функция определяет, является ли typeId простым типом.
:)
declare function local:isPrimitive( as xs:string) as xs:boolean
{
exists(/GCC_XML/FundamentalType[@id = ])
};
(:
Эта функция создаёт строку для отчета. Строка содержит
имя переменной, файл исходных кодов и номер строки.
:)
declare function local:location( as element()) as xs:string
{
concat(/GCC_XML/File[@id = /@file]/@name, at line , /@line)
};
(:
Эта функция генерирует отчет. Заметьте, что она вызывает один раз
в элементе <body> вывода <html>.
Она игнорирует постоянные переменные простых типов, но сообщает обо всех остальных.
:)
declare function local:report() as element()+
{
let as element(Variable)* := /GCC_XML/Variable[local:isComplexType(@type)]
return if (exists())
then (<p xmlns=http://www.w3.org/1999/xhtml/>Global variables with complex types:</p>,
<ol xmlns=http://www.w3.org/1999/xhtml/>
{
(: Для каждой Variable в ... :)
/<li><span class=variableName>{string(@name)}</span> in {local:location(.)}</li>
}
</ol>)
else <p xmlns=http://www.w3.org/1999/xhtml/>No complex global variables found.</p>
,
let as element(Variable)+ := /GCC_XML/Variable[local:isPrimitive(@type)]
return if (exists())
then (<p xmlns=http://www.w3.org/1999/xhtml/>Mutable global variables with primitives types:</p>,
<ol xmlns=http://www.w3.org/1999/xhtml/>
{
(: Для каждой Variable в ... :)
/<li><span class=variableName>{string(@name)}</span> in {local:location(.)}</li>
}
</ol>)
else <p xmlns=http://www.w3.org/1999/xhtml/>No mutable primitive global variables found.</p>
};
(:
Здесь происходит вывод <html> отчета. Сначала
стиль, затем элемент <body>,
который содержит вызов \c{local:report()}
указанный выше.
:)
<html xmlns=http://www.w3.org/1999/xhtml/ xml:lang=en lang=en>
<head>
<title>Global variables report for </title>
</head>
<style type=text/css>
.details
{{
text-align: left;
font-size: 80%;
color: blue
}}
.variableName
{{
font-family: courier;
color: blue
}}
</style>
<body>
<p class=details>Start report: {current-dateTime()}</p>
{
local:report()
}
<p class=details>End report: {current-dateTime()}</p>
</body>
</html>
To run the XQuery using the xmlpatterns command line utility, enter the following command:
xmlpatterns reportGlobals.xq -param fileToOpen=globals.gccxml -output globals.html
The xmlpatterns command loads and parses globals.gccxml, runs the XQuery reportGlobals.xq, and generates this report:
|
Start report: 2008-12-16T13:43:49.65Z Global variables with complex types:
Mutable global variables with primitives types:
End report: 2008-12-16T13:43:49.65Z |
|
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |