VerifierHelper.py 33 KB

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