embed.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import re
  2. preprocessorRe = re.compile( r'\s*#.*' )
  3. fdefineRe = re.compile( r'\s*#\s*define\s*(\S*)\s*\(' ) # #defines that take arguments
  4. defineRe = re.compile( r'\s*#\s*define\s*(\S*)(\s+)(.*)' ) # all #defines
  5. undefRe = re.compile( r'\s*#\s*undef\s*(\S*)' ) # all #undefs
  6. ifdefCommonRe = re.compile( r'\s*#\s*if' ) # all #ifdefs
  7. ifdefRe = re.compile( r'\s*#\s*ifdef\s*(\S*)' )
  8. ifndefRe = re.compile( r'\s*#\s*ifndef\s*(\S*)' )
  9. endifRe = re.compile( r'\s*#\s*endif\s*//\s*(.*)' )
  10. elseRe = re.compile( r'\s*#\s*else' )
  11. ifRe = re.compile( r'\s*#\s*if\s+(.*)' )
  12. nsRe = re.compile( r'(.*?\s*\s*namespace\s+)(\w+)(\s*{?)(.*)' )
  13. nsCloseRe = re.compile( r'(.*\s*})(\s*\/\/\s*namespace\s+)(\w+)(\s*)(.*)' )
  14. class LineMapper:
  15. def __init__( self, idMap, outerNamespace ):
  16. self.idMap = idMap
  17. self.outerNamespace = outerNamespace
  18. # TBD:
  19. # #if, #ifdef, comments after #else
  20. def mapLine( self, lineNo, line ):
  21. for idFrom, idTo in self.idMap.items():
  22. r = re.compile("(.*)" + idFrom + "(.*)")
  23. m = r.match( line )
  24. if m:
  25. line = m.group(1) + idTo + m.group(2) + "\n"
  26. m = nsCloseRe.match( line )
  27. if m:
  28. originalNs = m.group(3)
  29. # print("[{0}] originalNs: '{1}' - closing".format(lineNo, originalNs))
  30. # print( " " + line )
  31. # print( " 1:[{0}]\n 2:[{1}]\n 3:[{2}]\n 4:[{3}]\n 5:[{4}]".format( m.group(1), m.group(2), m.group(3), m.group(4), m.group(5) ) )
  32. if originalNs in self.outerNamespace:
  33. outerNs, innerNs = self.outerNamespace[originalNs]
  34. return "{0}}}{1}{2}::{3}{4}{5}\n".format( m.group(1), m.group(2), outerNs, innerNs, m.group(4), m.group(5))
  35. m = nsRe.match( line )
  36. if m:
  37. originalNs = m.group(2)
  38. # print("[{0}] originalNs: '{1}'".format(lineNo, originalNs))
  39. # print( " " + line )
  40. # print( " 1:[{0}]\n 2:[{1}]\n 3:[{2}]\n 4:[{3}]".format( m.group(1), m.group(2), m.group(3), m.group(4) ) )
  41. if originalNs in self.outerNamespace:
  42. outerNs, innerNs = self.outerNamespace[originalNs]
  43. return "{0}{1} {{ namespace {2}{3}{4}\n".format( m.group(1), outerNs, innerNs, m.group(3), m.group(4) )
  44. return line
  45. def mapFile(self, filenameIn, filenameOut ):
  46. print( "Embedding:\n {0}\nas:\n {1}".format( filenameIn, filenameOut ) )
  47. with open( filenameIn, 'r' ) as f, open( filenameOut, 'w' ) as outf:
  48. lineNo = 1
  49. for line in f:
  50. outf.write( self.mapLine( lineNo, line ) )
  51. lineNo = lineNo + 1
  52. print( "Written {0} lines".format( lineNo ) )