PageRenderTime 56ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/fathead/cppreference_doc/cppreference-doc/index2ddg.py

http://github.com/duckduckgo/zeroclickinfo-fathead
Python | 563 lines | 460 code | 53 blank | 50 comment | 45 complexity | e7be3d207420f8d3f63edb2c53cdd60b MD5 | raw file
Possible License(s): Apache-2.0
  1. #!/usr/bin/env python3
  2. '''
  3. Copyright (C) 2013 Povilas Kanapickas <povilas@radix.lt>
  4. This file is part of cppreference-doc
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see http://www.gnu.org/licenses/.
  15. '''
  16. import argparse
  17. import fnmatch
  18. import json
  19. import os
  20. import sys
  21. import re
  22. import lxml.etree as e
  23. import lxml.html as html
  24. from index_transform import IndexTransform
  25. from xml_utils import xml_escape
  26. from build_link_map import build_link_map
  27. from ddg_parse_html import get_declarations, get_short_description, DdgException
  28. # Entry types
  29. # a class or struct
  30. ITEM_TYPE_CLASS = 1
  31. # a member function or free function
  32. ITEM_TYPE_FUNCTION = 2
  33. # a constructor
  34. ITEM_TYPE_CONSTRUCTOR = 3
  35. # a constructor that is described in the same page as the class
  36. ITEM_TYPE_CONSTRUCTOR_INLINEMEM = 4
  37. # a destructor
  38. ITEM_TYPE_DESTRUCTOR = 5
  39. # a destructor that is described in the same page as the class
  40. ITEM_TYPE_DESTRUCTOR_INLINEMEM = 6
  41. # a member function that is described in the same page as the class
  42. ITEM_TYPE_FUNCTION_INLINEMEM = 7
  43. # an enum
  44. ITEM_TYPE_ENUM = 8
  45. # a value of an enum
  46. ITEM_TYPE_ENUM_CONST = 9
  47. # a variable
  48. ITEM_TYPE_VARIABLE = 10
  49. # a member variable that is described in the same page as the containing class
  50. ITEM_TYPE_VARIABLE_INLINEMEM = 11
  51. def get_item_type(el):
  52. if (el.tag == 'const' and el.getparent().tag == 'enum' and
  53. el.get('link') == '.'):
  54. return ITEM_TYPE_ENUM_CONST
  55. if el.tag == 'function':
  56. if el.get('link') == '.':
  57. return ITEM_TYPE_FUNCTION_INLINEMEM
  58. else:
  59. return ITEM_TYPE_FUNCTION
  60. if el.tag == 'variable':
  61. if el.get('link') == '.':
  62. return ITEM_TYPE_VARIABLE_INLINEMEM
  63. else:
  64. return ITEM_TYPE_VARIABLE
  65. if el.tag == 'constructor':
  66. if el.get('link') == '.':
  67. return ITEM_TYPE_CONSTRUCTOR_INLINEMEM
  68. else:
  69. return ITEM_TYPE_CONSTRUCTOR
  70. if el.tag == 'destructor':
  71. if el.get('link') == '.':
  72. return ITEM_TYPE_DESTRUCTOR_INLINEMEM
  73. else:
  74. return ITEM_TYPE_DESTRUCTOR
  75. if el.tag == 'class':
  76. return ITEM_TYPE_CLASS
  77. if el.tag == 'enum':
  78. return ITEM_TYPE_ENUM
  79. return None # not recognized
  80. class DDGDebug:
  81. def __init__(self, enabled=False, ident_match=None, debug_abstracts_path=None):
  82. self.enabled = enabled
  83. self.ident_match = ident_match
  84. self.stat_line_nums = []
  85. self.debug_abstracts_file = sys.stdout
  86. if debug_abstracts_path is not None:
  87. self.debug_abstracts_file = open(debug_abstracts_path, 'w', encoding='utf-8')
  88. # track the statistics of number of lines used by the entries
  89. def submit_line_num(self, line_num):
  90. while len(self.stat_line_nums) <= line_num:
  91. self.stat_line_nums.append(0)
  92. self.stat_line_nums[line_num] += 1
  93. def should_skip_ident(self, ident):
  94. if self.ident_match is None:
  95. return False
  96. if isinstance(ident, list):
  97. for i in ident:
  98. if self.ident_match in i:
  99. return False
  100. else:
  101. if self.ident_match in ident:
  102. return False
  103. return True
  104. class Index2DuckDuckGoList(IndexTransform):
  105. def __init__(self, ident_map):
  106. self.ident_map = ident_map
  107. super(Index2DuckDuckGoList, self).__init__(ignore_typedefs=True)
  108. def process_item_hook(self, el, full_name, full_link):
  109. item_type = get_item_type(el)
  110. if item_type:
  111. if full_link in self.ident_map:
  112. self.ident_map[full_link][full_name] = item_type
  113. else:
  114. self.ident_map[full_link] = { full_name : item_type }
  115. IndexTransform.process_item_hook(self, el, full_name, full_link)
  116. def get_html_files(root):
  117. files = []
  118. for dir, dirnames, filenames in os.walk(root):
  119. for filename in fnmatch.filter(filenames, '*.html'):
  120. files.append(os.path.join(dir, filename))
  121. return files
  122. def get_processing_instructions(ident_map, link_map):
  123. proc_ins = {}
  124. for link in ident_map:
  125. if link in link_map.mapping:
  126. fn = link_map.mapping[link]
  127. if fn not in proc_ins:
  128. proc_ins[fn] = { 'fn': fn, 'link': link, 'idents': {}}
  129. for ident in ident_map[link]:
  130. proc_ins[fn]['idents'][ident] = { 'ident' : ident,
  131. 'type' : ident_map[link][ident] }
  132. return proc_ins
  133. # process the files
  134. # returns the unqualified name of an identifier
  135. def get_unqualified_name(ident):
  136. if ident.find('(') != -1:
  137. ident = re.sub('\(.*?\)', '', ident)
  138. if ident.find('<') != -1:
  139. ident = re.sub('\<.*?\>', '', ident)
  140. qpos = ident.rfind('::')
  141. if qpos != -1:
  142. ident = ident[qpos+2:]
  143. return ident
  144. # returns the version number common to all declarations. Returns none if two
  145. # declarations have different version numbers or if no version number is
  146. # provided
  147. def get_version(decls):
  148. rv = None
  149. for code,v in decls:
  150. if v:
  151. if rv == None:
  152. rv = v
  153. elif v != rv:
  154. return None
  155. return rv
  156. def build_abstract(decls, desc, max_code_lines, split_code_lines, debug=DDGDebug()):
  157. limited = False
  158. code_snippets = []
  159. for i,(code,ver) in enumerate(decls):
  160. code = code.strip()
  161. code = code.replace('<', '&lt;').replace('>', '&gt;')
  162. code_num_lines = code.count('\n') + 1
  163. # limit the number of code snippets to be included so that total number
  164. # of lines is less than max_code_lines. The limit becomes active only
  165. # for the second and subsequent snippets.
  166. first = True if i == 0 else False;
  167. last = True if i == len(decls)-1 else False;
  168. if not first:
  169. if last:
  170. if code_num_lines > max_code_lines:
  171. limited = True
  172. break
  173. else:
  174. if code_num_lines > max_code_lines - 1:
  175. # -1 because we need to take into account
  176. # < omitted declarations > message
  177. limited = True
  178. break
  179. code_snippets.append(code)
  180. max_code_lines -= code_num_lines
  181. if split_code_lines:
  182. code_snippets = ['<pre><code>' + s + '</code></pre>' for s in code_snippets]
  183. code_text = ''.join(code_snippets)
  184. else:
  185. code_text = '<pre><code>' + '\n\n'.join(code_snippets) + '</code></pre>'
  186. if limited:
  187. code_text += '\n<p><em>Additional declarations have been omitted</em></p>'
  188. # count the number of lines used
  189. num_lines = code_text.count('\n') + 1 # last line has no newline after it
  190. if len(desc) > 110:
  191. num_lines += 2
  192. else:
  193. num_lines += 1
  194. debug.submit_line_num(num_lines)
  195. result_lines = [
  196. '<section class="prog__container">',
  197. '<p>' + desc + '</p>',
  198. code_text,
  199. '</section>'
  200. ]
  201. result_text = '\n'.join(result_lines)
  202. if debug.enabled and num_lines >= 10:
  203. print("# error : large number of lines: ")
  204. print("# BEGIN ======")
  205. print(result_text)
  206. print("# END ========")
  207. return result_text
  208. ''' Outputs additional redirects for an identifier.
  209. Firstly, we replace '::' with spaces. Then we add two redirects: one with
  210. unchanged text and another with '_' replaced with spaces. We strip one
  211. level of namespace/class qualification and repeat the process with the
  212. remaining text.
  213. For constructors and destructors, we strip the function name and apply the
  214. abovementioned algorithm, the only difference being that we append
  215. (or prepend) 'constructor' or 'destructor' to the title of the redirect
  216. respectively.
  217. Each redirect has a 'priority', which is defined by the number of stripped
  218. namespace/class qualifications from the entry that produced the redirect.
  219. This is used to remove duplicate redirects. For each group of duplicate
  220. redirects, we find the redirect with the highest priority (i.e. lowest
  221. number of qualifications stripped) and remove all other redirects. If the
  222. number of highest-priority redirects is more than one, then we remove all
  223. redirects from the group altogether.
  224. We don't add any redirects to specializations, overloads or operators.
  225. '''
  226. ''' array of dict { 'title' -> redirect title,
  227. 'target' -> redirect target,
  228. 'priority' -> redirect priority as int
  229. }
  230. '''
  231. def build_redirects(redirects, item_ident, item_type):
  232. for ch in [ '(', ')', '<', '>', 'operator' ]:
  233. if ch in item_ident:
  234. return
  235. target = item_ident
  236. parts = item_ident.split('::')
  237. # -----
  238. def do_parts(redirects, parts, prepend='', append=''):
  239. if prepend != '':
  240. prepend = prepend + ' '
  241. if append != '':
  242. append = ' ' + append
  243. p = 0
  244. while p < len(parts):
  245. redir1 = prepend + ' '.join(parts[p:]) + append
  246. redir2 = prepend + ' '.join(x.replace('_',' ') for x in parts[p:]) + append
  247. redir1 = redir1.replace(' ', ' ').replace(' ', ' ')
  248. redir2 = redir2.replace(' ', ' ').replace(' ', ' ')
  249. redirects.append({'title' : redir1, 'target' : target,
  250. 'priority' : p})
  251. if redir1 != redir2:
  252. redirects.append({'title' : redir2, 'target' : target,
  253. 'priority' : p})
  254. p += 1
  255. # -----
  256. if item_type in [ ITEM_TYPE_CLASS,
  257. ITEM_TYPE_FUNCTION,
  258. ITEM_TYPE_FUNCTION_INLINEMEM,
  259. ITEM_TYPE_VARIABLE,
  260. ITEM_TYPE_VARIABLE_INLINEMEM,
  261. ITEM_TYPE_ENUM,
  262. ITEM_TYPE_ENUM_CONST ]:
  263. do_parts(redirects, parts)
  264. elif item_type in [ ITEM_TYPE_CONSTRUCTOR,
  265. ITEM_TYPE_CONSTRUCTOR_INLINEMEM ]:
  266. parts.pop()
  267. do_parts(redirects, parts, prepend='constructor')
  268. do_parts(redirects, parts, append='constructor')
  269. elif item_type in [ ITEM_TYPE_DESTRUCTOR,
  270. ITEM_TYPE_DESTRUCTOR_INLINEMEM ]:
  271. parts.pop()
  272. do_parts(redirects, parts, prepend='destructor')
  273. do_parts(redirects, parts, append='destructor')
  274. else:
  275. pass # should not be here
  276. def output_redirects(out, redirects):
  277. # convert to a convenient data structure
  278. # dict { title -> dict { priority -> list ( targets ) } }
  279. redir_map = {}
  280. for r in redirects:
  281. title = r['title']
  282. target = r['target']
  283. priority = r['priority']
  284. if title not in redir_map:
  285. redir_map[title] = {}
  286. if priority not in redir_map[title]:
  287. redir_map[title][priority] = []
  288. redir_map[title][priority].append(target)
  289. # get non-duplicate redirects
  290. ok_redirects = [] # list ( dict { 'title' : title, 'target' : target })
  291. for title in redir_map:
  292. # priority decreases with increasing values
  293. highest_prio = min(redir_map[title])
  294. if len(redir_map[title][highest_prio]) == 1:
  295. # not duplicate
  296. target = redir_map[title][highest_prio][0]
  297. ok_redirects.append({ 'title' : title, 'target' : target })
  298. # sort the redirects
  299. ok_redirects = sorted(ok_redirects, key=lambda x: x['title'])
  300. # output
  301. for r in ok_redirects:
  302. # title
  303. line = r['title'] + '\t'
  304. # type
  305. line += 'R\t'
  306. # redirect
  307. line += r['target'] + '\t'
  308. # otheruses, categories, references, see_also, further_reading,
  309. # external links, disambiguation, images, abstract, source url
  310. line += '\t\t\t\t\t\t\t\t\t\t\n'
  311. out.write(line)
  312. def process_identifier(out, redirects, root, link, item_ident, item_type,
  313. opts, debug=DDGDebug()):
  314. # get the name by extracting the unqualified identifier
  315. name = get_unqualified_name(item_ident)
  316. debug_verbose = True if debug.enabled and debug.ident_match is not None else False
  317. try:
  318. if item_type == ITEM_TYPE_CLASS:
  319. decls = get_declarations(root, name)
  320. desc = get_short_description(root, get_version(decls), opts.max_sentences, opts.max_characters,
  321. opts.max_paren_chars, debug=debug_verbose)
  322. abstract = build_abstract(decls, desc, opts.max_code_lines,
  323. opts.split_code_snippets, debug=debug)
  324. elif item_type in [ ITEM_TYPE_FUNCTION,
  325. ITEM_TYPE_CONSTRUCTOR,
  326. ITEM_TYPE_DESTRUCTOR ]:
  327. decls = get_declarations(root, name)
  328. desc = get_short_description(root, get_version(decls), opts.max_sentences, opts.max_characters,
  329. opts.max_paren_chars, debug=debug_verbose)
  330. abstract = build_abstract(decls, desc, opts.max_code_lines,
  331. opts.split_code_snippets, debug=debug)
  332. elif item_type in [ ITEM_TYPE_FUNCTION_INLINEMEM,
  333. ITEM_TYPE_CONSTRUCTOR_INLINEMEM,
  334. ITEM_TYPE_DESTRUCTOR_INLINEMEM ]:
  335. raise DdgException("INLINEMEM") # not implemented
  336. ''' Implementation notes:
  337. * the declarations are possibly versioned
  338. * declaration is selected from the member table
  339. * the member table is found according to the identifier
  340. (last part after :: is enough, hopefully)
  341. '''
  342. elif item_type in [ ITEM_TYPE_VARIABLE,
  343. ITEM_TYPE_VARIABLE_INLINEMEM,
  344. ITEM_TYPE_ENUM ]:
  345. raise DdgException("ENUM") # not implemented
  346. ''' Implementation notes:
  347. * the declarations are possibly versioned
  348. '''
  349. elif item_type == ITEM_TYPE_ENUM_CONST:
  350. raise DdgException("ENUM_CONST") # not implemented
  351. ''' Implementation notes:
  352. * the abstract will come from the const -> definition table,
  353. which is always put before the first heading.
  354. * the declaration will come from the dcl template. We need
  355. to split the content at ';' and ',', then search for the
  356. name of the enum. If we find duplicates, signal an error.
  357. '''
  358. if debug.enabled:
  359. debug.debug_abstracts_file.write("--------------\n")
  360. debug.debug_abstracts_file.write(item_ident + '\n')
  361. debug.debug_abstracts_file.write(abstract + '\n')
  362. # title
  363. line = item_ident + '\t'
  364. # type
  365. line += 'A\t'
  366. # redirect, otheruses, categories, references, see_also,
  367. # further_reading, external links, disambiguation, images
  368. line += '\t\t\t\t\t\t\t\t\t'
  369. # abstract
  370. abstract = abstract.replace('\n','\\n')
  371. line += abstract + '\t'
  372. # source url
  373. line += 'http://en.cppreference.com/w/' + link + '\n'
  374. out.write(line)
  375. build_redirects(redirects, item_ident, item_type)
  376. except DdgException as err:
  377. if debug.enabled:
  378. line = '# error (' + str(err) + "): " + link + ": " + item_ident + "\n"
  379. out.write(line)
  380. def main():
  381. parser = argparse.ArgumentParser(prog='index2ddg.py')
  382. parser.add_argument('index', type=str,
  383. help='The path to the XML index containing identifier data')
  384. parser.add_argument('reference', type=str,
  385. help=('The path to the downloaded reference (reference '
  386. 'directory in the downloaded archive)'))
  387. parser.add_argument('output', type=str,
  388. help='The path to destination output.txt file')
  389. parser.add_argument('--split_code_snippets', action='store_true', default=False,
  390. help='Puts each declaration into a separate code snippet.')
  391. parser.add_argument('--max_code_lines', type=int, default=6,
  392. help='Maximum number of lines of code to show in abstract')
  393. parser.add_argument('--max_sentences', type=int, default=1,
  394. help='Maximum number of sentences to use for the description')
  395. parser.add_argument('--max_characters', type=int, default=200,
  396. help='Maximum number of characters to use for the description')
  397. parser.add_argument('--max_paren_chars', type=int, default=40,
  398. help='Maximum size of parenthesized text in the description. '+
  399. 'Parenthesized chunks longer than that is removed, unless '+
  400. 'they are within <code>, <b> or <i> tags')
  401. parser.add_argument('--debug', action='store_true', default=False,
  402. help='Enables debug mode.')
  403. parser.add_argument('--debug_ident', type=str, default=None,
  404. help='Processes only the identifiers that match debug_ident')
  405. parser.add_argument('--debug_abstracts_path', type=str, default=None,
  406. help='Path to print the abstracts before newline stripping occurs')
  407. args = parser.parse_args()
  408. # If a the second argument is 'debug', the program switches to debug mode and
  409. # prints everything to stdout. If the third argument is provided, the program
  410. # processes only the identifiers that match the provided string
  411. debug = DDGDebug(args.debug, args.debug_ident, args.debug_abstracts_path)
  412. index_file = args.index
  413. output_file = args.output
  414. # a map that stores information about location and type of identifiers
  415. # it's two level map: full_link maps to a dict that has full_name map to
  416. # ITEM_TYPE_* value
  417. ident_map = {}
  418. # get a list of pages to analyze
  419. tr = Index2DuckDuckGoList(ident_map)
  420. tr.transform(index_file)
  421. # get a list of existing pages
  422. html_files = get_html_files(args.reference)
  423. # get a mapping between titles and pages
  424. # linkmap = dict { title -> filename }
  425. link_map = build_link_map(args.reference)
  426. # create a list of processing instructions for each page
  427. proc_ins = get_processing_instructions(ident_map, link_map)
  428. # sort proc_ins to produce ordered output.txt
  429. proc_ins = [ v for v in proc_ins.values() ]
  430. proc_ins = sorted(proc_ins, key=lambda x: x['link'])
  431. for page in proc_ins:
  432. idents = page['idents']
  433. idents = [ v for v in idents.values() ]
  434. idents = sorted(idents, key=lambda x: x['ident'])
  435. page['idents'] = idents
  436. redirects = []
  437. out = open(output_file, 'w', encoding='utf-8')
  438. #i=1
  439. for page in proc_ins:
  440. idents = page['idents']
  441. link = page['link']
  442. fn = page['fn']
  443. if debug.should_skip_ident([ i['ident'] for i in idents ]):
  444. continue
  445. #print(str(i) + '/' + str(len(proc_ins)) + ': ' + link)
  446. #i+=1
  447. root = e.parse(os.path.join(args.reference, fn), parser=html.HTMLParser())
  448. for ident in idents:
  449. item_ident = ident['ident']
  450. item_type = ident['type']
  451. process_identifier(out, redirects, root, link, item_ident, item_type,
  452. args, debug=debug)
  453. output_redirects(out, redirects)
  454. if debug.enabled:
  455. print('=============================')
  456. print('Numbers of lines used:')
  457. for i,l in enumerate(debug.stat_line_nums):
  458. print(str(i) + ': ' + str(l) + ' result(s)')
  459. if __name__ == "__main__":
  460. main()