1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
use std::fmt;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::str;

use protobuf::descriptor::FileDescriptorProto;

use crate::linked_hash_map::LinkedHashMap;
use crate::parse_and_typecheck::ParsedAndTypechecked;
use crate::proto;
use crate::proto_path::ProtoPath;
use crate::proto_path::ProtoPathBuf;
use crate::pure::convert;
use crate::pure::model;
use crate::FileDescriptorPair;

#[derive(Debug, thiserror::Error)]
enum ParseAndTypeckError {
    #[error("file `{0}` content is not UTF-8")]
    FileContentIsNotUtf8(String),
    #[error("protobuf path `{0}` is not found in import path {1}")]
    FileNotFoundInImportPath(String, String),
    #[error("file `{0}` must reside in include path {1}")]
    FileMustResideInImportPath(String, String),
    #[error("could not read file `{0}`: {1}")]
    CouldNotReadFile(String, io::Error),
}

#[derive(Debug, thiserror::Error)]
#[error("error in `{file}`: {error}")]
struct WithFileError {
    file: String,
    #[source]
    error: anyhow::Error,
}

/// Resolve `.proto` files. `Display` is used for error messages.
pub trait ProtoPathResolver: fmt::Display {
    /// Resolve a `.proto` file.
    ///
    /// Return `None` if a path is unknown, and if a path is a built-in protobuf file,
    /// like `google/protobuf/descriptor.proto`, it will be handled by the library.
    fn resolve(&self, path: &ProtoPath) -> anyhow::Result<Option<ResolvedProtoFile>>;
}

struct Run<R>
where
    R: ProtoPathResolver,
{
    parsed_files: LinkedHashMap<ProtoPathBuf, FileDescriptorPair>,
    resolver: R,
}

impl<R> Run<R>
where
    R: ProtoPathResolver,
{
    fn get_file_and_all_deps_already_parsed(
        &self,
        protobuf_path: &ProtoPath,
        result: &mut LinkedHashMap<ProtoPathBuf, FileDescriptorPair>,
    ) {
        if let Some(_) = result.get(protobuf_path) {
            return;
        }

        let pair = self
            .parsed_files
            .get(protobuf_path)
            .expect("must be already parsed");
        result.insert(protobuf_path.to_proto_path_buf(), pair.clone());

        self.get_all_deps_already_parsed(&pair.parsed, result);
    }

    fn get_all_deps_already_parsed(
        &self,
        parsed: &model::FileDescriptor,
        result: &mut LinkedHashMap<ProtoPathBuf, FileDescriptorPair>,
    ) {
        for import in &parsed.imports {
            self.get_file_and_all_deps_already_parsed(&import.path, result);
        }
    }

    fn add_file_content(
        &mut self,
        protobuf_path: &ProtoPath,
        resolved: &ResolvedProtoFile,
    ) -> anyhow::Result<()> {
        let content = str::from_utf8(&resolved.content)
            .map_err(|_| ParseAndTypeckError::FileContentIsNotUtf8(protobuf_path.to_string()))?;

        let parsed = model::FileDescriptor::parse(&content).map_err(|e| WithFileError {
            file: resolved.path.clone(),
            error: e.into(),
        })?;

        for import in &parsed.imports {
            self.add_imported_file(&import.path)?;
        }

        let mut this_file_deps = LinkedHashMap::new();
        self.get_all_deps_already_parsed(&parsed, &mut this_file_deps);

        let this_file_deps: Vec<_> = this_file_deps.into_iter().map(|(_, v)| v).collect();

        let descriptor = convert::file_descriptor(protobuf_path, &parsed, &this_file_deps)
            .map_err(|e| WithFileError {
                file: resolved.path.clone(),
                error: e.into(),
            })?;

        self.parsed_files.insert(
            protobuf_path.to_proto_path_buf(),
            FileDescriptorPair { parsed, descriptor },
        );

        Ok(())
    }

    fn add_imported_file(&mut self, protobuf_path: &ProtoPath) -> anyhow::Result<()> {
        if let Some(_) = self.parsed_files.get(protobuf_path) {
            return Ok(());
        }

        let resolved = self.resolver.resolve(protobuf_path)?;
        if let Some(resolved) = resolved {
            return self.add_file_content(protobuf_path, &resolved);
        }

        let embedded = match protobuf_path.to_str() {
            "rustproto.proto" => Some(proto::RUSTPROTO_PROTO),
            "google/protobuf/any.proto" => Some(proto::ANY_PROTO),
            "google/protobuf/api.proto" => Some(proto::API_PROTO),
            "google/protobuf/descriptor.proto" => Some(proto::DESCRIPTOR_PROTO),
            "google/protobuf/duration.proto" => Some(proto::DURATION_PROTO),
            "google/protobuf/empty.proto" => Some(proto::EMPTY_PROTO),
            "google/protobuf/field_mask.proto" => Some(proto::FIELD_MASK_PROTO),
            "google/protobuf/source_context.proto" => Some(proto::SOURCE_CONTEXT_PROTO),
            "google/protobuf/struct.proto" => Some(proto::STRUCT_PROTO),
            "google/protobuf/timestamp.proto" => Some(proto::TIMESTAMP_PROTO),
            "google/protobuf/type.proto" => Some(proto::TYPE_PROTO),
            "google/protobuf/wrappers.proto" => Some(proto::WRAPPERS_PROTO),
            _ => None,
        };

        match embedded {
            Some(content) => self.add_file_content(
                protobuf_path,
                &ResolvedProtoFile {
                    path: protobuf_path.to_string(),
                    content: content.as_bytes().to_vec(),
                },
            ),
            None => Err(ParseAndTypeckError::FileNotFoundInImportPath(
                protobuf_path.to_string(),
                format!("{}", self.resolver),
            )
            .into()),
        }
    }
}

