doil/utils/omniidl_be/doil/yat.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 #
3 # @brief YAT: YAml Template text processor
4 # @date $Date: 2008-02-09 20:04:27 $
5 # @author Norkai Ando <n-ando@aist.go.jp>
6 #
7 # Copyright (C) 2008 Noriaki Ando, All rights reserved.
8 #
9 # $Id: yat.py 775 2008-07-28 16:14:45Z n-ando $
10 #
11 
12 #
13 # Usage:
14 #------------------------------------------------------------
15 # import yaml
16 # import yat
17 #
18 # dict = yaml.load(open(filename, "r").read())
19 # t = yat.Template(template, "\[", "\]")
20 # result = t.generate(dict)
21 #------------------------------------------------------------
22 #
23 # 1. Simple directive:
24 # [dictionary_key]
25 #
26 # Nested dictionaries can be expressed by dotted expression.
27 #
28 # example:
29 # dict = {"a": "This is a",
30 # "b": {"1": "This is b.1",
31 # "2": "This is b.2"}
32 # }
33 #
34 # template:
35 # [a]
36 #
37 # [b.1]
38 #
39 # [b.2]
40 #
41 # result:
42 # This is a
43 # This is b.1
44 # This is b.2
45 #
46 #
47 # 2. "for" directive:
48 # [for key in list] statement [endfor]
49 # [for-inv key in list] statement [endfor] (inverted)
50 #
51 # Iterative evaluation for listed values is performed by "for" statement.
52 # In iteration at each evaluation, the value of the list is assigned to
53 # "key". The "key" also can be the nested dictionary directive.
54 #
55 # example:
56 # dict = {"list": [0, 1, 2],
57 # "listed_dict": [
58 # {"name": "x", "value": "1.0"},
59 # {"name": "y", "value": "0.2"},
60 # {"name": "z", "value": "0.1"}]}
61 #
62 # template:
63 # [for lst in list][lst], [endfor]
64 # [for-inv lst in list][lst], [endfor]
65 # [for lst in listed_dict]
66 # [lst.name]: [lst.value]
67 #
68 # [endfor]
69 #
70 # result:
71 # 1, 2, 3,
72 # 3, 2, 1
73 # x: 1.0
74 # y: 0.2
75 # x: 0.1
76 #
77 #
78 # 3. "if-index" directive:
79 # [for key in val]
80 # [if-index key is first|even|odd|last|NUMBER] statement1
81 # [elif-index key is first|even|odd|last|NUMBER] statement2
82 # [endif][endfor]
83 #
84 # "if-index" is used to specify the index of the "for" iteration.
85 # The "key" string which is defined in the "for" statement is used as index.
86 # A number or predefined directives such as "first", "even", "odd" and
87 # "last" can be used to specify the index.
88 #
89 # example:
90 # dict = {"list": [0,1,2,3,4,5,6,7,8,9,10]}
91 #
92 # template:
93 # [for key in list]
94 # [if-index key is 3] [key] is hoge!!
95 # [elif-index key is 6] [key] is foo!!
96 # [elif-index key is 9] [key] is bar!!
97 # [elif-index key is first] [key] is first
98 # [elif-index key is last] Omoro-------!!!!
99 # [elif-index key is odd] [key] is odd number
100 # [elif-index key is even] [key] is even number
101 # [endif]
102 # [endfor]
103 #
104 # result:
105 # 0 is first
106 # 1 is odd number
107 # 2 is even number
108 # 3 is hoge!!
109 # 4 is even number
110 # 5 is odd number
111 # 6 is foo!!
112 # 7 is odd number
113 # 8 is even number
114 # 9 is bar!!
115 # Omoro-------!!!!
116 #
117 #
118 # 4. "if" directive:
119 # [if key is "string"] text1 [else] text2 [endif]
120 # [if key is 'string'] text1 [else] text2 [endif]
121 # [if key is value] text1 [else] text2 [endif]
122 # If "key" is [value] or "string", "text1" appears,
123 # otherwise "text2" appears.
124 #
125 # example:
126 # dict = {"key1": "a", "key2": "b", "key3": "a"}
127 #
128 # template:
129 # [if key1 is 'a']
130 # The key1 is "a".
131 # [elif key1 is key3]
132 # This key1 is not "a".
133 # [endif]
134 #
135 # result:
136 # The key1 is "a".
137 #
138 #
139 # 5. "if-any" directive: [if-any key1] text1 [else] text2 [endif]
140 # If the "key1" exists in the dictionary, "text1" appears, otherwise
141 # "text2" appears.
142 #
143 # example:
144 # dict = {"key1": "a", "key2": "b"}
145 #
146 # template:
147 # [if-any key1]
148 # key1 exists.
149 # [endif][if-any key3]
150 # key3 exists.
151 # [else]
152 # key3 does not exists.
153 # [endif]
154 #
155 # result:
156 # key1 exists.
157 # key3 does not exists.
158 #
159 #
160 # 6. bracket and comment:
161 # [[] is left bracket if begin mark is "["
162 # [# comment ] is comment if begin/end marks are "[" and "]"
163 #
164 # example:
165 # dict = {}
166 #
167 # template:
168 # [[]bracket]
169 # [# comment]
170 #
171 # result:
172 # [bracket]
173 #
174 import string
175 import re
176 from types import StringType, IntType, FloatType, DictType, ListType, ClassType
177 import sys
178 
179 class Template:
180  """
181  usage:
182  tempalte_text = read template text from file
183  dictionary = create dictionaly by using yaml
184  t = Template(tempalte_text)
185  generated_text = t.generate(dictionary)
186 
187  """
188 
189  def __init__(self, template, begin_mark="\[", end_mark="\]"):
190  self.__procs = [self.__proc_text,
191  self.__proc_cmd,
192  self.__proc_bracket]
193  self.template = template
194 
195  # regular expression to devide text into DIRECTIVE, BRACKET and COMMENT
196  #
197  # default:
198  # START_MARK: "["
199  # END_MARK : "]"
200  # -> START_MARK and END_MARK can be given in ctor
201  #
202  # ITEM: (?:"(?:[^\\"]|\\.)*"|[-\w.]+)
203  # \[(ITEM(?: +ITEM)*)\]|(\[\[\])|\[#[^\]]*\]
204  # ~~~~~~~~(1)~~~~~~ ~~(2)~~~ ~~~(3)~~~~~
205  # (1) COMMAND : '[' ITEM (whitespace ITEM)* ']
206  # ITEM : STRING | NAME
207  # STRING : '"' (not-slash-or-dquote | '\' anychar)* '"'
208  # NAME : (alphanum | '_' | '-' | '.')+
209  # (2) BEGIN_MARK_ESCAPE : '[[]'
210  # (3) COMMENT : '[#' not-rbracket
211  #
212  # re_item = r'(?:"(?:[^\\"]|\\.)*"|[-\w.]+)'
213  # re_command = r'\[(%s(?: +%s)*)\]' % (re_item, re_item)
214  # re_beginmark = r'\[\[\]'
215  # re_comment = r'\[#[^\]]*\]'
216  # re_parse = re.compile(r'%s|(%s)|%s'
217  # % (re_command, re_beginmark, re_comment))
218  # re_args = re.compile(r'"(?:[^\\"]|\\.)*"|[-\w.]+')
219  #
220  #
221  re_item = r'(?:"(?:[^\\"]|\\.)*"|[-\w.:]+)'
222  re_command = r'%s(%s(?: +%s)*)%s' % \
223  (begin_mark, re_item, re_item, end_mark)
224  re_bracket = r'%s%s%s' % \
225  (begin_mark, begin_mark, end_mark)
226  re_comment = r'%s#[^%s]*%s' % \
227  (begin_mark, end_mark, end_mark)
228  self.begin_mark = begin_mark.replace("\\","")
229  self.re_parse = re.compile(r'%s|(%s)|%s' % \
230  (re_command, re_bracket, re_comment))
231  self.re_args = re.compile(r'"(?:[^\\"]|\\.)*"|[-\w.:]+')
232  self.re_number = re.compile(r'[0-9]+')
233 
234  # tokenize input text
235  self.token = self.re_parse.split(self.template)
236  self.token_len = len(self.token)
237 
238  # initialize variables
239  self.script = program
240  self.indent = 4
241  self.script_level = 2
242  self.level = 0
243  self.index = 0
244  self.cmd_cxt = []
245 
246  # parse token
247  self.__parse_template(self.token)
248 
249  return
250 
251  def generate(self, dict):
252  # eval generated script
253  exec(self.script)
254  # script includes Generator class
255  gen = Generator(self.token, dict)
256  # execute generated script
257  return gen.generate()
258 
259  def get_script(self):
260  return self.script
261 
262  def __push_level(self):
263  self.level += 1
264 
265  def __pop_level(self):
266  self.level -= 1
267 
268  def __write_cmd(self, cmd):
269  tmp_cmd = self.__indent()
270  tmp_cmd += "self.set_index(%s)\n" % (self.index)
271  self.script += tmp_cmd
272  self.__write_cmd_noindex(cmd)
273 
274  def __write_cmd_noindex(self, cmd):
275  tmp_cmd = self.__indent()
276  tmp_cmd += cmd + "\n"
277  self.script += tmp_cmd
278 
279  def __parse_template(self, dict):
280  try:
281  # split into (TEXT DIRECTIVE BRACKET)* TEXT
282  self.__parse()
283  except YATException, e:
284  self.__print_error(e)
285  sys.exit(-1)
286 
287  def __indent(self):
288  indent = " " * ((self.script_level + self.level) * self.indent)
289  return indent
290 
291  def __parse(self):
292  while self.index < self.token_len:
293  self.__procs[self.index % 3]()
294  self.index += 1
295 
296  def __proc_text(self):
297  if self.token[self.index] == None:
298  return
299  cmd_text = "self.write_token(%s)" % (self.index)
300  self.__write_cmd(cmd_text)
301  return True
302 
303  def __proc_bracket(self):
304  if self.token[self.index] == None:
305  return
306  cmd_text = "self.write(\"" + self.begin_mark + "\")"
307  self.__write_cmd(cmd_text)
308  return True
309 
310  def __proc_cmd(self):
311  cmd = self.token[self.index]
312  try:
313  args = self.re_args.findall(cmd)
314  except:
315  return
316  self.del_nl_after_cmd()
317  argc = len(args)
318  if argc == 0:
319  raise InvalidDirective(self.lineno(), "_an empty directive_ ")
320 
321  # simple directive
322  if argc == 1:
323  if args[0] == "endfor":
324  self.__endfor_cmd(args)
325  return
326  elif args[0] == "else":
327  self.__else_cmd(args)
328  return
329  elif args[0] == "last":
330  self.__last_cmd(args)
331  return
332  elif args[0] == "endif":
333  self.__endif_cmd(args)
334  return
335  else:
336  self.__cmd(args)
337  return
338  elif argc == 2:
339  if args[0] == "if-any":
340  self.__if_any_cmd(args)
341  return
342  elif argc == 4: # [for key in value]
343  if args[0] == "for" and args[2] == "in":
344  self.__for_cmd(args)
345  return True
346  elif args[0] == "for-inv" and args[2] == "in":
347  self.__for_inv_cmd(args)
348  return True
349  elif args[0] == "if" and args[2] == "is":
350  self.__if_cmd(args)
351  elif args[0] == "elif" and args[2] == "is":
352  self.__elif_cmd(args)
353  elif args[0] == "if-index" and args[2] == "is":
354  self.__if_index_cmd(args)
355  elif args[0] == "elif-index" and args[2] == "is":
356  self.__elif_index_cmd(args)
357  else:
358  raise InvalidDirective(self.lineno(), cmd)
359  else:
360  raise InvalidDirective(self.lineno(), cmd)
361  return True
362 
363  def __cmd(self, args):
364  cmd_text = "self.write_dict(\"%s\")" % (args[0])
365  self.__write_cmd(cmd_text)
366 
367  #------------------------------------------------------------
368  # [for] commands
369  # - for
370  # - last
371  # - endfor
372  #------------------------------------------------------------
373  def __for_cmd(self, args):
374  """
375  The following [for] directive
376  [for tmp_key in directive]
377  is converted into the following python command.
378  for i in len(directive):
379  self.dicts.append({tmp_key: ditective[i])
380  and, endfor directive terminate as the following,
381  self.dicts.pop()
382  """
383  key = args[1]
384  directive = args[3]
385  # (key) : variable string of index variable for [for] block
386  # (key)_list: list value of specified directive
387  # (key)_len : length of the list
388  cmd_text = "%s_list = self.get_list(\"%s\")" % (key, directive)
389  self.__write_cmd(cmd_text)
390  cmd_text = "%s_len = len(%s_list)" % (key, key)
391  self.__write_cmd(cmd_text)
392  cmd_text = "for %s_index in range(len(%s_list)):" % (key, key)
393  self.__write_cmd(cmd_text)
394  self.__push_level()
395  cmd_text = "self.push_dict({\"%s\": %s_list[%s_index]})" \
396  % (key, key, key)
397  self.__write_cmd(cmd_text)
398  self.cmd_cxt.append("for")
399 
400  def __for_inv_cmd(self, args):
401  """
402  The following [for] directive
403  [for tmp_key in directive]
404  is converted into the following python command.
405  for i in len(directive):
406  self.dicts.append({tmp_key: ditective[i])
407  and, endfor directive terminate as the following,
408  self.dicts.pop()
409  """
410  key = args[1]
411  directive = args[3]
412  # (key) : variable string of index variable for [for] block
413  # (key)_list: list value of specified directive
414  # (key)_len : length of the list
415  cmd_text = "%s_list = self.get_list(\"%s\")" % (key, directive)
416  self.__write_cmd(cmd_text)
417  cmd_text = "%s_len = len(%s_list)" % (key, key)
418  self.__write_cmd(cmd_text)
419  cmd_text = "for %s_index in range(len(%s_list))[::-1]:" % (key, key)
420  self.__write_cmd(cmd_text)
421  self.__push_level()
422  cmd_text = "self.push_dict({\"%s\": %s_list[%s_index]})" \
423  % (key, key, key)
424  self.__write_cmd(cmd_text)
425  self.cmd_cxt.append("for-inv")
426 
427  def __endfor_cmd(self, args):
428  try:
429  cxt = self.cmd_cxt.pop()
430  if cxt != "for" and cxt != "for-inv":
431  raise UnmatchedBlock(self.lineno(), "endfor")
432  self.__write_cmd("self.pop_dict()")
433  self.__pop_level()
434  except:
435  print args, self.lineno()
436  raise UnmatchedBlock(self.lineno(), "endfor")
437  return
438 
439  # end of [for] commands
440  #------------------------------------------------------------
441 
442  #------------------------------------------------------------
443  # [if] commands
444  # - if
445  # - if-index
446  # - if-any
447  #------------------------------------------------------------
448  def __if_cmd(self, args):
449  """
450  The following [if] directive
451  [if directive is string]
452  is converted into the following python command.
453  if self.__get_string() == "string":
454  """
455  directive = args[1]
456  string = args[3]
457  if string[0] == '"' or string[-1] == "'" \
458  or string[0] == '"' or string[-1] == "'":
459  cmd_text = "if self.get_text(\"%s\") == %s:" % \
460  (directive, string)
461  else:
462  cmd_text = "if self.get_text(\"%s\") == self.get_text(\"%s\"):" % \
463  (directive, string)
464  self.__write_cmd(cmd_text)
465  self.__push_level()
466  self.cmd_cxt.append("if")
467  return
468 
469  def __elif_cmd(self, args):
470  if self.cmd_cxt[-1] != "if":
471  raise UnmatchedBlock(self.lineno(), "elif")
472  directive = args[1]
473  string = args[3]
474  if string[0] == '"' or string[-1] == "'" \
475  or string[0] == '"' or string[-1] == "'":
476  cmd_text = "elif self.get_text(\"%s\") == %s:" % \
477  (directive, string)
478  else:
479  cmd_text = "elif self.get_text(\"%s\") == self.get_text(\"%s\"):" % \
480  (directive, string)
481  self.__pop_level()
482  self.__write_cmd_noindex(cmd_text)
483  self.__push_level()
484  return
485 
486  # [if-index] commands
487  def __if_index_cmd(self, args):
488  # [if-index KEY is [first|even|odd|last|NUMBER]]
489  # ~~~0~~~ ~1~ 2 ~~~~~~~~~~~~~~3~~~~~~~~~~~~
490  cmdlist = {"first": "if %s_index == 0:",
491  "even" : "if (%s_index %% 2) == 0:",
492  "odd" : "if (%s_index %% 2) != 0:",
493  "last" : "if %s_index == %s_len - 1:"}
494  key = args[1]
495  cmd = args[3]
496  if len(self.re_number.findall(cmd)) == 1:
497  cmd_text = "if %s_index == %s:" % (key, cmd)
498  elif cmdlist.has_key(cmd):
499  if cmd == "last":
500  cmd_text = cmdlist[cmd] % (key,key)
501  else:
502  cmd_text = cmdlist[cmd] % (key)
503  else:
504  raise InvalidDirective(self.lineno(), ''.join(args))
505  self.__write_cmd(cmd_text)
506  self.__push_level()
507  self.cmd_cxt.append("if-index")
508 
509  def __elif_index_cmd(self, args):
510  if self.cmd_cxt[-1] != "if-index":
511  raise UnmatchedBlock(self.lineno(), "elif-index")
512  # [elif-index KEY is [first|even|odd|last|NUMBER]]
513  # ~~~0~~~ ~1~ 2 ~~~~~~~~~~~~~~3~~~~~~~~~~~~
514  cmdlist = {"first": "elif %s_index == 0:",
515  "even" : "elif (%s_index %% 2) == 0:",
516  "odd" : "elif (%s_index %% 2) != 0:",
517  "last" : "elif %s_index == %s_len - 1:"}
518  key = args[1]
519  cmd = args[3]
520  if len(self.re_number.findall(cmd)) == 1:
521  cmd_text = "elif %s_index == %s:" % (key, cmd)
522  elif cmdlist.has_key(cmd):
523  if cmd == "last":
524  cmd_text = cmdlist[cmd] % (key,key)
525  else:
526  cmd_text = cmdlist[cmd] % (key)
527  else:
528  raise InvalidDirective(self.lineno(), ' '.join(args))
529  self.__pop_level()
530  self.__write_cmd_noindex(cmd_text)
531  self.__push_level()
532 
533  # [if-any] command
534  def __if_any_cmd(self, args):
535  directive = args[1]
536  cmd_text = "if self.has_key(\"%s\"):" % (directive)
537  self.__write_cmd(cmd_text)
538  self.__push_level()
539  self.cmd_cxt.append("if-any")
540  return
541 
542  def __elif_any_cmd(self, args):
543  if self.cmd_cxt[-1] != "if-any":
544  raise UnmatchedBlock(self.lineno(), "elif-any")
545  directive = args[1]
546  cmd_text = "if self.has_key(\"%s\"):" % (directive)
547  self.__pop_level()
548  self.__write_cmd_noindex(cmd_text)
549  self.__push_level()
550  return
551 
552  # [else], [endif] commands
553  def __else_cmd(self, args):
554  if self.cmd_cxt[-1] != "if" and self.cmd_cxt[-1] != "if-index" \
555  and self.cmd_cxt[-1] != "if-any":
556  raise UnmatchedBlock(self.lineno(), "else")
557  self.__pop_level()
558  self.__write_cmd_noindex("else:")
559  self.__push_level()
560  return
561 
562  def __endif_cmd(self, args):
563  try:
564  if self.cmd_cxt[-1] != "if" and self.cmd_cxt[-1] != "if-index" \
565  and self.cmd_cxt[-1] != "if-any":
566  raise UnmatchedBlock(self.lineno(), "endif")
567  self.cmd_cxt.pop()
568  self.__pop_level()
569  except:
570  raise UnmatchedBlock(self.lineno(), "endif")
571  return
572  # end of [if] commands
573  #------------------------------------------------------------
574 
575  def __print_error(self, e):
576  print "Parse Error: line", e.lineno, "in input data"
577  print " " + ''.join(nesteditem(e.value))
578  lines = self.template.split("\n")
579  length = len(lines)
580  print "------------------------------------------------------------"
581  for i in range(1,10):
582  l = e.lineno - 6 + i
583  if l > 0 and l < length:
584  print lines[l]
585  if i == 5:
586  uline = '~'*len(lines[l])
587  print uline
588  print "------------------------------------------------------------"
589  if hasattr(e, 'context'):
590  print "Current context:"
591  print e.context
592 
593 
594  def del_nl_after_cmd(self):
595  # next text index after command
596  next = self.index + 2
597  if next > self.token_len: return
598  if self.token[next] == None: return
599  text = self.token[next]
600  tlen = len(text)
601  if tlen > 0 and text[0] == '\n':
602  self.token[next] = text[1:]
603  return
604  elif tlen > 0 and text[0] == '\r':
605  self.token[next] = text[1:]
606  return
607  elif tlen > 1 and text[0:2] == '\r\n':
608  self.token[next] = text[2:]
609 
610  def lineno(self):
611  l = 1
612  for i in range(self.index):
613  if isinstance(self.token[i], StringType):
614  l += self.token[i].count('\n')
615  for i in range(1, self.index, 3):
616  l += 1
617  return l
618 
619 
620 #------------------------------------------------------------
621 # Generator and GeneratorBase classes
622 #------------------------------------------------------------
623 program = """
624 class Generator(GeneratorBase):
625  def __init__(self, token, dict):
626  GeneratorBase.__init__(self, token, dict)
627  def generate(self):
628  try:
629  self.process()
630  except YATException, e:
631  self.print_error(e)
632  sys.exit(-1)
633  return self.text
634 
635  def process(self):
636 """
637 
639  def __init__(self, token, dict):
640  self.token = token
641  self.dicts = [dict]
642  self.index = 0
643  self.text = ""
644 
645  def print_error(self, e):
646  print "\nTemplate Generation Error: line", e.lineno, "in input data"
647  print " " + ''.join(nesteditem(e.value))
648  temp = ""
649  for i, s in enumerate(self.token):
650  if s != None:
651  if i % 3 == 1:
652  temp += "[" + s + "]\n"
653  else:
654  temp += s
655  lines = temp.split("\n")
656  length = len(lines)
657  print "Template text:"
658  print "------------------------------------------------------------"
659  for i in range(1,10):
660  l = e.lineno - 6 + i
661  if l > 0 and l < length:
662  print lines[l]
663  if i == 5:
664  uline = '~'*len(lines[l])
665  print uline
666  if hasattr(e, 'context'):
667  print "\nCurrent context:"
668  print "------------------------------------------------------------"
669  print e.context
670 
671  def set_index(self, index):
672  self.index = index
673 
674  def push_dict(self, dict):
675  self.dicts.append(dict)
676 
677  def pop_dict(self):
678  if len(self.dicts) < 2:
679  raise UnmatchedBlock(self.lineno(), "")
680  self.dicts.pop()
681 
682  def write(self, text):
683  self.text += text
684 
685  def write_dict(self, keytext):
686  self.write(self.get_text(keytext))
687 
688  def write_token(self, index):
689  self.write(self.token[index])
690 
691  def lineno(self):
692  cnt = 1
693  for i in range(0, self.index, 3):
694  if self.token[i] != None:
695  cnt += self.token[i].count('\n')
696  # count deleted '\n' after commands
697  for i in range(1, self.index, 3):
698  if self.token[i] != None:
699  cnt += 1
700  return cnt
701 
702  def get_text(self, keytext):
703  val = self.get_value(keytext)
704  if isinstance(val, StringType):
705  return val
706  if isinstance(val, IntType) or isinstance(val, FloatType):
707  return str(val)
708  raise UnexpectedData(self.lineno(), "\"" + keytext + \
709  "\" should have string, int or float value.")
710 
711  def get_list(self, keytext):
712  val = self.get_value(keytext)
713  if not isinstance(val, ListType):
714  raise UnexpectedData(self.lineno(),
715  "\"" + keytext + "\" should have list value.")
716  return val
717 
718  def has_key(self, keytext):
719  try:
720  self.get_value(keytext)
721  return True
722  except NotFound, e:
723  return False
724 
725  def get_value(self, keytext):
726  keys = keytext.split('.')
727  for i in range(len(self.dicts) - 1, -1, -1):
728  dict_value = self.get_dict_value(keys, self.dicts[i])
729  if dict_value != None:
730  return dict_value
731 
732  # not found
733  keys.pop()
734  if len(keys) != 0:
735  raise NotFound(self.lineno(), keytext, self.get_value(keys[0]))
736  raise NotFound(self.lineno(), keytext)
737 
738  def get_dict_value(self, keys, dict):
739  length = len(keys)
740  d = dict
741  for i in range(length):
742  if isinstance(d, DictType) and d.has_key(keys[i]):
743  d = d[keys[i]]
744  else:
745  return None
746  return d
747 
748 
749 #------------------------------------------------------------
750 # Exceptions
751 #------------------------------------------------------------
752 class YATException(Exception):
753  pass
754 
755 class UnknownError(YATException):
756  def __init__(self, lineno):
757  self.lineno = lineno
758  self.value = "Unknown error."
759 
761  def __init__(self, lineno, msg):
762  self.lineno = lineno
763  self.value = "Unmatched block error: " + msg
764 
766  def __init__(self, lineno, msg):
767  self.lineno = lineno
768  self.value = msg
769 
771  def __init__(self, dictkey, dictvalue):
772  self.value = "Specified key is not final element: ",\
773  dictkey, "=>", dictvalue
774 
776  def __init__(self, lineno, directive):
777  self.lineno = lineno
778  self.value = "Invalid directive: \"[" + directive + "]\""
779 
781  def __init__(self, lineno, description):
782  self.lineno = lineno
783  self.value = "Unmatched data and input: ", description
784 
786  def __init__(self, lineno, description, context = None):
787  self.lineno = lineno
788  self.value = "Value not found for: \"" + description + "\"\n"
789  if context != None:
790  try:
791  import yaml
792  self.context = yaml.dump(context, default_flow_style = False)
793  except:
794  pass
795 
796 #------------------------------------------------------------
797 # other functions
798 #------------------------------------------------------------
799 def nesteditem(aList):
800  for anItem in aList:
801  if type(anItem)==list:
802  for subitem in nesteditem(anItem):
803  yield subitem
804  else:
805  yield anItem
806 
807 
808 
809 if __name__ == "__main__":
810  dict = []
811  template = []
812  #------------------------------------------------------------
813  # Example 0
814  #------------------------------------------------------------
815  dict.append({"a": "This is a",
816  "b": {"1": "This is b.1",
817  "2": "This is b.2"}
818  })
819  template.append("""[a]
820 
821 [b.1]
822 
823 [b.2]""")
824 
825  #------------------------------------------------------------
826  # Example 1
827  #------------------------------------------------------------
828  dict.append({"list": [0, 1, 2],
829  "listed_dict": [
830  {"name": "x", "value": "1.0"},
831  {"name": "y", "value": "0.2"},
832  {"name": "z", "value": "0.1"}]})
833  template.append("""[for lst in list]
834 [lst],
835 [endfor]
836 [for lst in listed_dict]
837 [lst.name]: [lst.value]
838 
839 [endfor]""")
840 
841  #------------------------------------------------------------
842  # Example 2
843  #------------------------------------------------------------
844  dict.append({"list": [0,1,2,3,4,5,6,7,8,9,10]})
845  template.append("""[for key in list]
846 [if-index key is 3] [key] is hoge!!
847 [elif-index key is 6] [key] is foo!!
848 [elif-index key is 9] [key] is bar!!
849 [elif-index key is first] [key] is first
850 [elif-index key is last] Omoro-------!!!!
851 [elif-index key is odd] [key] is odd number
852 [elif-index key is even] [key] is even number
853 [endif]
854 [endfor]""")
855 
856  #------------------------------------------------------------
857  # Example 3
858  #------------------------------------------------------------
859  dict.append({"key1": "a", "key2": "b"})
860  template.append("""[if key1 is a]
861 The key1 is "a".
862 [else]
863 This key1 is not "a".
864 [endif]""")
865 
866  #------------------------------------------------------------
867  # Example 4
868  #------------------------------------------------------------
869  dict.append({"key1": "a", "key2": "b"})
870  template.append("""[if-any key1]
871 key1 exists.
872 [endif][if-any key3]
873 key3 exists.
874 [else]
875 key3 does not exists.
876 [endif]""")
877 
878  dict.append({})
879  template.append("""
880 [[]bracket]
881 [# comment]
882 """)
883 
884  import yaml
885  if len(dict) == len(template):
886  for i in range(len(dict)-1,len(dict)):
887  t = Template(template[i])
888  print "-" * 60
889  print "Example:", i
890  print "-" * 60
891  print "Template:\n"
892  print template[i]
893  print "-" * 60
894  print "Dictionary:\n"
895  print yaml.dump(dict[i], default_flow_style=False)
896  print "-" * 60
897  print "Generated Script:\n"
898  print t.get_script()
899  print "-" * 60
900  print "Generated Text:\n"
901  print t.generate(dict[i])
902  print ""
vstring split(const std::string &input, const std::string &delimiter, bool ignore_empty)
Split string by delimiter.
Definition: stringutil.cpp:346
def __init__(self, lineno, description, context=None)
def __init__(self, lineno, directive)
void append(SDOPackage::NVList &dest, const SDOPackage::NVList &src)
Append an element to NVList.
Definition: NVUtil.cpp:354
def __init__(self, dictkey, dictvalue)
def __init__(self, template, begin_mark="\, end_mark="\")
def __init__(self, lineno, description)


openrtm_aist
Author(s): Noriaki Ando
autogenerated on Mon Feb 28 2022 23:00:45