interface_parser/function.py
Go to the documentation of this file.
1 """
2 GTSAM Copyright 2010-2020, Georgia Tech Research Corporation,
3 Atlanta, Georgia 30332-0415
4 All Rights Reserved
5 
6 See LICENSE for the license information
7 
8 Parser classes and rules for parsing C++ functions.
9 
10 Author: Duy Nguyen Ta, Fan Jiang, Matthew Sklar, Varun Agrawal, and Frank Dellaert
11 """
12 
13 from typing import Any, Iterable, List, Union
14 
15 from pyparsing import Optional, ParseResults, delimitedList # type: ignore
16 
17 from .template import Template
18 from .tokens import (COMMA, DEFAULT_ARG, EQUAL, IDENT, LOPBRACK, LPAREN, PAIR,
19  ROPBRACK, RPAREN, SEMI_COLON)
20 from .type import TemplatedType, Type
21 
22 
23 class Argument:
24  """
25  The type and name of a function/method argument.
26 
27  E.g.
28  ```
29  void sayHello(/*`s` is the method argument with type `const string&`*/ const string& s);
30  ```
31  """
32  rule = ((Type.rule ^ TemplatedType.rule)("ctype") #
33  + IDENT("name") #
34  + Optional(EQUAL + DEFAULT_ARG)("default")
35  ).setParseAction(lambda t: Argument(
36  t.ctype, #
37  t.name, #
38  t.default[0] if isinstance(t.default, ParseResults) else None))
39 
40  def __init__(self,
41  ctype: Union[Type, TemplatedType],
42  name: str,
43  default: ParseResults = None):
44  if isinstance(ctype, Iterable):
45  self.ctype = ctype[0] # type: ignore
46  else:
47  self.ctype = ctype
48  self.name = name
49  self.default = default
50  self.parent: Union[ArgumentList, None] = None
51 
52  def __repr__(self) -> str:
53  return self.to_cpp()
54 
55  def to_cpp(self) -> str:
56  """Return full C++ representation of argument."""
57  return '{} {}'.format(repr(self.ctype), self.name)
58 
59 
61  """
62  List of Argument objects for all arguments in a function.
63  """
64  rule = Optional(delimitedList(Argument.rule)("args_list")).setParseAction(
65  lambda t: ArgumentList.from_parse_result(t.args_list))
66 
67  def __init__(self, args_list: List[Argument]):
68  self.args_list = args_list
69  for arg in args_list:
70  arg.parent = self
71  # The parent object which contains the argument list
72  # E.g. Method, StaticMethod, Template, Constructor, GlobalFunction
73  self.parent: Any = None
74 
75  @staticmethod
76  def from_parse_result(parse_result: ParseResults):
77  """Return the result of parsing."""
78  if parse_result:
79  return ArgumentList(parse_result.asList())
80  else:
81  return ArgumentList([])
82 
83  def __repr__(self) -> str:
84  return repr(tuple(self.args_list))
85 
86  def __len__(self) -> int:
87  return len(self.args_list)
88 
89  def names(self) -> List[str]:
90  """Return a list of the names of all the arguments."""
91  return [arg.name for arg in self.args_list]
92 
93  def list(self) -> List[Argument]:
94  """Return a list of the names of all the arguments."""
95  return self.args_list
96 
97  def to_cpp(self) -> List[str]:
98  """Generate the C++ code for wrapping."""
99  return [arg.ctype.to_cpp() for arg in self.args_list]
100 
101 
103  """
104  Rule to parse the return type.
105 
106  The return type can either be a single type or a pair such as <type1, type2>.
107  """
108  _pair = (
109  PAIR.suppress() #
110  + LOPBRACK #
111  + Type.rule("type1") #
112  + COMMA #
113  + Type.rule("type2") #
114  + ROPBRACK #
115  )
116  rule = (_pair ^
117  (Type.rule ^ TemplatedType.rule)("type1")).setParseAction( # BR
118  lambda t: ReturnType(t.type1, t.type2))
119 
120  def __init__(self, type1: Union[Type, TemplatedType], type2: Type):
121  # If a TemplatedType, the return is a ParseResults, so we extract out the type.
122  self.type1 = type1[0] if isinstance(type1, ParseResults) else type1
123  self.type2 = type2
124  # The parent object which contains the return type
125  # E.g. Method, StaticMethod, Template, Constructor, GlobalFunction
126  self.parent: Any = None
127 
128  def is_void(self) -> bool:
129  """
130  Check if the return type is void.
131  """
132  return self.type1.typename.name == "void" and not self.type2
133 
134  def __repr__(self) -> str:
135  return "{}{}".format(
136  self.type1, (', ' + self.type2.__repr__()) if self.type2 else '')
137 
138  def to_cpp(self) -> str:
139  """
140  Generate the C++ code for wrapping.
141 
142  If there are two return types, we return a pair<>,
143  otherwise we return the regular return type.
144  """
145  if self.type2:
146  return "std::pair<{type1},{type2}>".format(
147  type1=self.type1.to_cpp(), type2=self.type2.to_cpp())
148  else:
149  return self.type1.to_cpp()
150 
151 
153  """
154  Rule to parse functions defined in the global scope.
155  """
156  rule = (
157  Optional(Template.rule("template")) + ReturnType.rule("return_type") #
158  + IDENT("name") #
159  + LPAREN #
160  + ArgumentList.rule("args_list") #
161  + RPAREN #
162  + SEMI_COLON #
163  ).setParseAction(lambda t: GlobalFunction(t.name, t.return_type, t.
164  args_list, t.template))
165 
166  def __init__(self,
167  name: str,
168  return_type: ReturnType,
169  args_list: ArgumentList,
170  template: Template,
171  parent: Any = ''):
172  self.name = name
173  self.return_type = return_type
174  self.args = args_list
175  self.template = template
176 
177  self.parent = parent
178  self.return_type.parent = self
179  self.args.parent = self
180 
181  def __repr__(self) -> str:
182  return "GlobalFunction: {}{}({})".format(self.return_type, self.name,
183  self.args)
184 
185  def to_cpp(self) -> str:
186  """Generate the C++ code for wrapping."""
187  return self.name
bool isinstance(handle obj)
Definition: pytypes.h:700
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
str repr(handle h)
Definition: pytypes.h:2265
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2244


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:34:14