PageRenderTime 147ms CodeModel.GetById 23ms RepoModel.GetById 2ms app.codeStats 0ms

/index2ddg.py

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