swr: [rasterizer codegen] add cmdline to archrast gen files
[mesa.git] / src / gallium / drivers / swr / rasterizer / codegen / gen_common.py
1 # Copyright (C) 2014-2016 Intel Corporation. All Rights Reserved.
2 #
3 # Permission is hereby granted, free of charge, to any person obtaining a
4 # copy of this software and associated documentation files (the "Software"),
5 # to deal in the Software without restriction, including without limitation
6 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
7 # and/or sell copies of the Software, and to permit persons to whom the
8 # Software is furnished to do so, subject to the following conditions:
9 #
10 # The above copyright notice and this permission notice (including the next
11 # paragraph) shall be included in all copies or substantial portions of the
12 # Software.
13 #
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20 # IN THE SOFTWARE.
21
22 # Python source
23 from __future__ import print_function
24 import os
25 import sys
26 import argparse
27 from mako.template import Template
28 from mako.exceptions import RichTraceback
29
30
31 #==============================================================================
32 class MakoTemplateWriter:
33 '''
34 MakoTemplateWriter - Class (namespace) for functions to generate strings
35 or files using the Mako template module.
36
37 See http://docs.makotemplates.org/en/latest/ for
38 mako documentation.
39 '''
40
41 @staticmethod
42 def to_string(template_filename, **kwargs):
43 '''
44 Write template data to a string object and return the string
45 '''
46 from mako.template import Template
47 from mako.exceptions import RichTraceback
48
49 try:
50 template = Template(filename=template_filename)
51 # Split + Join fixes line-endings for whatever platform you are using
52 return '\n'.join(template.render(**kwargs).splitlines())
53 except:
54 traceback = RichTraceback()
55 for (filename, lineno, function, line) in traceback.traceback:
56 print('File %s, line %s, in %s' % (filename, lineno, function))
57 print(line, '\n')
58 print('%s: %s' % (str(traceback.error.__class__.__name__), traceback.error))
59
60 @staticmethod
61 def to_file(template_filename, output_filename, **kwargs):
62 '''
63 Write template data to a file
64 '''
65 with open(output_filename, 'w') as outfile:
66 print(MakoTemplateWriter.to_string(template_filename, **kwargs), file=outfile)
67
68
69 #==============================================================================
70 class ArgumentParser(argparse.ArgumentParser):
71 '''
72 Subclass of argparse.ArgumentParser
73
74 Allow parsing from command files that start with @
75 Example:
76 >bt run @myargs.txt
77
78 Contents of myargs.txt:
79 -m <machine>
80 --target cdv_win7
81
82 The below function allows multiple args to be placed on the same text-file line.
83 The default is one token per line, which is a little cumbersome.
84
85 Also allow all characters after a '#' character to be ignored.
86 '''
87
88 #==============================================================================
89 class _HelpFormatter(argparse.RawTextHelpFormatter):
90 ''' Better help formatter for argument parser '''
91
92 def _split_lines(self, text, width):
93 ''' optimized split lines algorighm, indents split lines '''
94 lines = text.splitlines()
95 out_lines = []
96 if len(lines):
97 out_lines.append(lines[0])
98 for line in lines[1:]:
99 out_lines.append(' ' + line)
100 return out_lines
101
102 #==============================================================================
103 def __init__(self, *args, **kwargs):
104 ''' Constructor. Compatible with argparse.ArgumentParser(),
105 but with some modifications for better usage and help display.
106 '''
107 super(ArgumentParser, self).__init__(
108 *args,
109 fromfile_prefix_chars='@',
110 formatter_class=ArgumentParser._HelpFormatter,
111 **kwargs)
112
113 #==========================================================================
114 def convert_arg_line_to_args(self, arg_line):
115 ''' convert one line of parsed file to arguments '''
116 arg_line = arg_line.split('#', 1)[0]
117 if sys.platform == 'win32':
118 arg_line = arg_line.replace('\\', '\\\\')
119 for arg in shlex.split(arg_line):
120 if not arg.strip():
121 continue
122 yield arg
123
124 #==========================================================================
125 def _read_args_from_files(self, arg_strings):
126 ''' read arguments from files '''
127 # expand arguments referencing files
128 new_arg_strings = []
129 for arg_string in arg_strings:
130
131 # for regular arguments, just add them back into the list
132 if arg_string[0] not in self.fromfile_prefix_chars:
133 new_arg_strings.append(arg_string)
134
135 # replace arguments referencing files with the file content
136 else:
137 filename = arg_string[1:]
138
139 # Search in sys.path
140 if not os.path.exists(filename):
141 for path in sys.path:
142 filename = os.path.join(path, arg_string[1:])
143 if os.path.exists(filename):
144 break
145
146 try:
147 args_file = open(filename)
148 try:
149 arg_strings = []
150 for arg_line in args_file.read().splitlines():
151 for arg in self.convert_arg_line_to_args(arg_line):
152 arg_strings.append(arg)
153 arg_strings = self._read_args_from_files(arg_strings)
154 new_arg_strings.extend(arg_strings)
155 finally:
156 args_file.close()
157 except IOError:
158 err = sys.exc_info()[1]
159 self.error(str(err))
160
161 # return the modified argument list
162 return new_arg_strings