VerifierHelper.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. # Copyright (C) Microsoft Corporation. All rights reserved.
  2. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details.
  3. r"""VerifierHelper.py - help with test content used with:
  4. clang-hlsl-tests /name:VerifierTest.*
  5. This script will produce an HLSL file with expected-error and expected-warning
  6. statements corresponding to actual errors/warnings produced from clang-hlsl-tests.
  7. The new file will be located in %TEMP%, named after the original file, but with
  8. the added extension '.result'.
  9. This can then be compared with the original file (such as varmods-syntax.hlsl)
  10. to see the differences in errors. It may also be used to replace the original
  11. file, once the correct output behavior is verified.
  12. This script can also be used to do the same with fxc, adding expected errors there too.
  13. If there were errors/warnings/notes reported by clang, but nothing reported by fxc, an
  14. "fxc-pass {{}}" entry will be added. If copied to reference, it means that you sign
  15. off on the difference in behavior between clang and fxc.
  16. In ast mode, this will find the ast subtree corresponding to a line of code preceding
  17. a line containing only: "/*verify-ast", and insert a stripped subtree between this marker
  18. and a line containing only: "*/". This relies on clang.exe in the build directory.
  19. This tool expects clang.exe and clang-hlsl-tests.dll to be in %HLSL_BLD_DIR%\bin\Debug.
  20. Usage:
  21. VerifierHelper.py clang <testname> - run test through clang-hlsl-tests and show differences
  22. VerifierHelper.py fxc <testname> - run test through fxc and show differences
  23. VerifierHelper.py ast <testname> - run test through ast-dump and show differences
  24. VerifierHelper.py all <testname> - run test through clang-hlsl-tests, ast-dump, and fxc, then show differences
  25. <testname> - name of verifier test as passed to "te clang-hlsl-tests.dll /name:VerifierTest::<testname>":
  26. Example: RunVarmodsSyntax
  27. Can also specify * to run all tests
  28. Environment variables - set these to ensure this tool works properly:
  29. HLSL_SRC_DIR - root path of HLSLonLLVM enlistment
  30. HLSL_BLD_DIR - path to projects and build output
  31. HLSL_FXC_PATH - fxc.exe to use for comparison purposes
  32. HLSL_DIFF_TOOL - tool to use for file comparison (optional)
  33. """
  34. import os, sys, re
  35. try: DiffTool = os.environ['HLSL_DIFF_TOOL']
  36. except: DiffTool = None
  37. try: FxcPath = os.environ['HLSL_FXC_PATH']
  38. except: FxcPath = 'fxc'
  39. HlslVerifierTestCpp = os.path.expandvars(r'${HLSL_SRC_DIR}\tools\clang\unittests\HLSL\VerifierTest.cpp')
  40. HlslDataDir = os.path.expandvars(r'${HLSL_SRC_DIR}\tools\clang\test\HLSL')
  41. HlslBinDir = os.path.expandvars(r'${HLSL_BLD_DIR}\Debug\bin')
  42. VerifierTests = {
  43. 'RunAttributes': 'attributes.hlsl',
  44. 'RunBadInclude': 'bad-include.hlsl',
  45. 'RunBinopDims': 'binop-dims.hlsl',
  46. 'RunCXX11Attributes': 'cxx11-attributes.hlsl',
  47. 'RunConstAssign': 'const-assign.hlsl',
  48. 'RunConstDefault': 'const-default.hlsl',
  49. 'RunConstExpr': 'const-expr.hlsl',
  50. 'RunCppErrors': 'cpp-errors.hlsl',
  51. 'RunCppErrorsHV2015': 'cpp-errors-hv2015.hlsl',
  52. 'RunDerivedToBaseCasts': 'derived-to-base.hlsl',
  53. 'RunEffectsSyntax': 'effects-syntax.hlsl',
  54. 'RunEnums': 'enums.hlsl',
  55. 'RunFunctions': 'functions.hlsl',
  56. 'RunImplicitCasts': 'implicit-casts.hlsl',
  57. 'RunIndexingOperator': 'indexing-operator.hlsl',
  58. 'RunIntrinsicExamples': 'intrinsic-examples.hlsl',
  59. 'RunLiterals': 'literals.hlsl',
  60. 'RunMatrixAssignments': 'matrix-assignments.hlsl',
  61. 'RunMatrixSyntax': 'matrix-syntax.hlsl',
  62. 'RunMatrixSyntaxExactPrecision': 'matrix-syntax-exact-precision.hlsl',
  63. 'RunMoreOperators': 'more-operators.hlsl',
  64. 'RunObjectOperators': 'object-operators.hlsl',
  65. 'RunPackReg': 'packreg.hlsl',
  66. 'RunRayTracings': "raytracing.hlsl",
  67. 'RunScalarAssignments': 'scalar-assignments.hlsl',
  68. 'RunScalarAssignmentsExactPrecision': 'scalar-assignments-exact-precision.hlsl',
  69. 'RunScalarOperators': 'scalar-operators.hlsl',
  70. 'RunScalarOperatorsAssign': 'scalar-operators-assign.hlsl',
  71. 'RunScalarOperatorsAssignExactPrecision': 'scalar-operators-assign-exact-precision.hlsl',
  72. 'RunScalarOperatorsExactPrecision': 'scalar-operators-exact-precision.hlsl',
  73. 'RunSemantics': 'semantics.hlsl',
  74. 'RunString': 'string.hlsl',
  75. 'RunStructAssignments': 'struct-assignments.hlsl',
  76. 'RunTemplateChecks': 'template-checks.hlsl',
  77. 'RunTypemodsSyntax': 'typemods-syntax.hlsl',
  78. 'RunUint4Add3': 'uint4_add3.hlsl',
  79. 'RunVarmodsSyntax': 'varmods-syntax.hlsl',
  80. 'RunVectorAssignments': 'vector-assignments.hlsl',
  81. 'RunVectorConditional': 'vector-conditional.hlsl',
  82. 'RunVectorSyntax': 'vector-syntax.hlsl',
  83. 'RunVectorSyntaxExactPrecision': 'vector-syntax-exact-precision.hlsl',
  84. 'RunVectorSyntaxMix': 'vector-syntax-mix.hlsl',
  85. 'RunWave': 'wave.hlsl',
  86. }
  87. # The following test(s) do not work in fxc mode:
  88. fxcExcludedTests = [
  89. 'RunCppErrors',
  90. 'RunCppErrorsHV2015',
  91. 'RunCXX11Attributes',
  92. 'RunEnums',
  93. 'RunIntrinsicExamples',
  94. 'RunMatrixSyntaxExactPrecision',
  95. 'RunRayTracings',
  96. 'RunScalarAssignmentsExactPrecision',
  97. 'RunScalarOperatorsAssignExactPrecision',
  98. 'RunScalarOperatorsExactPrecision',
  99. 'RunVectorSyntaxExactPrecision',
  100. 'RunWave',
  101. ]
  102. # rxRUN = re.compile(r'[ RUN ] VerifierTest.(\w+)') # gtest syntax
  103. rxRUN = re.compile(r'StartGroup: VerifierTest::(\w+)') # TAEF syntax
  104. rxEndGroup = re.compile(r'EndGroup: VerifierTest::(\w+)\s+\[(\w+)\]') # TAEF syntax
  105. rxForProgram = re.compile(r'^for program (.*?) with errors\:$')
  106. # rxExpected = re.compile(r"^error\: \'(\w+)\' diagnostics (expected but not seen|seen but not expected)\: $") # gtest syntax
  107. rxExpected = re.compile(r"^\'(\w+)\' diagnostics (expected but not seen|seen but not expected)\: $") # TAEF syntax
  108. rxDiagReport = re.compile(r' (?:File (.*?) )?Line (\d+): (.*)$')
  109. rxDiag = re.compile(r'((expected|fxc)-(error|warning|note|pass)\s*\{\{(.*?)\}\}\s*)')
  110. rxFxcErr = re.compile(r'(.+)\((\d+)(?:,(\d+)(?:\-(\d+))?)?\)\: (error|warning) (.*?)\: (.*)')
  111. # groups = (filename, line, colstart, colend, ew, error_code, error_message)
  112. rxCommentStart = re.compile(r'(//|/\*)')
  113. rxStrings = re.compile(r'(\'|\").*?((?<!\\)\1)')
  114. rxBraces = re.compile(r'(\(|\)|\{|\}|\[|\])')
  115. rxStatementEndOrBlockBegin = re.compile(r'(\;|\{)')
  116. rxLineContinued = re.compile(r'.*\\$')
  117. rxVerifyArguments = re.compile(r'\s*//\s*\:FXC_VERIFY_ARGUMENTS\:\s+(.*)')
  118. rxVerifierTestMethod = re.compile(r'TEST_F\(VerifierTest,\s*(\w+)\)\s*')
  119. rxVerifierTestCheckFile = re.compile(r'CheckVerifiesHLSL\s*\(\s*L?\"([^"]+)"\s*\)')
  120. rxVerifyAst = re.compile(r'^\s*(\/\*verify\-ast)\s*$') # must start with line containing only "/*verify-ast"
  121. rxEndVerifyAst = re.compile(r'^\s*\*\/\s*$') # ends with line containing only "*/"
  122. rxAstSourceLocation = re.compile(
  123. r'''\<(?:(?P<Invalid>\<invalid\ sloc\>) |
  124. (?:
  125. (?:(?:(?P<FromFileLine>line|\S*):(?P<FromLine>\d+):(?P<FromLineCol>\d+)) |
  126. col:(?P<FromCol>\d+)
  127. )
  128. (?:,\s+
  129. (?:(?:(?P<ToFileLine>line|\S*):(?P<ToLine>\d+):(?P<ToLineCol>\d+)) |
  130. col:(?P<ToCol>\d+)
  131. )
  132. )?
  133. )
  134. )\>''',
  135. re.VERBOSE)
  136. rxAstHexAddress = re.compile(r'\b(0x[0-9a-f]+) ?')
  137. rxAstNode = re.compile(r'((?:\<\<\<NULL\>\>\>)|(?:\w+))\s*(.*)')
  138. # matches ignored portion of line for first AST node in subgraph to match
  139. rxAstIgnoredIndent = re.compile(r'^(\s+|\||\`|\-)*')
  140. # The purpose of StripComments and CountBraces is to be used when commenting lines of code out to allow
  141. # Fxc testing to continue even when it doesn't recover as well as clang. Some error lines are on the
  142. # beginning of a function, where commenting just that line will comment out the beginning of the function
  143. # block, but not the body or end of the block, producing invalid syntax. Here's an example:
  144. # void foo(error is here) { /* expected-error {{some expected clang error}} */
  145. # return;
  146. # }
  147. # If the first line is commented without the rest of the function, it will be incorrect code.
  148. # So the intent is to detect when the line being commented out results in an unbalanced brace matching.
  149. # Then these functions will be used to comment additional lines until the braces match again.
  150. # It's simple and won't handle the general case, but should handle the cases in the test files, and if
  151. # not, the tests should be easily modifyable to work with it.
  152. # This still does not handle preprocessor directives, or escaped characters (like line ends or escaped
  153. # quotes), or other cases that a real parser would handle.
  154. def StripComments(line, multiline_comment_continued = False):
  155. "Remove comments from line, returns stripped line and multiline_comment_continued if a multiline comment continues beyond the line"
  156. if multiline_comment_continued:
  157. # in multiline comment, only look for end of that
  158. idx = line.find('*/')
  159. if idx < 0:
  160. return '', True
  161. return StripComments(line[idx+2:])
  162. # look for start of multiline comment or eol comment:
  163. m = rxCommentStart.search(line)
  164. if m:
  165. if m.group(1) == '/*':
  166. line_end, multiline_comment_continued = StripComments(line[m.end(1):], True)
  167. return line[:m.start(1)] + line_end, multiline_comment_continued
  168. elif m.group(1) == '//':
  169. return line[:m.start(1)], False
  170. return line, False
  171. def CountBraces(line, bracestacks):
  172. m = rxStrings.search(line)
  173. if m:
  174. CountBraces(line[:m.start(1)], bracestacks)
  175. CountBraces(line[m.end(2):], bracestacks)
  176. return
  177. for b in rxBraces.findall(line):
  178. if b in '()':
  179. bracestacks['()'] = bracestacks.get('()', 0) + ((b == '(') and 1 or -1)
  180. elif b in '{}':
  181. bracestacks['{}'] = bracestacks.get('{}', 0) + ((b == '{') and 1 or -1)
  182. elif b in '[]':
  183. bracestacks['[]'] = bracestacks.get('[]', 0) + ((b == '[') and 1 or -1)
  184. def ProcessStatementOrBlock(lines, start, fn_process):
  185. num = 0
  186. # statement_continued initialized with whether line has non-whitespace content
  187. statement_continued = not not StripComments(lines[start], False)[0].strip()
  188. # Assumes start of line is not inside multiline comment
  189. multiline_comment_continued = False
  190. bracestacks = {}
  191. while start+num < len(lines):
  192. line = lines[start+num]
  193. lines[start+num] = fn_process(line)
  194. num += 1
  195. line, multiline_comment_continued = StripComments(line, multiline_comment_continued)
  196. CountBraces(line, bracestacks)
  197. if (statement_continued and
  198. not rxStatementEndOrBlockBegin.search(line) ):
  199. continue
  200. statement_continued = False
  201. if rxLineContinued.match(line):
  202. continue
  203. if (bracestacks.get('{}', 0) < 1 and
  204. bracestacks.get('()', 0) < 1 and
  205. bracestacks.get('[]', 0) < 1 ):
  206. break
  207. return num
  208. def CommentStatementOrBlock(lines, start):
  209. def fn_process(line):
  210. return '// ' + line
  211. return ProcessStatementOrBlock(lines, start, fn_process)
  212. def ParseVerifierTestCpp():
  213. "Returns dictionary mapping Run* test name to hlsl filename by parsing VerifierTest.cpp"
  214. tests = {}
  215. FoundTest = None
  216. def fn_null(line):
  217. return line
  218. def fn_process(line):
  219. searching = FoundTest is not None
  220. if searching:
  221. m = rxVerifierTestCheckFile.search(line)
  222. if m:
  223. tests[FoundTest] = m.group(1)
  224. searching = False
  225. return line
  226. with open(HlslVerifierTestCpp, 'rt') as f:
  227. lines = f.readlines()
  228. start = 0
  229. while start < len(lines):
  230. m = rxVerifierTestMethod.search(lines[start])
  231. if m:
  232. FoundTest = m.group(1)
  233. start += ProcessStatementOrBlock(lines, start, fn_process)
  234. if FoundTest not in tests:
  235. print('Could not parse file for test %s' % FoundTest)
  236. FoundTest = None
  237. else:
  238. start += ProcessStatementOrBlock(lines, start, fn_null)
  239. return tests
  240. class SourceLocation(object):
  241. def __init__(self, line=None, **kwargs):
  242. if not kwargs:
  243. self.Invalid = '<invalid sloc>'
  244. return
  245. for key, value in kwargs.items():
  246. try: value = int(value)
  247. except: pass
  248. setattr(self, key, value)
  249. if line and not self.FromLine:
  250. self.FromLine = line
  251. self.FromCol = self.FromCol or self.FromLineCol
  252. self.ToCol = self.ToCol or self.ToLineCol
  253. def Offset(self, offset):
  254. "Offset From/To Lines by specified value"
  255. if self.Invalid:
  256. return
  257. if self.FromLine:
  258. self.FromLine = self.FromLine + offset
  259. if self.ToLine:
  260. self.ToLine = self.ToLine + offset
  261. def ToStringAtLine(self, line):
  262. "convert to string relative to specified line"
  263. if self.Invalid:
  264. sloc = self.Invalid
  265. else:
  266. if self.FromLine and line != self.FromLine:
  267. sloc = 'line:%d:%d' % (self.FromLine, self.FromCol)
  268. line = self.FromLine
  269. else:
  270. sloc = 'col:%d' % self.FromCol
  271. if self.ToCol:
  272. if self.ToLine and line != self.ToLine:
  273. sloc += ', line:%d:%d' % (self.ToLine, self.ToCol)
  274. else:
  275. sloc += ', col:%d' % self.ToCol
  276. return '<' + sloc + '>'
  277. class AstNode(object):
  278. def __init__(self, name, sloc, prefix, text, indent=''):
  279. self.name, self.sloc, self.prefix, self.text, self.indent = name, sloc, prefix, text, indent
  280. self.children = []
  281. def ToStringAtLine(self, line):
  282. "convert to string relative to specified line"
  283. if self.name == '<<<NULL>>>':
  284. return self.name
  285. return ('%s %s%s %s' % (self.name, self.prefix, self.sloc.ToStringAtLine(line), self.text)).strip()
  286. def WalkAstChildren(ast_root):
  287. "yield each child node in the ast tree in depth-first order"
  288. for node in ast_root.children:
  289. yield node
  290. for child in WalkAstChildren(node):
  291. yield child
  292. def WriteAstSubtree(ast_root, line, indent=''):
  293. output = []
  294. output.append(indent + ast_root.ToStringAtLine(line))
  295. if not ast_root.sloc.Invalid and ast_root.sloc.FromLine:
  296. line = ast_root.sloc.FromLine
  297. root_indent_len = len(ast_root.indent)
  298. for child in WalkAstChildren(ast_root):
  299. output.append(indent + child.indent[root_indent_len:] + child.ToStringAtLine(line))
  300. if not child.sloc.Invalid and child.sloc.FromLine:
  301. line = child.sloc.FromLine
  302. return output
  303. def FindAstNodesByLine(ast_root, line):
  304. nodes = []
  305. if not ast_root.sloc.Invalid and ast_root.sloc.FromLine == line:
  306. return [ast_root]
  307. if not ast_root.sloc.Invalid and ast_root.sloc.ToLine and ast_root.sloc.ToLine < line:
  308. return []
  309. for child in ast_root.children:
  310. sub_nodes = FindAstNodesByLine(child, line)
  311. if sub_nodes:
  312. nodes += sub_nodes
  313. return nodes
  314. def ParseAst(astlines):
  315. cur_line = 0 # current source line
  316. root_node = None
  317. ast_stack = [] # stack of nodes and column numbers so we can pop the right number of nodes up the stack
  318. i = 0 # ast line index
  319. def push(node, col):
  320. if ast_stack:
  321. cur_node, prior_col = ast_stack[-1]
  322. cur_node.children.append(node)
  323. ast_stack.append((node, col))
  324. def popto(col):
  325. cur_node, prior_col = ast_stack[-1]
  326. while ast_stack and col <= prior_col:
  327. ast_stack.pop()
  328. cur_node, prior_col = ast_stack[-1]
  329. assert ast_stack
  330. def parsenode(text, indent):
  331. m = rxAstNode.match(text)
  332. if m:
  333. name = m.group(1)
  334. text = text[m.end(1):].strip()
  335. else:
  336. print('rxAstNode match failed on:\n %s' % text)
  337. return AstNode('ast-parse-failed', SourceLocation(), '', '', indent)
  338. text = rxAstHexAddress.sub('', text).strip()
  339. m = rxAstSourceLocation.search(text)
  340. if m:
  341. prefix = text[:m.start()]
  342. sloc = SourceLocation(cur_line, **m.groupdict())
  343. text = text[m.end():].strip()
  344. else:
  345. prefix = ''
  346. sloc = SourceLocation()
  347. return AstNode(name, sloc, prefix, text, indent)
  348. # Look for TranslationUnitDecl and start from there
  349. while i < len(astlines):
  350. text = astlines[i]
  351. if text.startswith('TranslationUnitDecl'):
  352. root_node = parsenode(text, '')
  353. push(root_node, 0)
  354. break
  355. i += 1
  356. i += 1
  357. # gather ast nodes
  358. while i < len(astlines):
  359. line = astlines[i]
  360. # get starting column and update stack
  361. m = rxAstIgnoredIndent.match(line)
  362. indent = ''
  363. col = 0
  364. if m:
  365. indent = m.group(0)
  366. col = m.end()
  367. if col == 0:
  368. break # at this point we should be done parsing the translation unit!
  369. popto(col)
  370. # parse and add the node
  371. node = parsenode(line[col:], indent)
  372. if not node:
  373. print('error parsing line %d:\n%s' % (i+1, line))
  374. assert False
  375. push(node, col)
  376. # update current source line
  377. sloc = node.sloc
  378. if not sloc.Invalid and sloc.FromLine:
  379. cur_line = sloc.FromLine
  380. i += 1
  381. return root_node
  382. class File(object):
  383. def __init__(self, filename):
  384. self.filename = filename
  385. self.expected = {} # {line_num: [('error' or 'warning', 'error or warning message'), ...], ...}
  386. self.unexpected = {} # {line_num: [('error' or 'warning', 'error or warning message'), ...], ...}
  387. self.last_diag_col = None
  388. def AddExpected(self, line_num, ew, message):
  389. self.expected.setdefault(line_num, []).append((ew, message))
  390. def AddUnexpected(self, line_num, ew, message):
  391. self.unexpected.setdefault(line_num, []).append((ew, message))
  392. def MatchDiags(self, line, diags=[], prefix='expected', matchall=False):
  393. diags = diags[:]
  394. diag_col = None
  395. matches = []
  396. for m in rxDiag.finditer(line):
  397. if diag_col is None:
  398. diag_col = m.start()
  399. self.last_diag_col = diag_col
  400. if m.group(2) == prefix:
  401. pattern = m.groups()[2:4]
  402. for idx, (ew, message) in enumerate(diags):
  403. if pattern == (ew, message):
  404. matches.append(m)
  405. break
  406. else:
  407. if matchall:
  408. matches.append(m)
  409. continue
  410. del diags[idx]
  411. return sorted(matches, key=lambda m: m.start()), diags, diag_col
  412. def RemoveDiags(self, line, diags, prefix='expected', removeall=False):
  413. """Removes expected-* diags from line, returns result_line, remaining_diags, diag_col
  414. Where, result_line is the line without the matching diagnostics,
  415. remaining is the list of diags not found on the line,
  416. diag_col is the column of the first diagnostic found on the line.
  417. """
  418. matches, diags, diag_col = self.MatchDiags(line, diags, prefix, removeall)
  419. for m in reversed(matches):
  420. line = line[:m.start()] + line[m.end():]
  421. return line, diags, diag_col
  422. def AddDiags(self, line, diags, diag_col=None, prefix='expected'):
  423. "Adds expected-* diags to line."
  424. if diags:
  425. if diag_col is None:
  426. if self.last_diag_col is not None and self.last_diag_col-3 > len(line):
  427. diag_col = self.last_diag_col
  428. else:
  429. diag_col = max(len(line) + 7, 63) # 4 spaces + '/* ' or at column 63, whichever is greater
  430. line = line + (' ' * ((diag_col - 3) - len(line))) + '/* */'
  431. for ew, message in reversed(diags):
  432. line = line[:diag_col] + ('%s-%s {{%s}} ' % (prefix, ew, message)) + line[diag_col:]
  433. return line.rstrip()
  434. def SortDiags(self, line):
  435. matches = list(rxDiag.finditer(line))
  436. if matches:
  437. for m in sorted(matches, key=lambda m: m.start(), reverse=True):
  438. line = line[:m.start()] + line[m.end():]
  439. diag_col = m.start()
  440. for m in sorted(matches, key=lambda m: m.groups()[1:], reverse=True):
  441. line = line[:diag_col] + ('%s-%s {{%s}} ' % m.groups()[1:]) + line[diag_col:]
  442. return line.rstrip()
  443. def OutputResult(self):
  444. temp_filename = os.path.expandvars(r'${TEMP}\%s' % os.path.split(self.filename)[1])
  445. with open(self.filename, 'rt') as fin:
  446. with open(temp_filename+'.result', 'wt') as fout:
  447. line_num = 0
  448. for line in fin.readlines():
  449. if line[-1] == '\n':
  450. line = line[:-1]
  451. line_num += 1
  452. line, expected, diag_col = self.RemoveDiags(line, self.expected.get(line_num, []))
  453. for ew, message in expected:
  454. print('Error: Line %d: Could not find: expected-%s {{%s}}!!' % (line_num, ew, message))
  455. line = self.AddDiags(line, self.unexpected.get(line_num, []), diag_col)
  456. line = self.SortDiags(line)
  457. fout.write(line + '\n')
  458. def TryFxc(self, result_filename=None):
  459. temp_filename = os.path.expandvars(r'${TEMP}\%s' % os.path.split(self.filename)[1])
  460. if result_filename is None:
  461. result_filename = temp_filename + '.fxc'
  462. inlines = []
  463. with open(self.filename, 'rt') as fin:
  464. for line in fin.readlines():
  465. if line[-1] == '\n':
  466. line = line[:-1]
  467. inlines.append(line)
  468. verify_arguments = None
  469. for line in inlines:
  470. m = rxVerifyArguments.search(line)
  471. if m:
  472. verify_arguments = m.group(1)
  473. print('Found :FXC_VERIFY_ARGUMENTS: %s' % verify_arguments)
  474. break
  475. # result will hold the final result after adding fxc error messages
  476. # initialize it by removing all the expected diagnostics
  477. result = [(line, None, False) for line in inlines]
  478. for n, (line, diag_col, expected) in enumerate(result):
  479. line, diags, diag_col = self.RemoveDiags(line, [], prefix='fxc', removeall=True)
  480. matches, diags, diag_col2 = self.MatchDiags(line, [], prefix='expected', matchall=True)
  481. if matches:
  482. expected = True
  483. ## if diag_col is None:
  484. ## diag_col = diag_col2
  485. ## elif diag_col2 < diag_col:
  486. ## diag_col = diag_col2
  487. result[n] = (line, diag_col, expected)
  488. # commented holds the version that gets progressively commented as fxc reports errors
  489. commented = inlines[:]
  490. # diags_by_line is a dictionary of a set of errors and warnings keyed off line_num
  491. diags_by_line = {}
  492. while True:
  493. with open(temp_filename+'.fxc_temp', 'wt') as fout:
  494. fout.write('\n'.join(commented))
  495. if verify_arguments is None:
  496. fout.write("\n[numthreads(1,1,1)] void _test_main() { }\n")
  497. if verify_arguments is None:
  498. args = '/E _test_main /T cs_5_1'
  499. else:
  500. args = verify_arguments
  501. os.system('%s /nologo "%s.fxc_temp" %s /DVERIFY_FXC=1 /Fo "%s.fxo" /Fe "%s.err" 1> "%s.log" 2>&1' %
  502. (FxcPath, temp_filename, args, temp_filename, temp_filename, temp_filename))
  503. with open(temp_filename+'.err', 'rt') as f:
  504. errors = [m for m in map(rxFxcErr.match, f.readlines()) if m]
  505. errors = sorted(errors, key=lambda m: int(m.group(2)))
  506. first_error = None
  507. for m in errors:
  508. line_num = int(m.group(2))
  509. if not first_error and m.group(5) == 'error':
  510. first_error = line_num
  511. elif first_error and line_num > first_error:
  512. break
  513. diags_by_line.setdefault(line_num, set()).add((m.group(5), m.group(6) + ': ' + m.group(7)))
  514. if first_error and first_error <= len(commented):
  515. CommentStatementOrBlock(commented, first_error-1)
  516. else:
  517. break
  518. # Add diagnostic messages from fxc to result:
  519. self.last_diag_col = None
  520. for i, (line, diag_col, expected) in enumerate(result):
  521. line_num = i + 1
  522. if diag_col:
  523. self.last_diag_col = diag_col
  524. diags = diags_by_line.get(line_num, set())
  525. if not diags:
  526. if expected:
  527. diags.add(('pass', ''))
  528. else:
  529. continue
  530. diags = sorted(list(diags))
  531. line = self.SortDiags(self.AddDiags(line, diags, diag_col, prefix='fxc'))
  532. result[i] = line, diag_col, expected
  533. with open(result_filename, 'wt') as f:
  534. f.write('\n'.join(map(lambda (line, diag_col, expected): line, result)))
  535. def TryAst(self, result_filename=None):
  536. temp_filename = os.path.expandvars(r'${TEMP}\%s' % os.path.split(self.filename)[1])
  537. if result_filename is None:
  538. result_filename = temp_filename + '.ast'
  539. try: os.unlink(temp_filename+'.ast_dump')
  540. except: pass
  541. try: os.unlink(result_filename)
  542. except: pass
  543. ## result = os.system('%s\\clang.exe -cc1 -fsyntax-only -ast-dump %s 1>"%s.ast_dump" 2>"%s.log"' %
  544. result = os.system('%s\\dxc.exe -ast-dump %s -E main -T ps_5_0 1>"%s.ast_dump" 2>"%s.log"' %
  545. (HlslBinDir, self.filename, temp_filename, temp_filename))
  546. # dxc dumps ast even if there exists any syntax error. If there is any error, dxc returns some nonzero errorcode.
  547. if not os.path.isfile(temp_filename+'.ast_dump'):
  548. print('ast-dump failed, see log:\n %s.log' % (temp_filename))
  549. return
  550. ## elif result:
  551. ## print('ast-dump succeeded, but exited with error code %d, see log:\n %s.log' % (result, temp_filename))
  552. astlines = []
  553. with open(temp_filename+'.ast_dump', 'rt') as fin:
  554. for line in fin.readlines():
  555. if line[-1] == '\n':
  556. line = line[:-1]
  557. astlines.append(line)
  558. try:
  559. ast_root = ParseAst(astlines)
  560. except:
  561. print('ParseAst failed on "%s"' % (temp_filename + '.ast_dump'))
  562. raise
  563. inlines = []
  564. with open(self.filename, 'rt') as fin:
  565. for line in fin.readlines():
  566. if line[-1] == '\n':
  567. line = line[:-1]
  568. inlines.append(line)
  569. outlines = []
  570. i = 0
  571. while i < len(inlines):
  572. line = inlines[i]
  573. outlines.append(line)
  574. m = rxVerifyAst.match(line)
  575. if m:
  576. indent = line[:m.start(1)] + ' '
  577. # at this point i is the ONE based source line number
  578. # (since it's one past the line we want to verify in zero based index)
  579. ast_nodes = FindAstNodesByLine(ast_root, i)
  580. if not ast_nodes:
  581. outlines += [indent + 'No matching AST found for line!']
  582. else:
  583. for ast in ast_nodes:
  584. outlines += WriteAstSubtree(ast, i, indent)
  585. while i+1 < len(inlines) and not rxEndVerifyAst.match(inlines[i+1]):
  586. i += 1
  587. i += 1
  588. with open(result_filename, 'wt') as f:
  589. f.write('\n'.join(outlines))
  590. def ProcessVerifierOutput(lines):
  591. files = {}
  592. cur_filename = None
  593. cur_test = None
  594. state = 'WaitingForFile'
  595. ew = ''
  596. expected = None
  597. for line in lines:
  598. if not line:
  599. continue
  600. if line[-1] == '\n':
  601. line = line[:-1]
  602. m = rxRUN.match(line)
  603. if m:
  604. cur_test = m.group(1)
  605. m = rxForProgram.match(line)
  606. if m:
  607. cur_filename = m.group(1)
  608. files[cur_filename] = File(cur_filename)
  609. state = 'WaitingForCategory'
  610. continue
  611. if state is 'WaitingForFile':
  612. m = rxEndGroup.match(line)
  613. if m and m.group(2) == 'Failed':
  614. # This usually happens when compiler crashes
  615. print('Fatal Error: test %s failed without verifier results.' % cur_test)
  616. if state is 'WaitingForCategory' or state is 'ReadingErrors':
  617. m = rxExpected.match(line)
  618. if m:
  619. ew = m.group(1)
  620. expected = m.group(2) == 'expected but not seen'
  621. state = 'ReadingErrors'
  622. continue
  623. if state is 'ReadingErrors':
  624. m = rxDiagReport.match(line)
  625. if m:
  626. line_num = int(m.group(2))
  627. if expected:
  628. files[cur_filename].AddExpected(line_num, ew, m.group(3))
  629. else:
  630. files[cur_filename].AddUnexpected(line_num, ew, m.group(3))
  631. continue
  632. for f in files.values():
  633. f.OutputResult()
  634. return files
  635. def maybe_compare(filename1, filename2):
  636. with open(filename1, 'rt') as fbefore:
  637. with open(filename2, 'rt') as fafter:
  638. before = fbefore.read()
  639. after = fafter.read()
  640. if before.strip() != after.strip():
  641. print('Differences found. Compare:\n %s\nwith:\n %s' % (filename1, filename2))
  642. if DiffTool:
  643. os.system('%s %s %s' % (DiffTool, filename1, filename2))
  644. return True
  645. return False
  646. def PrintUsage():
  647. print(__doc__)
  648. print('Available tests and corresponding files:')
  649. tests = sorted(VerifierTests.keys())
  650. width = len(max(tests, key=len))
  651. for name in tests:
  652. print((' %%-%ds %%s' % width) % (name, VerifierTests[name]))
  653. print('Tests incompatible with fxc mode:')
  654. for name in fxcExcludedTests:
  655. print(' %s' % name)
  656. def RunVerifierTest(test, HlslDataDir=HlslDataDir):
  657. import codecs
  658. temp_filename = os.path.expandvars(r'${TEMP}\VerifierHelper_temp.txt')
  659. cmd = ('te %s\\clang-hlsl-tests.dll /p:"HlslDataDir=%s" /name:VerifierTest::%s > %s' %
  660. (HlslBinDir, HlslDataDir, test, temp_filename))
  661. print(cmd)
  662. os.system(cmd) # TAEF test
  663. # TAEF outputs unicode, so read as binary and convert:
  664. with open(temp_filename, 'rb') as f:
  665. return codecs.decode(f.read(), 'UTF-16').replace(u'\x7f', u'').replace(u'\r\n', u'\n').splitlines()
  666. def main(*args):
  667. global VerifierTests
  668. try:
  669. VerifierTests = ParseVerifierTestCpp()
  670. except:
  671. print('Unable to parse tests from VerifierTest.cpp; using defaults')
  672. if len(args) < 1 or (args[0][0] in '-/' and args[0][1:].lower() in ('h', '?', 'help')):
  673. PrintUsage()
  674. return -1
  675. mode = args[0]
  676. if mode == 'fxc':
  677. allFxcTests = sorted(filter(lambda key: key not in fxcExcludedTests, VerifierTests.keys()))
  678. if args[1] == '*':
  679. tests = allFxcTests
  680. else:
  681. if args[1] not in allFxcTests:
  682. PrintUsage()
  683. return -1
  684. tests = [args[1]]
  685. differences = False
  686. for test in tests:
  687. print('---- %s ----' % test)
  688. filename = os.path.join(HlslDataDir, VerifierTests[test])
  689. result_filename = os.path.expandvars(r'${TEMP}\%s.fxc' % os.path.split(filename)[1])
  690. File(filename).TryFxc()
  691. differences = maybe_compare(filename, result_filename) or differences
  692. if not differences:
  693. print('No differences found!')
  694. elif mode == 'clang':
  695. if args[1] != '*' and args[1] not in VerifierTests:
  696. PrintUsage()
  697. return -1
  698. files = ProcessVerifierOutput(RunVerifierTest(args[1]))
  699. differences = False
  700. if files:
  701. for f in files.values():
  702. if f.expected or f.unexpected:
  703. result_filename = os.path.expandvars(r'${TEMP}\%s.result' % os.path.split(f.filename)[1])
  704. differences = maybe_compare(f.filename, result_filename) or differences
  705. if not differences:
  706. print('No differences found!')
  707. elif mode == 'ast':
  708. allAstTests = sorted(VerifierTests.keys())
  709. if args[1] == '*':
  710. tests = allAstTests
  711. else:
  712. if args[1] not in allAstTests:
  713. PrintUsage()
  714. return -1
  715. tests = [args[1]]
  716. differences = False
  717. for test in tests:
  718. print('---- %s ----' % test)
  719. filename = os.path.join(HlslDataDir, VerifierTests[test])
  720. result_filename = os.path.expandvars(r'${TEMP}\%s.ast' % os.path.split(filename)[1])
  721. File(filename).TryAst()
  722. differences = maybe_compare(filename, result_filename) or differences
  723. if not differences:
  724. print('No differences found!')
  725. elif mode == 'all':
  726. allTests = sorted(VerifierTests.keys())
  727. if args[1] == '*':
  728. tests = allTests
  729. else:
  730. if args[1] not in allTests:
  731. PrintUsage()
  732. return -1
  733. tests = [args[1]]
  734. # Do clang verifier tests, updating source file paths for changed files:
  735. sourceFiles = dict([(VerifierTests[test], os.path.join(HlslDataDir, VerifierTests[test])) for test in tests])
  736. files = ProcessVerifierOutput(RunVerifierTest(args[1]))
  737. if files:
  738. for f in files.values():
  739. if f.expected or f.unexpected:
  740. name = os.path.split(f.filename)[1]
  741. sourceFiles[name] = os.path.expandvars(r'${TEMP}\%s.result' % name)
  742. # update verify-ast blocks:
  743. for name, sourceFile in sourceFiles.items():
  744. result_filename = os.path.expandvars(r'${TEMP}\%s.ast' % name)
  745. File(sourceFile).TryAst(result_filename)
  746. sourceFiles[name] = result_filename
  747. # now do fxc verification and final comparison
  748. differences = False
  749. fxcExcludedFiles = [VerifierTests[test] for test in fxcExcludedTests]
  750. width = len(max(tests, key=len))
  751. for test in tests:
  752. name = VerifierTests[test]
  753. sourceFile = sourceFiles[name]
  754. print(('Test %%-%ds - %%s' % width) % (test, name))
  755. result_filename = os.path.expandvars(r'${TEMP}\%s.fxc' % name)
  756. if name not in fxcExcludedFiles:
  757. File(sourceFile).TryFxc(result_filename)
  758. sourceFiles[name] = result_filename
  759. differences = maybe_compare(os.path.join(HlslDataDir, name), sourceFiles[name]) or differences
  760. if not differences:
  761. print('No differences found!')
  762. else:
  763. PrintUsage()
  764. return -1
  765. return 0
  766. if __name__ == '__main__':
  767. sys.exit(main(*sys.argv[1:]))