2
0

VerifierHelper.py 33 KB

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