VerifierHelper.py 35 KB

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