pub(crate) fn path_to_proto_path(
    path: &Path,
    includes: &[PathBuf],
) -> anyhow::Result<ProtoPathBuf> {
    for include in includes {
        if include == Path::new(".") && path.is_relative() {
            // Special handling of `.` to allow using `.` as an include path
            // and `foo.proto` as input.
            return ProtoPathBuf::from_path(path);
        }
        match path.strip_prefix(include) {
            Ok(stripped) => return ProtoPathBuf::from_path(stripped),
            Err(_) => continue,
        }
    }
    Err(ParseAndTypeckError::FileMustResideInImportPath(
        path.display().to_string(),
        format!("{:?}", includes),
    )
    .into())
}

/// `.proto` file result provided from the [`ProtoPathResolver`].
pub struct ResolvedProtoFile {
    /// For error reporting.
    pub path: String,
    /// File content.
    pub content: Vec<u8>,
}

fn fs_resolver(includes: &[PathBuf]) -> impl ProtoPathResolver {
    struct Impl {
        includes: Vec<PathBuf>,
    }

    impl fmt::Display for Impl {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{:?}", self.includes)
        }
    }

    impl ProtoPathResolver for Impl {
        fn resolve(&self, proto_path: &ProtoPath) -> anyhow::Result<Option<ResolvedProtoFile>> {
            for include_dir in &self.includes {
                let fs_path = include_dir.join(proto_path.to_path());
                match fs::read_to_string(&fs_path) {
                    Ok(content) => {
                        return Ok(Some(ResolvedProtoFile {
                            path: fs_path.display().to_string(),
                            content: content.into_bytes(),
                        }))
                    }
                    Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
                    Err(e) => {
                        return Err(ParseAndTypeckError::CouldNotReadFile(
                            fs_path.display().to_string(),
                            e,
                        )
                        .into())
                    }
                }
            }
            Ok(None)
        }
    }

    Impl {
        includes: includes.to_vec(),
    }
}

/// Parse `.proto` files using pure Rust implementation.
pub fn parse_and_typecheck(
    includes: &[PathBuf],
    input: &[PathBuf],
) -> anyhow::Result<ParsedAndTypechecked> {
    let mut run = Run {
        parsed_files: LinkedHashMap::new(),
        resolver: fs_resolver(includes),
    };

    let relative_paths = input
        .iter()
        .map(|input| Ok((path_to_proto_path(input, includes)?, input)))
        .collect::<anyhow::Result<Vec<_>>>()?;

    for (proto_path, path) in &relative_paths {
        let content = fs::read_to_string(path)
            .map_err(|e| ParseAndTypeckError::CouldNotReadFile(path.display().to_string(), e))?;
        run.add_file_content(
            proto_path,
            &ResolvedProtoFile {
                path: path.display().to_string(),
                content: content.into_bytes(),
            },
        )?;
    }

    let file_descriptors: Vec<_> = run
        .parsed_files
        .into_iter()
        .map(|(_, v)| v.descriptor)
        .collect();

    Ok(ParsedAndTypechecked {
        relative_paths: relative_paths.into_iter().map(|(p, _)| p).collect(),
        file_descriptors,
    })
}

#[doc(hidden)]
pub fn parse_and_typecheck_custom(
    input: &[ProtoPathBuf],
    resolver: impl ProtoPathResolver,
) -> anyhow::Result<Vec<FileDescriptorProto>> {
    let mut run = Run {
        parsed_files: LinkedHashMap::new(),
        resolver,
    };

    for proto_path in input {
        run.add_imported_file(proto_path)?;
    }

    Ok(run
        .parsed_files
        .into_iter()
        .map(|(_, v)| v.descriptor)
        .collect())
}

#[cfg(test)]
mod test {
    use std::fmt;

    use crate::proto_path::ProtoPath;
    use crate::pure::parse_and_typecheck::ProtoPathResolver;
    use crate::pure::parse_and_typecheck::ResolvedProtoFile;
    use crate::ProtoPathBuf;

    #[test]
    fn parse_and_typecheck_custom() {
        struct ResolverImpl;

        impl fmt::Display for ResolverImpl {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "ResolverImpl")
            }
        }

        impl ProtoPathResolver for ResolverImpl {
            fn resolve(&self, proto_path: &ProtoPath) -> anyhow::Result<Option<ResolvedProtoFile>> {
                if proto_path == "xx.proto" {
                    Ok(Some(ResolvedProtoFile {
                        path: "xx.proto".to_string(),
                        content: "syntax = 'proto3'; message Foo {}".as_bytes().to_vec(),
                    }))
                } else {
                    Ok(None)
                }
            }
        }

        let resolved = super::parse_and_typecheck_custom(
            &[ProtoPathBuf::new("xx.proto".to_owned()).unwrap()],
            ResolverImpl,
        )
        .unwrap();
        assert_eq!(1, resolved.len());
        assert_eq!("Foo", resolved[0].message_type[0].get_name());
    }
}