blob: 6db103405c49d96bd327b8704389d7e0a954ffdb [file] [log] [blame]
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +00001# $Copyright:
2# ----------------------------------------------------------------
3# This confidential and proprietary software may be used only as
4# authorised by a licensing agreement from ARM Limited
5# (C) COPYRIGHT 2015 ARM Limited
6# ALL RIGHTS RESERVED
7# The entire notice above must be reproduced on all authorised
8# copies and copies may only be made to the extent permitted
9# by a licensing agreement from ARM Limited.
10# ----------------------------------------------------------------
11# File: dynamic.py
12# ----------------------------------------------------------------
13# $
14#
15
16"""The idea is to create a wrapper class that
17returns a Type of a Class dynamically created based
18on the input parameters. Similar to a factory design
19pattern
20"""
21from cr2.base import Base
22import re
23from cr2.run import Run
24
25
Javi Merino6f34d902015-02-21 11:39:09 +000026def default_init(self):
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000027 """Default Constructor for the
28 Dynamic MetaClass
29 """
30
31 super(type(self), self).__init__(
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000032 unique_word=self.unique_word,
Kapileshwar Singh7a709132015-03-27 17:45:22 +000033 parse_raw=self.parse_raw
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000034 )
35
36
37class DynamicTypeFactory(type):
38
39 """Override the type class to create
40 a dynamic type on the fly
41 """
42
43 def __new__(mcs, name, bases, dct):
44 """Override the new method"""
45 return type.__new__(mcs, name, bases, dct)
46
47 def __init__(cls, name, bases, dct):
48 """Override the constructor"""
49 super(DynamicTypeFactory, cls).__init__(name, bases, dct)
50
51
52def _get_name(name):
53 """Internal Method to Change camelcase to
54 underscores. CamelCase -> camel_case
55 """
56 return re.sub('(?!^)([A-Z]+)', r'_\1', name).lower()
57
58
Kapileshwar Singh7a709132015-03-27 17:45:22 +000059def register_dynamic(class_name, unique_word, scope="all",
60 parse_raw=False):
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000061 """Create a Dynamic Type and register
62 it with the cr2 Framework"""
63
64 dyn_class = DynamicTypeFactory(
65 class_name, (Base,), {
66 "__init__": default_init,
67 "unique_word": unique_word,
Kapileshwar Singh7a709132015-03-27 17:45:22 +000068 "name": _get_name(class_name),
69 "parse_raw" : parse_raw
Kapileshwar Singhfb8fa1a2015-02-11 17:21:04 +000070 }
71 )
72 Run.register_class(dyn_class, scope)
73 return dyn_class
74
75
76def register_class(cls):
77 """Register a new class implementation
78 Should be used when the class has
79 complex helper methods and does not
80 expect to use the default constructor
81 """
82
83 # Check the argspec of the class
84 Run.register_class(cls)