VerifierHelper.py 33 KB

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